Update README.md

This commit is contained in:
Mitchell Marino 2024-03-20 23:17:34 +00:00
parent fbe746702a
commit fb44b5d303

View File

@ -1,4 +1,64 @@
# leptos_form_tool # leptos_form_tool
A tool for making forms in leptos. A declaritive way to create forms for [leptos](https://leptos.dev/).
leptos_form_tool allows you to define forms in a declaritive way, without specifying how to render each component. You define what controls and visual components the form should have, as well as how to parse and validate the data. That form definition can then be used to render a `View` for the form, or create a Validator so the client and server can both check the integrity of the data in the same way, without duplicating code.
The rendering of the form controls are defined seperatly from the form itself. This sepperation allows different styles to be swapped in and out, relativly easily and helps reduce code duplication. A particular style can be created by creating a type that implements the FormStyle trait. This FormStyle trait specifies functions for defining all the common form controls such as TextInput, Select, RadioButtons, etc. leptos_form_tool also support custom components if you want more controls than the just the common ones. Custom controls natrually cannot be fully styled with by the FormStyle.
An implmentation of FormStyle might have some variables that should be defined on a per-component basis. Take, for example, a FormStyle that renders it's controls in a grid (like TWGridFormStyle). We would like to be able to define a width for how many columns in the grid that a control will take up. For this, the FormStyle also defines a type for it's attributes:
```rust
pub enum TWGridFormAttributes {
Width(u32),
}
```
With this, you add these styling attributes to components with the `style()` method.
Here is an example of how a form can be defined:
```rust
// all FormData must implement Default and must be 'static
#[derive(Default)]
// this struct should contain all the data that needs to be submitted.
struct MyFormData {
name: String,
age: u32,
}
// now implment the FormData trait
impl FormData for MyFormData {
// the form style must be decided now, as the available attributes depend on the FormStyle
type Style = TWGridFormStyle;
fn build_form(FormBuilder fb) -> Form {
fb
.heading(|h| h.title("Tell Me About Yourself"))
.text_input(|t| {
t.label("Name")
.placeholder("Name")
.parse_fn(|name, form_data| Ok(form_data.name = name))
.validation_fn(|fd| {
if fd.name.is_empty() {
Err("Name is required")
} else if fd.name.len() >= 32 {
Err("Name must be shorter than 32 characters")
} else {
Ok(())
}
})
})
.text_input(|t| {
t.label("age")
.placeholder("age")
.parse_fn(|age, form_data| { Ok(form_data.age = age.parse().map_err(|e| e.to_string())?)}
.validation_fn(|form_data| {
if form_data.age > 99 {
Err("Please enter an age <= 99")
} else {
Ok(())
}
})
})
.submit(|s| s.text("Submit"))
}
}
```