Skip to main content

ModelChoiceField

Struct ModelChoiceField 

Source
pub struct ModelChoiceField<T: FormModel> {
    pub name: String,
    pub required: bool,
    pub error_messages: HashMap<String, String>,
    pub widget: Widget,
    pub help_text: String,
    pub initial: Option<Value>,
    pub queryset: Vec<T>,
    pub empty_label: Option<String>,
    /* private fields */
}
Expand description

A field for selecting a single model instance from a queryset

This field displays model instances as choices in a select widget.

Fields§

§name: String

The field name used as the form data key.

§required: bool

Whether a selection is required.

§error_messages: HashMap<String, String>

Custom error messages keyed by error type.

§widget: Widget

The widget type used for rendering this field.

§help_text: String

Help text displayed alongside the field.

§initial: Option<Value>

Optional initial (default) value for the field.

§queryset: Vec<T>

The list of model instances to choose from.

§empty_label: Option<String>

Label for the empty/default option (e.g., “Select one…”).

Implementations§

Source§

impl<T: FormModel> ModelChoiceField<T>

Source

pub fn new(name: impl Into<String>, queryset: Vec<T>) -> Self

Create a new ModelChoiceField

§Examples
use reinhardt_forms::fields::ModelChoiceField;
use reinhardt_forms::FormField;
use reinhardt_forms::FormModel;
use serde_json::{json, Value};

// Define a simple Category model
#[derive(Clone)]
struct Category {
    id: i32,
    name: String,
}

impl FormModel for Category {
    fn field_names() -> Vec<String> {
        vec!["id".to_string(), "name".to_string()]
    }

    fn get_field(&self, name: &str) -> Option<Value> {
        match name {
            "id" => Some(json!(self.id)),
            "name" => Some(json!(self.name)),
            _ => None,
        }
    }

    fn set_field(&mut self, _name: &str, _value: Value) -> Result<(), String> {
        Ok(())
    }

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

// Create a queryset with sample categories
let categories = vec![
    Category { id: 1, name: "Technology".to_string() },
    Category { id: 2, name: "Science".to_string() },
];

let field = ModelChoiceField::new("category", categories);
assert_eq!(field.name(), "category");
assert!(FormField::required(&field));
Source

pub fn required(self, required: bool) -> Self

Sets whether a selection is required.

Source

pub fn help_text(self, text: impl Into<String>) -> Self

Sets the help text displayed alongside the field.

Source

pub fn initial(self, value: Value) -> Self

Sets the initial (default) value.

Source

pub fn empty_label(self, label: Option<String>) -> Self

Sets the label for the empty/default option.

Source

pub fn error_message( self, error_type: impl Into<String>, message: impl Into<String>, ) -> Self

Overrides the error message for a specific error type.

Trait Implementations§

Source§

impl<T: FormModel> FormField for ModelChoiceField<T>

Source§

fn name(&self) -> &str

Returns the field’s name used as the form data key.
Source§

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

Returns the human-readable label, if set.
Source§

fn widget(&self) -> &Widget

Returns the widget type used for HTML rendering.
Source§

fn required(&self) -> bool

Returns whether this field must have a non-empty value.
Source§

fn initial(&self) -> Option<&Value>

Returns the initial (default) value for this field, if any.
Source§

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

Returns optional help text displayed alongside the field.
Source§

fn clean(&self, value: Option<&Value>) -> FieldResult<Value>

Validates and cleans the submitted value, returning the cleaned result.
Source§

fn has_changed(&self, initial: Option<&Value>, data: Option<&Value>) -> bool

Check if the field value has changed from its initial value
Source§

fn error_messages(&self) -> HashMap<ErrorType, String>

Get custom error messages for this field

Auto Trait Implementations§

§

impl<T> Freeze for ModelChoiceField<T>

§

impl<T> RefUnwindSafe for ModelChoiceField<T>
where T: RefUnwindSafe,

§

impl<T> Send for ModelChoiceField<T>

§

impl<T> Sync for ModelChoiceField<T>

§

impl<T> Unpin for ModelChoiceField<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for ModelChoiceField<T>

§

impl<T> UnwindSafe for ModelChoiceField<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.