From 3a775ed4d49a2618875cacbcf06ed19506c3f0ce Mon Sep 17 00:00:00 2001 From: Andrea Zagli Date: Fri, 6 Jan 2023 10:22:49 +0100 Subject: [PATCH] Form get fields and field by name. --- examples/form.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++--- src/lib.rs | 14 ++++++++++ 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/examples/form.rs b/examples/form.rs index 22d8774..7909609 100644 --- a/examples/form.rs +++ b/examples/form.rs @@ -39,26 +39,85 @@ struct AppState { settings: Settings, } +#[derive(Deserialize)] +struct FormData { + name: String, + notes: String, +} + +async fn index_post( + data: web::Data, + form: web::Form, +) -> Result { + let mut s = String::new(); + + s.push_str("\n"); + s.push_str("\n"); + + s.push_str(r#"
"#); + + let mut f = zakform::Form::new(); + + let mut fi = zakform::Field::new(zakform::FType::Text, "name"); + fi.set_label("Name"); + fi.set_value(form.name.as_str()); + f.add_field(fi); + + let mut fi = zakform::Field::new(zakform::FType::TextArea, "notes"); + fi.set_label("Notes"); + fi.set_rows(15); + fi.set_value(form.notes.as_str()); + f.add_field(fi); + + let fs = f.fields(); + for fi in fs { + s.push_str(fi.render().as_str()); + } + + s.push_str(r#""#); + + s.push_str("
\n"); + + s.push_str("\n"); + s.push_str(""); + + Ok(HttpResponse::Ok().body(s)) +} + async fn index( data: web::Data, ) -> Result { let mut s = String::new(); + s.push_str("\n"); + s.push_str("\n"); + + s.push_str(r#"
"#); + let mut f = zakform::Form::new(); let mut fi = zakform::Field::new(zakform::FType::Text, "name"); fi.set_label("Name"); - fi.set_help("Must not be empty."); - s.push_str(fi.render().as_str()); f.add_field(fi); let mut fi = zakform::Field::new(zakform::FType::TextArea, "notes"); fi.set_label("Notes"); fi.set_rows(15); - s.push_str(fi.render().as_str()); f.add_field(fi); + let fs = f.fields(); + for fi in fs { + s.push_str(fi.render().as_str()); + } + + s.push_str(r#""#); + + s.push_str("
\n"); + + s.push_str("\n"); + s.push_str(""); + Ok(HttpResponse::Ok().body(s)) } @@ -82,7 +141,9 @@ async fn main() -> std::io::Result<()> { settings: Settings::new().unwrap(), })) .wrap(middleware::Logger::default()) // enable logger - .service(web::resource("/").route(web::get().to(index))) + .service(web::resource("/") + .route(web::get().to(index)) + .route(web::post().to(index_post))) .service(web::scope("").wrap(error_handlers())) }) .bind((appstate.settings.http.bind_ip, appstate.settings.http.bind_port))? diff --git a/src/lib.rs b/src/lib.rs index 3a38bd2..689f40f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,4 +143,18 @@ impl Form { pub fn add_field(&mut self, field: Field) { self.fields.push(field); } + + pub fn fields(&self) -> &Vec { + &self.fields + } + + pub fn get_field(&mut self, field_name: &str) -> Result<&mut Field, ()> { + for f in &mut self.fields { + if f.name.as_str() == field_name { + return Ok(f); + } + } + + Err(()) + } } -- 2.49.0