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 /// The value of `name` as sent, blank or not, or `None` when the form did not send it.
55 pub(crate) fn raw(&self, name: &str) -> Option<&str> {
56 self.0.get(name).map(String::as_str)
57 }
58
59 /// The names of the fields the form sent.
60 pub(crate) fn names(&self) -> impl Iterator<Item = &str> {
61 self.0.keys().map(String::as_str)
62 }
63
64 /// Sets the value of `name`.
65 pub(crate) fn insert(&mut self, name: String, value: String) {
66 self.0.insert(name, value);
67 }
68}
69
70/// Error messages for a form, keyed by field name. The panel shows each
71/// message next to its field when it re-renders the form.
72///
73/// The keys are owned `String`s, as the keys of Laravel's `MessageBag` are, so a
74/// runtime resource (whose field names are data) can report errors without leaking
75/// its names. A hand-written resource writes a literal key with `.to_string()`:
76///
77/// ```
78/// use ignite_core::FieldErrors;
79///
80/// let mut errors = FieldErrors::new();
81/// errors.insert("price".to_string(), "Price must be a whole number.".to_string());
82/// assert_eq!(errors.get("price").map(String::as_str), Some("Price must be a whole number."));
83/// ```
84///
85/// Since 0.3.0. Before, the keys were `&'static str`.
86pub type FieldErrors = HashMap<String, String>;
87
88/// A save the data layer refuses with a message on one or more fields, as Laravel's
89/// `ValidationException::withMessages(['field' => 'message'])`. A runtime resource's
90/// [`RuntimeData::try_create_for`](crate::RuntimeData::try_create_for) and
91/// [`try_update_for`](crate::RuntimeData::try_update_for) return it; the panel answers 422 with
92/// the form again, each message under its field and the typed values kept, as for the
93/// resource's own validation. Each key must be the name of a field the form shows: a message
94/// for another key has no slot to show in.
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub struct ValidationError {
97 errors: FieldErrors,
98}
99
100impl ValidationError {
101 /// The refusal with `messages`, as `(field, message)` pairs. A field named twice keeps its
102 /// last message.
103 pub fn with_messages<F, M>(messages: impl IntoIterator<Item = (F, M)>) -> Self
104 where
105 F: Into<String>,
106 M: Into<String>,
107 {
108 ValidationError {
109 errors: messages
110 .into_iter()
111 .map(|(field, message)| (field.into(), message.into()))
112 .collect(),
113 }
114 }
115
116 /// The messages, by field name.
117 pub fn errors(&self) -> &FieldErrors {
118 &self.errors
119 }
120
121 /// The messages, by field name, owned.
122 pub fn into_errors(self) -> FieldErrors {
123 self.errors
124 }
125}
126
127impl std::fmt::Display for ValidationError {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 let mut fields: Vec<&str> = self.errors.keys().map(String::as_str).collect();
130 fields.sort_unstable();
131 write!(f, "the save was refused on: {}", fields.join(", "))
132 }
133}
134
135impl std::error::Error for ValidationError {}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 fn form(pairs: &[(&str, &str)]) -> FormInput {
142 FormInput::new(
143 pairs
144 .iter()
145 .map(|(k, v)| (k.to_string(), v.to_string()))
146 .collect(),
147 )
148 }
149
150 #[test]
151 fn blank_and_missing_fields_are_none() {
152 let input = form(&[("name", "Ada"), ("email", " ")]);
153
154 assert_eq!(input.get("name"), Some("Ada"));
155 assert_eq!(input.get("email"), None);
156 assert_eq!(input.get("missing"), None);
157 }
158
159 #[test]
160 fn checkbox_is_true_only_for_ticked_values() {
161 let input = form(&[
162 ("a", "on"),
163 ("b", "1"),
164 ("c", "TRUE"),
165 ("d", "0"),
166 ("e", ""),
167 ]);
168
169 assert!(input.checkbox("a"));
170 assert!(input.checkbox("b"));
171 assert!(input.checkbox("c"));
172 assert!(!input.checkbox("d"));
173 assert!(!input.checkbox("e"));
174 assert!(!input.checkbox("missing"));
175 }
176
177 #[test]
178 fn has_tells_a_blank_field_from_a_missing_one() {
179 let input = form(&[("name", "Ada"), ("note", "")]);
180
181 assert!(input.has("name"));
182 assert!(input.has("note"), "sent blank");
183 assert_eq!(input.get("note"), None);
184 assert!(!input.has("missing"));
185 }
186}