From dd75472f1508e0b25a77f04ab3dcedc6c750a123 Mon Sep 17 00:00:00 2001 From: Andrea Zagli Date: Sat, 18 Feb 2023 10:25:10 +0100 Subject: [PATCH] Rendered html select. --- examples/form.rs | 5 ++++ src/fields.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/examples/form.rs b/examples/form.rs index 5e1bd8c..296a5ce 100644 --- a/examples/form.rs +++ b/examples/form.rs @@ -74,6 +74,11 @@ async fn index( fi.set_label("the check text very very long"); f.add_field(Box::new(fi)); + let mut fi = zakform::fields::FieldSelect::new("select"); + fi.add_option(zakform::fields::FOption{ value: String::from("F"), label: String::from("Female") }); + fi.add_option(zakform::fields::FOption{ value: String::from("M"), label: String::from("Male") }); + f.add_field(Box::new(fi)); + let fs = f.fields(); for fi in fs { s.push_str(fi.render().as_str()); diff --git a/src/fields.rs b/src/fields.rs index 56fbf64..73476bb 100644 --- a/src/fields.rs +++ b/src/fields.rs @@ -285,6 +285,74 @@ _ => {}, } } +#[derive(Default)] +pub struct FieldSelect { + field: Field, + options: Vec, +} + +impl TField for FieldSelect { + fn get_name(&self) -> String { + String::from(&self.field.name) + } + + fn get_label(&self) -> String { + String::from(&self.field.label) + } + + fn set_label(&mut self, label: &str) { + self.field.label = String::from(label); + } + + fn render(&self) -> String { + let mut s = String::new(); + + let mut context = tera::Context::new(); + context.insert("name", &self.field.name); + context.insert("label", &self.field.label); + context.insert("disabled", &self.field.disabled); + context.insert("invisible", &self.field.invisible); + context.insert("help", &self.field.help); + context.insert("value", &self.field.value); + context.insert("options", &self.options); + s.push_str(self.field.tmpl.render("field", &context).unwrap().as_str()); + + s + } + + fn any(&mut self) -> &mut dyn Any { + self + } +} + +impl FieldSelect { + pub fn new(name: &str) -> Self { + let mut f: FieldSelect = Default::default(); + + f.field.name = String::from(name); + f.field.label = String::from(name); + + match f.field.tmpl.add_raw_template("field", r#"{% if label %}
+
{% endif %} + + {% if help %}
{{ help }}
{% endif %} + {% if label %}
{% endif %}"#) { +Err(e) => { println!("{:?}", e) }, +_ => {}, +}; + + f + } + + pub fn add_option(&mut self, option: FOption) { + self.options.push(option); + } +} + #[derive(Default)] pub struct FieldCheck { field: Field, -- 2.49.0