Skip to main content

ignite_core/
form.rs

1//! Submitted form values and the per-field error messages.
2
3use std::collections::HashMap;
4
5/// Submitted form values, by field name. Empty fields are `None`.
6#[derive(Debug, Clone, Default, PartialEq, Eq)]
7pub struct FormInput(HashMap<String, String>);
8
9impl FormInput {
10    /// Wraps the values of a submitted form, keyed by field name.
11    pub fn new(values: HashMap<String, String>) -> Self {
12        FormInput(values)
13    }
14
15    /// Returns the value of `name`, or `None` when the field is missing or
16    /// blank. The value is not trimmed.
17    pub fn get(&self, name: &str) -> Option<&str> {
18        self.0
19            .get(name)
20            .map(String::as_str)
21            .filter(|value| !value.trim().is_empty())
22    }
23
24    /// Returns true when the form sent the field `name` at all, even blank. A field that is
25    /// sent blank is one the user cleared; a field that is not sent is one the form does not
26    /// have, so an update keeps its stored value. An unticked HTML checkbox sends nothing, so
27    /// use [`checkbox`](Self::checkbox) for a checkbox, not this.
28    pub fn has(&self, name: &str) -> bool {
29        self.0.contains_key(name)
30    }
31
32    /// Returns true when the checkbox `name` was ticked. An HTML checkbox
33    /// sends `on` when ticked and nothing when not, so `on`, `1` and `true`
34    /// (in any case) count as ticked.
35    pub fn checkbox(&self, name: &str) -> bool {
36        self.get(name).is_some_and(|value| {
37            matches!(
38                value.trim().to_ascii_lowercase().as_str(),
39                "on" | "1" | "true"
40            )
41        })
42    }
43
44    /// The form without the fields `names`, as if it had not sent them. The panel removes the
45    /// fields a [condition](crate::FieldConditions) hides before it checks and saves a form.
46    pub fn without<'n>(&self, names: impl IntoIterator<Item = &'n str>) -> FormInput {
47        let mut values = self.0.clone();
48        for name in names {
49            values.remove(name);
50        }
51        FormInput(values)
52    }
53
54    /// Sets the value of `name`.
55    pub(crate) fn insert(&mut self, name: String, value: String) {
56        self.0.insert(name, value);
57    }
58}
59
60/// Error messages for a form, keyed by field name. The panel shows each
61/// message next to its field when it re-renders the form.
62///
63/// The keys are owned `String`s, as the keys of Laravel's `MessageBag` are, so a
64/// runtime resource (whose field names are data) can report errors without leaking
65/// its names. A hand-written resource writes a literal key with `.to_string()`:
66///
67/// ```
68/// use ignite_core::FieldErrors;
69///
70/// let mut errors = FieldErrors::new();
71/// errors.insert("price".to_string(), "Price must be a whole number.".to_string());
72/// assert_eq!(errors.get("price").map(String::as_str), Some("Price must be a whole number."));
73/// ```
74///
75/// Since 0.3.0. Before, the keys were `&'static str`.
76pub type FieldErrors = HashMap<String, String>;
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    fn form(pairs: &[(&str, &str)]) -> FormInput {
83        FormInput::new(
84            pairs
85                .iter()
86                .map(|(k, v)| (k.to_string(), v.to_string()))
87                .collect(),
88        )
89    }
90
91    #[test]
92    fn blank_and_missing_fields_are_none() {
93        let input = form(&[("name", "Ada"), ("email", "   ")]);
94
95        assert_eq!(input.get("name"), Some("Ada"));
96        assert_eq!(input.get("email"), None);
97        assert_eq!(input.get("missing"), None);
98    }
99
100    #[test]
101    fn checkbox_is_true_only_for_ticked_values() {
102        let input = form(&[
103            ("a", "on"),
104            ("b", "1"),
105            ("c", "TRUE"),
106            ("d", "0"),
107            ("e", ""),
108        ]);
109
110        assert!(input.checkbox("a"));
111        assert!(input.checkbox("b"));
112        assert!(input.checkbox("c"));
113        assert!(!input.checkbox("d"));
114        assert!(!input.checkbox("e"));
115        assert!(!input.checkbox("missing"));
116    }
117
118    #[test]
119    fn has_tells_a_blank_field_from_a_missing_one() {
120        let input = form(&[("name", "Ada"), ("note", "")]);
121
122        assert!(input.has("name"));
123        assert!(input.has("note"), "sent blank");
124        assert_eq!(input.get("note"), None);
125        assert!(!input.has("missing"));
126    }
127}