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: StringImplementations§
Source§impl Forms
impl Forms
Sourcepub fn new(csrf_token: &str) -> Self
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.
Sourcepub fn set_honeypot(&mut self, name: &str)
pub fn set_honeypot(&mut self, name: &str)
Registers the honeypot field name injected by the anti-bot middleware.
Sourcepub fn set_url_params(&mut self, path: &StrMap, query: &StrMap)
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).
Sourcepub fn set_renderer(&mut self, renderer: FormRenderer)
pub fn set_renderer(&mut self, renderer: FormRenderer)
Attaches the Tera-based HTML renderer. Required for form.html in templates.
Sourcepub fn set_csp_nonce(&mut self, nonce: &str)
pub fn set_csp_nonce(&mut self, nonce: &str)
Passes the CSP nonce to the renderer so script tags carry the correct nonce attribute.
Sourcepub fn add_js(&mut self, files: &[&str])
pub fn add_js(&mut self, files: &[&str])
Appends JavaScript file paths to the renderer’s js_files list (injected via form.js_files).
Sourcepub fn field_generic(&mut self, field: GenericField)
pub fn field_generic(&mut self, field: GenericField)
Registers a pre-built GenericField. Prefer field for typed fields.
Sourcepub fn field_choices(
&mut self,
name: &str,
label: &str,
choices: Vec<(String, String)>,
)
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.
Sourcepub fn field<T>(&mut self, field_template: &T)
pub fn field<T>(&mut self, field_template: &T)
Registers a typed field (e.g. TextField, NumericField, FileField, …).
Called inside RuniqueForm::register_fields.
Sourcepub fn fill(&mut self, data: &StrMap, method: Method)
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).
Sourcepub fn field_label(&mut self, name: &str, label: &str) -> &mut Self
pub fn field_label(&mut self, name: &str, label: &str) -> &mut Self
Overrides the label of a registered field by name.
Sourcepub fn field_placeholder(&mut self, name: &str, placeholder: &str) -> &mut Self
pub fn field_placeholder(&mut self, name: &str, placeholder: &str) -> &mut Self
Overrides the placeholder of a registered field by name.
Sourcepub fn field_required(&mut self, name: &str, required: bool) -> &mut Self
pub fn field_required(&mut self, name: &str, required: bool) -> &mut Self
Overrides the required constraint of a registered field by name.
Sourcepub fn field_readonly(&mut self, name: &str, readonly: bool) -> &mut Self
pub fn field_readonly(&mut self, name: &str, readonly: bool) -> &mut Self
Sets a registered field as read-only by name.
Sourcepub fn field_disabled(&mut self, name: &str, disabled: bool) -> &mut Self
pub fn field_disabled(&mut self, name: &str, disabled: bool) -> &mut Self
Sets a registered field as disabled by name.
Sourcepub fn field_attr(&mut self, name: &str, key: &str, value: &str) -> &mut Self
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.
Sourcepub fn field_max_size(
&mut self,
name: &str,
size: FileSize,
) -> Result<&mut Self, String>
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.
Sourcepub fn add_value(&mut self, name: &str, value: &str)
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).
Sourcepub fn clear_values(&mut self)
pub fn clear_values(&mut self)
Clears all field values (except CSRF). To be called after reading cleaned data, before a redirect.
Source§impl Forms
impl Forms
Sourcepub async fn is_valid(&mut self) -> Result<bool, ValidationError>
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].
Sourcepub fn has_errors(&self) -> bool
pub fn has_errors(&self) -> bool
Returns true if any field or form-level error is present.
Sourcepub fn errors(&self) -> StrMap
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
impl Forms
Sourcepub fn database_error(&mut self, db_err: &DbErr)
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§
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<F, T> ConvertInto<T> for Fwhere
T: ConvertFrom<F>,
impl<F, T> ConvertInto<T> for Fwhere
T: ConvertFrom<F>,
Source§fn convert_into(self) -> T
fn convert_into(self) -> T
Self to a value of type T.Source§impl<F, T> ConvertTryFrom<F> for Twhere
F: ConvertInto<T>,
impl<F, T> ConvertTryFrom<F> for Twhere
F: ConvertInto<T>,
Source§impl<F, T> ConvertTryInto<T> for Fwhere
T: ConvertTryFrom<F>,
impl<F, T> ConvertTryInto<T> for Fwhere
T: ConvertTryFrom<F>,
Source§type Error = <T as ConvertTryFrom<F>>::Error
type Error = <T as ConvertTryFrom<F>>::Error
Source§fn convert_try_into(self) -> Result<T, <T as ConvertTryFrom<F>>::Error>
fn convert_try_into(self) -> Result<T, <T as ConvertTryFrom<F>>::Error>
Self to a value of type T.impl<T> ErasedDestructor for Twhere
T: 'static,
impl<A, B, T> HttpServerConnExec<A, B> for Twhere
B: Body,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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