✨ Serve the PageTop guides with pagetop-mdbook
Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.
Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.
Move the configuration to config/common.toml and translate the README
to English.
This commit is contained in:
parent
e41e71cc78
commit
1a41a456d4
80 changed files with 14112 additions and 1218 deletions
186
doc/v0.6/es/src/how-to/forms.md
Normal file
186
doc/v0.6/es/src/how-to/forms.md
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
# Crear y procesar formularios
|
||||
|
||||
**Objetivo:** construir un formulario accesible, recibir sus datos en el servidor, validarlos y
|
||||
responder sin que una recarga lo reenvíe.
|
||||
|
||||
## 1. Construye el formulario
|
||||
|
||||
Un formulario se construye con `Form` y sus campos, que generan el HTML accesible (etiquetas,
|
||||
textos de ayuda, atributos ARIA) por ti.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
fn contact_form() -> Form {
|
||||
Form::new()
|
||||
.with_id("contact")
|
||||
.with_action("/contact")
|
||||
.with_method(form::Method::Post)
|
||||
.with_child(
|
||||
form::input::Field::text()
|
||||
.with_name("name")
|
||||
.with_label(Lc::n("Name"))
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(
|
||||
form::input::Field::email()
|
||||
.with_name("email")
|
||||
.with_label(Lc::n("Email"))
|
||||
.with_help_text(Lc::n("We will only use it to reply to you.")),
|
||||
)
|
||||
.with_child(
|
||||
form::Textarea::new()
|
||||
.with_name("message")
|
||||
.with_label(Lc::n("Message"))
|
||||
.with_rows(5),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Send")))
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Elige los campos
|
||||
|
||||
| Campo | Constructor |
|
||||
|---|---|
|
||||
| Texto, correo, URL, teléfono, búsqueda | `form::input::Field::text()`, `email()`, `url()`, `telephone()`, `search()` |
|
||||
| Contraseña | `form::input::Field::password()` |
|
||||
| Número | `form::Number::new()` con `with_min()`, `with_max()`, `with_step()` |
|
||||
| Rango | `form::Range::new()` |
|
||||
| Área de texto | `form::Textarea::new()` |
|
||||
| Casilla o interruptor | `form::Checkbox::check()`, `form::Checkbox::switch()` |
|
||||
| Grupo de casillas | `form::check::Field` con `form::check::Item` |
|
||||
| Opciones excluyentes | `form::radio::Field` con `form::radio::Item` |
|
||||
| Lista desplegable | `form::select::Field` con `form::select::Item` |
|
||||
| Fecha, hora, fecha y hora | `form::date::Field::date()`, `time()`, `datetime()` |
|
||||
| Campo oculto | `form::Hidden::field(name, value)` |
|
||||
| Idioma, tema, zona horaria | `form::SelectLanguage`, `form::SelectTheme`, `form::SelectTimezone` |
|
||||
|
||||
Agrupa campos relacionados con `form::Fieldset`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> form::Fieldset {
|
||||
form::Fieldset::new()
|
||||
.with_legend(Lc::n("Preferences"))
|
||||
.with_child(
|
||||
form::radio::Field::new()
|
||||
.with_name("frequency")
|
||||
.with_label(Lc::n("How often do you want news?"))
|
||||
.with_item(form::radio::Item::new("weekly", Lc::n("Every week")).with_checked(true))
|
||||
.with_item(form::radio::Item::new("monthly", Lc::n("Every month"))),
|
||||
)
|
||||
.with_child(
|
||||
form::select::Field::new()
|
||||
.with_name("country")
|
||||
.with_label(Lc::n("Country"))
|
||||
.with_item(form::select::Item::new("es", Lc::n("Spain")))
|
||||
.with_item(form::select::Item::new("mx", Lc::n("Mexico")))
|
||||
.with_item(form::select::Item::new("ar", Lc::n("Argentina"))),
|
||||
)
|
||||
.with_child(form::Checkbox::switch().with_name("alerts").with_label(Lc::n("Alert me")))
|
||||
# }
|
||||
```
|
||||
|
||||
## 3. Recibe y valida los datos
|
||||
|
||||
Atiende `GET` y `POST` en la misma ruta. El *handler* del envío recibe los campos con
|
||||
`web::Form`, siempre como **último** parámetro (consume el cuerpo de la petición):
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
# fn contact_form() -> Form { Form::new() }
|
||||
pub struct Contact;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Contact {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/contact", web::get(show).post(send))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ContactData {
|
||||
name: String,
|
||||
email: String,
|
||||
message: String,
|
||||
}
|
||||
|
||||
async fn show(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Contact"))
|
||||
.with_child(Messages::new())
|
||||
.with_child(contact_form())
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send(
|
||||
request: HttpRequest,
|
||||
web::Form(data): web::Form<ContactData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
if data.message.trim().is_empty() {
|
||||
// Shows the form again with a message.
|
||||
let mut page = Page::new(request)
|
||||
.with_child(Messages::new())
|
||||
.with_child(contact_form());
|
||||
page.context()
|
||||
.push_message(MessageLevel::Error, Lc::n("Please write a message."));
|
||||
return page.render().await.map(IntoResponse::into_response);
|
||||
}
|
||||
// ... save or send `data` ...
|
||||
Ok(Redirect::see_other("/contact/thanks"))
|
||||
}
|
||||
```
|
||||
|
||||
Tras guardar, redirige con `see_other()` (patrón *Post/Redirect/Get*): así, si el usuario recarga
|
||||
la página, no reenvía el formulario.
|
||||
|
||||
## 4. Campos con varios valores
|
||||
|
||||
`web::Form` no admite claves repetidas (`interest=rust&interest=web`), que es lo que envían un grupo
|
||||
de casillas o una lista de selección múltiple. Para ellas, lee el cuerpo en bruto con
|
||||
`web::RawForm` y deserialízalo con [`serde_qs`](https://docs.rs/serde_qs):
|
||||
|
||||
```rust,ignore
|
||||
#[derive(Deserialize)]
|
||||
struct Interests {
|
||||
#[serde(default)]
|
||||
interest: Vec<String>,
|
||||
}
|
||||
|
||||
async fn save(request: HttpRequest, web::RawForm(body): web::RawForm) -> Response {
|
||||
let data: Interests = serde_qs::from_bytes(&body).unwrap_or(Interests { interest: vec![] });
|
||||
// ...
|
||||
# todo!()
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Fechas en el idioma del usuario
|
||||
|
||||
`form::date::Field` muestra y lee las fechas con el formato del idioma activo (`dd/mm/aaaa` en
|
||||
español). Para interpretar el texto recibido, usa los métodos del contexto:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
fn read_date(cx: &Context, text: &str) {
|
||||
match cx.parse_date(text) {
|
||||
Ok(Some(date)) => { /* a valid date: a `NaiveDate` */ }
|
||||
Ok(None) => { /* empty field */ }
|
||||
Err(_) => { /* invalid format */ }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Envía el formulario vacío: el navegador lo impide, porque `name` es obligatorio.
|
||||
2. Envía un mensaje en blanco (sólo espacios): el servidor lo rechaza y el formulario vuelve con el
|
||||
aviso.
|
||||
3. Envía uno correcto y recarga la página de destino: el navegador no ofrece reenviar el
|
||||
formulario.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Validar un campo al vuelo](htmx-validation.md): los mismos errores, sin recargar la página.
|
||||
- [Añadir usuarios y permisos](users.md): formularios que sólo ven algunos usuarios.
|
||||
Loading…
Add table
Add a link
Reference in a new issue