Skip to main content

Forms

Struct Forms 

Source
pub struct Forms {
    pub fields: FieldsMap,
    pub errors: Vec<String>,
    pub session_csrf_token: String,
    /* private fields */
}
Expand description

Container of form fields with validation and HTML rendering

§Utilisation manuelle du formulaire

ⓘ
use runique::prelude::*;
use runique::forms::{Forms, fields::text::TextField, fields::number::NumericField};

pub struct RegisterForm {
    pub form: Forms,
}

impl RuniqueForm for RegisterForm {
    fn register_fields(form: &mut Forms) {
        form.field(&TextField::text("username").label("Nom d'utilisateur").required());
        form.field(&TextField::email("email").label("Email").required());
        form.field(&NumericField::integer("age").label("Âge"));
        form.field(&TextField::password("password").label("Mot de passe").required());
    }
    impl_form_access!();
}

async fn register_handler(mut request: Request) -> AppResult<Response> {
    let form: RegisterForm = request.form();

    let validated = match ValidationForm::try_new(form, &request).await {
        Ok(validated) => validated,
        Err(form) => {
            // GET (rien soumis) ou soumission invalide — ré-afficher avec les erreurs
            context_update!(request => { "form" => &form });
            return request.render("register.html");
        }
    };

    let username = validated.cleaned_string("username");
    let email = validated.cleaned_string("email");
    let age = validated.cleaned_i32("age");

    // Logique métier...

    Ok(Redirect::to("/success").into_response())
}

request.form() construit le formulaire, extrait le body et vérifie le CSRF en coulisses — pas de Forms::new(&csrf_token) ni de set_renderer() manuel. ValidationForm::try_new(form, &request) remplace le if ctx.is_post() { form.fill(&data); if form.is_valid()... } : il dispatche lui-même sur la méthode HTTP (allow_get/allow_post) puis valide.

§Récupération des valeurs

Les accesseurs cleaned_* renvoient toujours un Option<T> (le champ peut être absent, vide, ou invalide) :

ⓘ
// Chaîne de caractères
let username: Option<String> = form.cleaned_string("username");

// Entiers et décimaux
let age: Option<i32> = form.cleaned_i32("age");
let score: Option<f64> = form.cleaned_f64("score");

// Booléen
let active: Option<bool> = form.cleaned_bool("active");

// Dates
let birthday: Option<chrono::NaiveDate> = form.cleaned_naive_date("birthday");

Fields§

§fields: FieldsMap§errors: Vec<String>§session_csrf_token: String

Implementations§

Source§

impl Forms

Source

pub fn new(csrf_token: &str) -> Self

Creates a Forms container pre-loaded with a CSRF hidden field set to csrf_token. The CSRF token is validated upstream by the Prisme pipeline — set_expected_value is not called here.

Source

pub fn set_honeypot(&mut self, name: &str)

Registers the honeypot field name injected by the anti-bot middleware.

Source

pub fn set_url_params(&mut self, path: &StrMap, query: &StrMap)

Injects path and query parameters so cleaned_* methods can read them (GET search forms).

Source

pub fn set_renderer(&mut self, renderer: FormRenderer)

Attaches the Tera-based HTML renderer. Required for form.html in templates.

Source

pub fn set_csp_nonce(&mut self, nonce: &str)

Passes the CSP nonce to the renderer so script tags carry the correct nonce attribute.

Source

pub fn add_js(&mut self, files: &[&str])

Appends JavaScript file paths to the renderer’s js_files list (injected via form.js_files).

Source

pub fn field_generic(&mut self, field: GenericField)

Registers a pre-built GenericField. Prefer field for typed fields.

Source

pub fn field_choices( &mut self, name: &str, label: &str, choices: Vec<(String, String)>, )

Replaces a field with a ChoiceField populated with the given options. Preserves the current value (pre-selects the matching option) and the required flag. Used by the admin daemon to inject FK select options loaded from the DB.

Source

pub fn field<T>(&mut self, field_template: &T)
where T: FormField + Clone + Into<GenericField> + 'static,

Registers a typed field (e.g. TextField, NumericField, FileField, …). Called inside RuniqueForm::register_fields.

Source

pub fn fill(&mut self, data: &StrMap, method: Method)

Fills the form fields from a data map. If allow_password is false, password fields are ignored (GET security). In PATCH mode (admin edit), password fields have their required constraint relaxed: empty value = keep existing (NotSet DB side).

Source

pub fn field_label(&mut self, name: &str, label: &str) -> &mut Self

Overrides the label of a registered field by name.

Source

pub fn field_placeholder(&mut self, name: &str, placeholder: &str) -> &mut Self

Overrides the placeholder of a registered field by name.

Source

pub fn field_required(&mut self, name: &str, required: bool) -> &mut Self

Overrides the required constraint of a registered field by name.

Source

pub fn field_readonly(&mut self, name: &str, readonly: bool) -> &mut Self

Sets a registered field as read-only by name.

Source

pub fn field_disabled(&mut self, name: &str, disabled: bool) -> &mut Self

Sets a registered field as disabled by name.

Source

pub fn field_attr(&mut self, name: &str, key: &str, value: &str) -> &mut Self

Sets an arbitrary HTML attribute on a registered field by name.

Source

pub fn field_max_size( &mut self, name: &str, size: FileSize, ) -> Result<&mut Self, String>

Overrides max_size for a file field. Returns Err if it exceeds the model ceiling.

Source

pub fn add_value(&mut self, name: &str, value: &str)

Forces a value on a named field, bypassing fill(). Also marks the form as submitted if the value is non-empty. Use this for fields skipped by fill() (e.g. password hash pre-computed before POST parsing).

Source

pub fn clear_values(&mut self)

Clears all field values (except CSRF). To be called after reading cleaned data, before a redirect.

Source

pub async fn finalize(&mut self) -> Result<(), String>

Runs each field’s finalize step (e.g. moving an uploaded file to its destination, hashing a password) in registration order. Returns the first error encountered, if any.

Source§

impl Forms

Source

pub async fn is_valid(&mut self) -> Result<bool, ValidationError>

Runs all field validators in order. Returns Ok(false) if the form was force-invalidated (honeypot). Used internally by [RuniqueForm::is_valid].

Source

pub fn has_errors(&self) -> bool

Returns true if any field or form-level error is present.

Source

pub fn errors(&self) -> StrMap

Collects all current field and global errors into a map keyed by field name, with a "global" entry for form-level errors (see FormValidator::collect_errors).

Source§

impl Forms

Source

pub fn render(&self) -> Result<String, String>

Renders the form to HTML via the attached renderer. Fails if no renderer was attached with Forms::set_renderer.

Source§

impl Forms

Source

pub fn database_error(&mut self, db_err: &DbErr)

Translates a database error into a user-facing form error. A unique/duplicate-key violation is attributed to the offending field when it can be identified from the error message, otherwise it is added as a global error; any other error is added as a global error too.

Trait Implementations§

Source§

impl Clone for Forms

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Forms

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serialize for Forms

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Forms

§

impl !UnwindSafe for Forms

§

impl Freeze for Forms

§

impl Send for Forms

§

impl Sync for Forms

§

impl Unpin for Forms

§

impl UnsafeUnpin for Forms

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<F, T> ConvertInto<T> for F
where T: ConvertFrom<F>,

Source§

fn convert_into(self) -> T

Infallibly converts a value of type Self to a value of type T.
Source§

impl<F, T> ConvertTryFrom<F> for T
where F: ConvertInto<T>,

Source§

type Error = !

The type of an error that can occur during a conversion. Read more
Source§

fn convert_try_from(value: F) -> Result<T, !>

Fallibly converts a value of type F to a value of type Self.
Source§

impl<F, T> ConvertTryInto<T> for F
where T: ConvertTryFrom<F>,

Source§

type Error = <T as ConvertTryFrom<F>>::Error

The type of an error that can occur during a conversion. Read more
Source§

fn convert_try_into(self) -> Result<T, <T as ConvertTryFrom<F>>::Error>

Fallibly converts a value of type Self to a value of type T.
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ServiceExt for T

Source§

fn compression(self) -> Compression<Self>
where Self: Sized,

Compresses response bodies. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
Source§

fn override_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request. Read more
Source§

fn append_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Append a header into the request. Read more
Source§

fn insert_request_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request, if the header is not already present. Read more
Source§

fn override_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response. Read more
Source§

fn append_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Append a header into the response. Read more
Source§

fn insert_response_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response, if the header is not already present. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more