From 07df7634c273eb4a3b69042325a707163d6695ed Mon Sep 17 00:00:00 2001 From: Andrea Zagli Date: Fri, 6 Jan 2023 12:10:23 +0100 Subject: [PATCH] Form as_json_string. --- Cargo.toml | 1 + examples/form.rs | 17 +++++++++++++---- src/lib.rs | 13 +++++++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 10aa291..ebae6c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,5 +12,6 @@ tera = "1.8.0" [dev-dependencies] serde = "1" serde_derive = "1" +serde_json = "1" config = "0.13" actix-web = "4" diff --git a/examples/form.rs b/examples/form.rs index fa85845..661f9a7 100644 --- a/examples/form.rs +++ b/examples/form.rs @@ -2,8 +2,10 @@ extern crate zakform; use zakform::filters; +use std::collections::HashMap; + use config::{Config, ConfigError}; -use serde_derive::Deserialize; +use serde_derive::{Serialize,Deserialize}; use actix_web::{ body::BoxBody, @@ -41,7 +43,7 @@ struct AppState { settings: Settings, } -#[derive(Deserialize)] +#[derive(Serialize,Deserialize)] struct FormData { name: String, notes: String, @@ -60,9 +62,13 @@ async fn index_post( let mut f = zakform::Form::new(); + let strform = serde_json::to_string(&form).unwrap(); + println!("{:#?}",strform); + let map: HashMap = serde_json::from_str(&strform).unwrap(); + let mut fi = zakform::Field::new(zakform::FType::Text, "name"); fi.set_label("Name"); - fi.set_value(form.name.as_str()); + fi.set_value(map.get(fi.name().as_str()).unwrap().as_str()); fi.add_filter(filters::filter_uppercase); fi.filter(); f.add_field(fi); @@ -70,7 +76,7 @@ async fn index_post( 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()); + fi.set_value(map.get(fi.name().as_str()).unwrap().as_str()); fi.add_filter(filters::filter_trim); fi.filter(); f.add_field(fi); @@ -80,6 +86,9 @@ async fn index_post( s.push_str(fi.render().as_str()); } + let js: HashMap = serde_json::from_str(f.as_json_string().as_str()).unwrap(); + println!("{:#?}", js); + s.push_str(r#""#); s.push_str("\n"); diff --git a/src/lib.rs b/src/lib.rs index 918fc1c..60d2878 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -175,4 +175,17 @@ impl Form { Err(()) } + + pub fn as_json_string(&mut self) -> String { + let mut s = String::from("{"); + + for f in &mut self.fields { + s.push_str(format!(r#""{}": "{}","#, f.name, f.value).as_str()); + } + + s.truncate(s.len() - 1); + s.push_str("}"); + + s + } } -- 2.49.0