Actions
An action is a mutation beyond create, update and delete. A record action runs on records: a button on each row, in the header of a record’s detail and edit pages, or an entry in the bulk bar for the selection. A header action runs on no record: a button in the header of a resource’s list or of a custom page.
Record actions
A record action is a type implementing Action<R>,
added to the def with ResourceDef::action. Its NAME is its URL segment and the name policies
answer for, run holds the write, and declare returns an
ActionDef with everything else,
each setting defaulted, as a resource’s declare returns its ResourceDef:
#![allow(unused)]
fn main() {
pub(crate) struct Publish;
impl Action<PostResource> for Publish {
type Input = ();
const NAME: &'static str = "publish";
fn declare() -> ActionDef<PostResource> {
ActionDef::new().can_run(|_cx, post: &Post| post.status != PostStatus::Published)
}
async fn run(
_cx: &Cx,
posts: &[Post],
_: (),
ex: &mut dyn toasty::Executor,
) -> Result<tablo::Outcome, tablo::WriteError<()>> {
Post::filter(filter_keys(posts))
.update()
.status(PostStatus::Published)
.exec(ex)
.await?;
Ok(tablo::Outcome::done())
}
}
impl Resource for PostResource {
// …
fn declare() -> ResourceDef<Self> {
ResourceDef::new()
// …
.action::<Publish>()
.action::<ChangeStatus>()
.header_action::<PublishDrafts>()
}
}
}
run holds only the write. filter_keys(posts)
selects the records it receives, so one statement publishes the whole selection. The framework owns everything around it, as it does for a delete: the
route and its CSRF check, the transaction the records load in and run writes through, the policy
checks on every record, the hooks, and the success notification. The
Action page lists each step, and
what a refused record or selection answers.
Where it shows
ActionDef::places says where the button renders: each row, the detail and edit pages’ headers, the
bulk bar, or any combination of them, by default all four. An action for the detail page and the
bulk bar only declares:
#![allow(unused)]
fn main() {
fn declare() -> ActionDef<PostResource> {
ActionDef::new()
// On the detail page and the bulk bar, not on each row or the edit page.
.places(Places::DETAIL.with(Places::BULK))
.label("Change status")
}
}
Places names each place, and
ActionDef::places
says which routes serve an action and which places no page renders. A run from a record’s page
lands back on it, so an action that hides the record from the list, such as an archive, belongs
on rows and the bulk bar.
A bulk action runs on the rows checked. On a list whose rows span pages, the bulk bar also offers
Select all matching, which runs it on every record the list’s search and filters select, up
to Limits::bulk_records.
Who runs it
One question decides, Run on the record, and two parties answer it:
- the policy, which each panel mounts its own, says who may run the action:
RunAny { action: NAME }for the resource at all, thenRunfor a given record; - the def’s
can_runsays what the action itself takes, on every panel: a published post refuses “publish”.
The button, the route and can::<R>(cx, Ability::Run { .. }) in your own code all ask both, so
they agree.
A record can_run refuses hides the button, unless disabled_reason says why: the button then
shows disabled, with the reason on hover. A record the policy refuses never shows it, so the
reason never tells a user what the policy refuses them.
Put who may act in the policy: a rule in can_run holds on every panel and no panel can lift it.
A panel that mounts the resource with ReadOnly offers none of its actions and refuses their
POSTs (Policy).
What a run returns
run returns an Outcome, which
says what the response does once the write commits. Outcome::done() keeps the defaults: the
success notification, landing back where the action ran from. A “duplicate” action reports its
own message and opens the copy it made:
#![allow(unused)]
fn main() {
let outcome = Outcome::done().notify(Notification::success(format!("Duplicated {}", post.title)));
Ok(match tablo::url::edit::<PostResource>(cx, ©) {
Some(edit) => outcome.redirect(edit),
None => outcome,
})
}
A file to download is a redirect to an app route that serves it.
A destructive action’s def calls confirm() to ask first through the delete’s confirmation
dialog, or confirmation(question) to word its question too. icon puts an icon before the
button’s label wherever it renders, and color(Color::Danger) tints the button as Delete’s is.
label replaces the text derived from NAME, and label_for and icon_for change them on one
record, such as “Deactivate” on an active account and “Activate” on another. A header action’s
HeaderActionDef declares
the same, without the per-record closures.
Header actions
A header action acts on no record: “publish every draft”, “recount the tags”, “clear the cache”.
It is a type implementing HeaderAction:
#![allow(unused)]
fn main() {
/// Publishes every draft, from the post list's header.
pub(crate) struct PublishDrafts;
impl HeaderAction for PublishDrafts {
type Input = ();
const NAME: &'static str = "publish-drafts";
fn declare() -> HeaderActionDef {
HeaderActionDef::new()
.confirm()
// A page has no policy: the action asks the post resource's own, wherever it is
// declared.
.can_run(|cx| can::<PostResource>(cx, Ability::RunHeader { action: Self::NAME }))
}
async fn run(
cx: &Cx,
_: (),
ex: &mut dyn toasty::Executor,
) -> Result<tablo::Outcome, tablo::WriteError<()>> {
// No record is loaded: the action scopes its own query to the request's tenant.
let drafts = scoped_query::<PostResource>(cx)?
.filter(Post::fields().status().eq(PostStatus::Draft))
.exec(&mut *ex)
.await?;
// The tenant's drafts are unbounded: one statement per chunk keeps each one bounded.
for chunk in drafts.chunks(500) {
Post::filter(filter_keys(chunk))
.update()
.status(PostStatus::Published)
.exec(&mut *ex)
.await?;
}
Ok(tablo::Outcome::done())
}
}
}
ResourceDef::header_action::<A>() puts its button in the header of the resource’s list, as the
post resource above does with PublishDrafts. The policy decides who runs it through ViewAny,
since the button is on the list, and
RunHeader, which
ability.is_header_action::<PublishDrafts>() matches. It is an ability of its own because a
policy that grants every record action and checks Run per record must not grant a header action
by accident: no record is there to check.
For the same reason, nothing scopes a header action to the request’s tenant: an action over a
tenant’s records reads them through scoped_query, as PublishDrafts does.
A page declares its header actions with
PageDef::header_action::<A>(). The default render shows their buttons in the page’s header; a
page that writes its own places them with
header_action_buttons::<Self>(cx):
#![allow(unused)]
fn main() {
pub struct MaintenancePage;
impl Page for MaintenancePage {
fn declare() -> PageDef {
PageDef::new().header_action::<PublishDrafts>()
}
}
}
An action whose button belongs in the page’s content, such as a plan card’s Subscribe that posts
the plan it offers, is declared with PageDef::action::<A>() instead: the page serves its route
and leaves it out of the header, and the page or one of its widgets places its button with
header_action_button::<Page, A>(cx, &input).
A page has no policy: its header actions run for whoever may open it. An action that writes a
resource’s records asks that resource’s policy in its own can_run, as PublishDrafts does, so
it runs for the same users from the list and from the page.
Asking for input
An action names what it asks for before it runs as type Input: () for nothing, or a struct
deriving FormInput, which run
receives parsed. A record action and a header action ask the same way:
#![allow(unused)]
fn main() {
/// What changing a post's status asks for.
#[derive(FormInput)]
pub(crate) struct StatusChange {
#[form(options)]
pub status: PostStatus,
#[form(label = "Feature on the home page")]
pub featured: bool,
}
pub(crate) struct ChangeStatus;
impl Action<PostResource> for ChangeStatus {
type Input = StatusChange;
const NAME: &'static str = "change-status";
fn declare() -> ActionDef<PostResource> {
ActionDef::new()
// On the detail page and the bulk bar, not on each row or the edit page.
.places(Places::DETAIL.with(Places::BULK))
.label("Change status")
}
fn validate_input(_cx: &Cx, change: &StatusChange) -> FieldErrors<StatusChange> {
let mut errors = FieldErrors::<StatusChange>::new();
if change.featured && change.status == PostStatus::Draft {
errors.add(|f| f.featured, "Only a published post is featured");
}
errors
}
async fn run(
_cx: &Cx,
posts: &[Post],
change: StatusChange,
ex: &mut dyn toasty::Executor,
) -> Result<tablo::Outcome, tablo::WriteError<StatusChange>> {
Post::filter(filter_keys(posts))
.update()
.status(change.status)
.featured(change.featured)
.exec(ex)
.await?;
Ok(tablo::Outcome::done())
}
}
}
Its button opens the input’s form in a dialog over the page instead of running. The derive picks
each field’s control and its required mark as a record form does; FormInput lists its field
attributes and the names an input may not use.
A dialog that runs the action two ways, such as Ship and Ship and notify, keeps one action and
gives its input a bool field the second button checks:
fn submits(submits: Submits<Shipping>) -> Submits<Shipping> { submits.add("Ship and notify", |f| f.notify) }.
The dialog renders no checkbox for notify, so the action’s own button posts it false and the
second button true, and run reads which one ran it. Both go through the same route and
checks; Submits has the rules.
A refusal lands on the input, never on a half-written record. validate_input refuses before the
transaction opens and sees no record, as ChangeStatus refuses to feature a draft. Its errors
are keyed by the input, FieldErrors::<StatusChange>::new(), and each picks the field it refuses
by name, errors.add(|f| f.featured, ".."), so a renamed field fails to compile rather than render
no message. A rule that reads the database refuses from run with
Err(WriteError::<StatusChange>::field(|f| f.featured, "..")), keyed by the input too, and the
transaction rolls back what run wrote. Either way the input renders as a page with the error
under its control. A reason that names no field declines instead, with
Err(WriteError::declined("..")): the transaction rolls back and the message flashes.
Names
An action’s NAME is its URL segment. A name that is not one segment does not compile, and
mounting the panel refuses a name two actions of one resource, or two header actions of one page,
share.