Skip to main content

AdminResource

Trait AdminResource 

Source
pub trait AdminResource:
    Send
    + Sync
    + 'static {
    type Model: Model + Policy + Serialize + Default + Send + Sync;
    type Form: DeserializeOwned + Validate + Serialize + Send + 'static;

Show 21 methods // Required methods fn label(&self) -> &str; fn plural_label(&self) -> &str; fn columns(&self) -> Vec<Column>; fn fields(&self) -> Vec<Field>; fn fill(&self, record: &mut Self::Model, form: Self::Form); // Provided methods fn record_title(&self, record: &Self::Model) -> String { ... } fn slug(&self) -> &str { ... } fn navigation_group(&self) -> Option<&str> { ... } fn rules( &self, form: &Self::Form, record: Option<&Self::Model>, v: &mut Validator, ) { ... } fn entries(&self) -> Vec<Entry> { ... } fn filters(&self) -> Vec<Filter<Self::Model>> { ... } fn actions(&self) -> Vec<AdminAction<Self::Model>> { ... } fn creatable(&self) -> bool { ... } fn deletable(&self) -> bool { ... } fn relations(&self) -> Vec<RelationManager> { ... } fn saved( &self, record: &Self::Model, cx: &SaveContext, ) -> impl Future<Output = Result> + Send { ... } fn state_machine(&self) -> Option<MachineInfo> { ... } fn available_transitions( &self, record: &Self::Model, user: &AuthUser, db: &Db, ) -> impl Future<Output = Result<Vec<Available>>> + Send { ... } fn query(&self) -> Query<Self::Model> { ... } fn grid(&self, grid: Grid) -> Grid { ... } fn allows( &self, user: &AuthUser, ability: &str, record: Option<&Self::Model>, ) -> bool { ... }
}
Expand description

A model in the admin panel (Filament’s resources), declared once: the grid’s columns, the form’s fields, its filters and actions, and who may do what (its Policy).

use renox::grid::Column;
use renox::prelude::*;
use renox_admin::{AdminResource, Field};
use serde::{Deserialize, Serialize};

#[derive(Model, Serialize, Default, Clone)]
struct Product { id: i64, name: String, price: i64, active: bool }

impl Policy for Product {
    fn allows(&self, user: &User, ability: &str) -> bool {
        // Everyone in the panel looks; only managers change things.
        matches!(ability, "viewAny" | "view") || user.has_role("manager")
    }
}

#[derive(Deserialize, Serialize, Validate)]
struct ProductForm {
    #[validate(required, max = 100)]
    name: String,
    #[validate(required, min = 0)]
    price: i64,
    active: bool,
}

struct Products;

impl AdminResource for Products {
    type Model = Product;
    type Form = ProductForm;

    fn label(&self) -> &str { "Product" }
    fn plural_label(&self) -> &str { "Products" }

    fn columns(&self) -> Vec<Column> {
        vec![
            Column::text("name", "Name").searchable(),
            Column::money("price", "Price"),
            Column::bool("active", "Active"),
        ]
    }

    fn fields(&self) -> Vec<Field> {
        vec![
            Field::text("name", "Name").required(),
            Field::money("price", "Price").required(),
            Field::toggle("active", "Active").default_value(true),
        ]
    }

    fn fill(&self, product: &mut Product, form: ProductForm) {
        product.name = form.name;
        product.price = form.price;
        product.active = form.active;
    }
}

Required Associated Types§

Source

type Model: Model + Policy + Serialize + Default + Send + Sync

The model the resource manages. Default gives the record a create page starts from, and the one list-level abilities are asked about.

Source

type Form: DeserializeOwned + Validate + Serialize + Send + 'static

The form of the create and edit pages, checked with its own rules (Valid<T>). Serialize refills it after rules fails (passwords aren’t refilled).

Required Methods§

Source

fn label(&self) -> &str

One record’s name: “Product”.

Source

fn plural_label(&self) -> &str

Several records’ name, in the navigation and the list’s title: “Products”.

Source

fn columns(&self) -> Vec<Column>

The list’s columns, left to right (renox::grid). Make some .searchable() for the list’s search box.

Source

fn fields(&self) -> Vec<Field>

The create and edit pages’ fields, in order.

Source

fn fill(&self, record: &mut Self::Model, form: Self::Form)

Copies a valid form into the record, before it is saved (a new record starts from Default).

Provided Methods§

Source

fn record_title(&self, record: &Self::Model) -> String

What a record’s view and edit pages call it: “Product #7” by default; its name reads better (product.name.clone()).

Source

fn slug(&self) -> &str

The resource’s part of the address and of the route names (/admin/products, admin.products.index): letters, digits, _ and -. The model’s table by default.

Source

fn navigation_group(&self) -> Option<&str>

A heading the navigation puts the resource under (“Shop”).

Source

fn rules( &self, form: &Self::Form, record: Option<&Self::Model>, v: &mut Validator, )

Rules that need the record being edited (None while creating), checked after the form’s own, e.g. a unique value that may stay the record’s own: v.field("sku", &form.sku).unique("products", "sku") followed by .ignore(record.id) when there is one.

Source

fn entries(&self) -> Vec<Entry>

The details of a record’s view page. Without any, the resource has no view page and its rows open the edit page. By default, an entry per column (Entry::from_column).

Source

fn filters(&self) -> Vec<Filter<Self::Model>>

Named filters over the list, shown as tabs above it (“Active”, “Low stock”); the grid’s columns filter on their own too.

Source

fn actions(&self) -> Vec<AdminAction<Self::Model>>

The resource’s own actions on selected rows (and, with AdminAction::row, on one row).

Source

fn creatable(&self) -> bool

Whether the panel offers a create page and a “New” button. Return false for a resource that is only edited (a settings row, a record other code creates): the create address answers 404.

Source

fn deletable(&self) -> bool

Whether records can be deleted from the panel (the delete buttons, the bulk delete, the trash and its restore). Return false for an edit-only resource: those addresses answer 404.

Source

fn relations(&self) -> Vec<RelationManager>

Child rows managed from a record’s own pages (Filament’s relation managers): its variants, photos or tags, each a tab of the record with its own list. See RelationManager.

Source

fn saved( &self, record: &Self::Model, cx: &SaveContext, ) -> impl Future<Output = Result> + Send

Runs after the create or edit page saved a record (Filament’s afterSave), with who saved it and, on an edit, the record as it was (SaveContext::previous): audit an exact price change, refresh search keywords. An error answers the request with it, though the record is saved by then; do the work in a transaction of your own when it must go in with the record.

struct Products;

impl AdminResource for Products {
    // ...
    async fn saved(&self, product: &Product, cx: &SaveContext) -> Result {
        let before = cx.previous.as_ref().and_then(|old| old["price"].as_i64());
        if before.is_some_and(|before| before != product.price) {
            // Write the audit entry: who (`cx.user`), which product, from, to.
            let _ = (&cx.state.db, &cx.user);
        }
        Ok(())
    }
}
Source

fn state_machine(&self) -> Option<MachineInfo>

The model’s state machine, for a read-only diagram on the view page: Some(renox::state_machine::info_of::<Order>()). Pair it with available_transitions for the buttons and AdminAction::transitions for what they run. None by default.

Source

fn available_transitions( &self, record: &Self::Model, user: &AuthUser, db: &Db, ) -> impl Future<Output = Result<Vec<Available>>> + Send

The transitions user may run on record now, shown as buttons on its view page (each posts to the action of the same name, see AdminAction::transitions). For a state machine model, return record.available(user, db).await. None by default.

Source

fn query(&self) -> Query<Self::Model>

Every query the panel runs for this resource starts here: the model’s query (with its default scope) by default. Narrow it to what the panel may ever show.

Source

fn grid(&self, grid: Grid) -> Grid

Changes the list’s grid after the panel built it from the columns, e.g. grid.sort_by("name").per_page(50).groups(&["status"]).

Source

fn allows( &self, user: &AuthUser, ability: &str, record: Option<&Self::Model>, ) -> bool

Whether user may do ability (viewAny, view, create, update, delete, deleteAny, restore, restoreAny, forceDelete, forceDeleteAny, or an action’s own) on record. By default, the model’s Policy after App::gate_before; when there’s no record (the list, the create page, what the list offers), the policy is asked about a blank record (Self::Model::default()).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§