Skip to main content

NestedForm

Struct NestedForm 

Source
pub struct NestedForm<T>(pub T);
Expand description

Form extractor for bracketed field names, like Rails’ params (post[title], tag_ids[], lines[0][qty]).

axum’s Form only knows flat names (title=...); use it for ordinary forms. NestedForm is for forms that send a list or nested records:

Field nameBecomes
titlethe field title
post[title]the field title of the struct in field post
tag_ids[] (repeated)a Vec with one item per value, in order
lines[0][qty], lines[1][qty]a Vec of structs, sorted by index (Rails’ fields_for / nested attributes)
lines[][qty], lines[][price]a Vec of structs; a name already set in the last item starts a new one

A name sent twice keeps the last value (so a hidden done=0 before the checkbox done=1 works as in Rails). Values are text: numbers and booleans are parsed from it (1/true/on/yes are true, 0, false, off, no and an empty value are false), an empty value is None for an Option, and a single value fills a one-item Vec. Enums with unit variants read their variant name.

On GET and HEAD it reads the query string; otherwise the body, which must be application/x-www-form-urlencoded (2 MB at most, axum’s default limit). A body that does not decode into T (a missing field, a number that is not one, a=1&a[b]=2) is a 400, as an HTML page for browsers (feature html) or JSON for API clients. Pure CPU, no binding call.

§Examples

use ocre::NestedForm;
use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
struct Order {
    customer: Customer,
    #[serde(default)]
    tag_ids: Vec<i64>,
    lines: Vec<Line>,
}

#[derive(Debug, Deserialize, PartialEq)]
struct Customer {
    name: String,
}

#[derive(Debug, Deserialize, PartialEq)]
struct Line {
    product: String,
    qty: u32,
    #[serde(default)]
    remove: bool,
}

let body = "customer[name]=Ada&tag_ids[]=3&tag_ids[]=7\
            &lines[0][product]=Tea&lines[0][qty]=2\
            &lines[1][product]=Cake&lines[1][qty]=1&lines[1][remove]=0&lines[1][remove]=1";
let order: Order = NestedForm::parse(body).unwrap();
assert_eq!(order.customer.name, "Ada");
assert_eq!(order.tag_ids, [3, 7]);
assert_eq!(order.lines[1], Line { product: "Cake".into(), qty: 1, remove: true });

In a handler, like axum’s Form:

use axum::response::Redirect;
use ocre::{NestedForm, Result};

async fn create(NestedForm(order): NestedForm<Order>) -> Result<Redirect> {
    Ok(Redirect::to("/orders"))
}

Tuple Fields§

§0: T

Implementations§

Source§

impl<T: DeserializeOwned> NestedForm<T>

Source

pub fn parse(input: &str) -> Result<T>

Decodes an application/x-www-form-urlencoded string (a body or a query string) with bracketed names.

The rules are those of NestedForm; errors are Error::BadRequest explaining which field failed.

§Examples
use ocre::NestedForm;
use std::collections::BTreeMap;

// `?filter[status]=open&filter[author]=ada` on an index page.
let filter: BTreeMap<String, BTreeMap<String, String>> =
    NestedForm::parse("filter[status]=open&filter[author]=ada").unwrap();
assert_eq!(filter["filter"]["author"], "ada");
assert!(NestedForm::<BTreeMap<String, u32>>::parse("n=many").is_err());

Trait Implementations§

Source§

impl<T: Clone> Clone for NestedForm<T>

Source§

fn clone(&self) -> NestedForm<T>

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<T: Copy> Copy for NestedForm<T>

Source§

impl<T: Debug> Debug for NestedForm<T>

Source§

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

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

impl<T: Default> Default for NestedForm<T>

Source§

fn default() -> NestedForm<T>

Returns the “default value” for a type. Read more
Source§

impl<T: DeserializeOwned, S: Send + Sync> FromRequest<S> for NestedForm<T>

Source§

type Rejection = Response<Body>

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection>

Perform the extraction.

Auto Trait Implementations§

§

impl<T> Freeze for NestedForm<T>
where T: Freeze,

§

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

§

impl<T> Send for NestedForm<T>
where T: Send,

§

impl<T> Sync for NestedForm<T>
where T: Sync,

§

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

§

impl<T> UnsafeUnpin for NestedForm<T>
where T: UnsafeUnpin,

§

impl<T> UnwindSafe for NestedForm<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
§

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

§

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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

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

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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.

§

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

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

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

§

fn vzip(self) -> V