Skip to main content

FormModel

Trait FormModel 

Source
pub trait FormModel: Send + Sync {
    // Required methods
    fn field_names() -> Vec<String>;
    fn get_field(&self, name: &str) -> Option<Value>;
    fn set_field(&mut self, name: &str, value: Value) -> Result<(), String>;
    fn save(&mut self) -> Result<(), String>;

    // Provided methods
    fn field_type(_name: &str) -> Option<FieldType> { ... }
    fn validate(&self) -> Result<(), Vec<String>> { ... }
    fn to_choice_label(&self) -> String { ... }
    fn to_choice_value(&self) -> String { ... }
}
Expand description

Trait for models that can be used with ModelForm

This trait is specifically for form models. For ORM models, use reinhardt_db::orm::Model.

Required Methods§

Source

fn field_names() -> Vec<String>

Get the model’s field names

Source

fn get_field(&self, name: &str) -> Option<Value>

Get a field value by name

Source

fn set_field(&mut self, name: &str, value: Value) -> Result<(), String>

Set a field value by name

Source

fn save(&mut self) -> Result<(), String>

Save the model to the database

Provided Methods§

Source

fn field_type(_name: &str) -> Option<FieldType>

Get field type metadata for form field inference

§Examples
fn field_type(name: &str) -> Option<FieldType> {
    match name {
        "name" => Some(FieldType::Char { max_length: Some(100) }),
        "email" => Some(FieldType::Email),
        "age" => Some(FieldType::Integer),
        _ => None,
    }
}
Source

fn validate(&self) -> Result<(), Vec<String>>

Run model-level (cross-field) validation hook.

This is an opt-in extension point invoked by ModelForm::is_valid after per-field validation has already succeeded. The default implementation intentionally performs no extra validation and returns Ok(()); per-field validation is fully handled by the form’s crate::Form::is_valid pipeline.

Implementers SHOULD override this method when they need cross-field invariants (e.g. “end_date must be after start_date”) that cannot be expressed at the individual field level.

Returns Ok(()) when the model passes all cross-field invariants, or Err(messages) with one or more human-readable error messages.

Source

fn to_choice_label(&self) -> String

Convert model instance to a choice label for display in forms

Default implementation returns the string representation of the primary key. Override this method to provide custom display labels.

§Examples
fn to_choice_label(&self) -> String {
    format!("{} - {}", self.id, self.name)
}
Source

fn to_choice_value(&self) -> String

Get the primary key value as a string for form field validation

Default implementation uses the “id” field.

§Examples
fn to_choice_value(&self) -> String {
    self.id.to_string()
}

Dyn Compatibility§

This trait is not dyn compatible.

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

Implementors§