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>>

Validate the model

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", so this trait is not object safe.

Implementors§