04 Forms
The next step now that we know how to work with inputs is to think about forms. We’re going to be using the formal package so let’s first add that to our project that we started with before. It might be worth going through the docs for formal itself as I won’t go into as much detail here.
gleam add formal
Imagine that you want to make a guest list for an event. What we’re going to build is for you to be able to add someone’s name and email so that you can send out your RSVP invitations! This means that we’ll need to, on submitting the form, validate the email address too. Once again, let’s update the imports:
import gleam/list
import formal/form.{type Form}
import lily/client
import lily/component.{type Component}
import lily/event
import lily/store
import lustre/attribute
import lustre/element.{type Element}
import lustre/element/html
With our types, the only thing that is really new here is that we’re also storing the current status of the form itself within the model. For more information on the structure of the Form type, check out the docs for formal.
pub type Guest {
Guest(name: String, email: String)
}
pub type Model {
Model(form: Form(Guest), guests: List(Guest))
}
pub type Message {
Edited(name: String, value: String)
Submitted(List(#(String, String)))
}
We can use formal’s functions to create the guest form and the update function with the appropriate validations (check out the formal docs for more information). The main thing to note here is that we must update the form value within the Model based on both edits, successful submissions, and failed validations.
fn guest_form() -> Form(Guest) {
form.new({
use name <- form.field("name", form.parse_string |> form.check_not_empty)
use email <- form.field("email", form.parse_email)
form.success(Guest(name: name, email: email))
})
}
fn update(model: Model, message: Message) -> Model {
case message {
Edited(name, value) -> {
let values = list.key_set(form.all_values(model.form), name, value)
Model(..model, form: form.set_values(model.form, values))
}
Submitted(values) ->
case guest_form() |> form.add_values(values) |> form.run {
Ok(guest) ->
Model(form: guest_form(), guests: list.append(model.guests, [guest]))
Error(invalid) -> Model(..model, form: invalid)
}
}
}
To understand when the messages are fired, let’s look at the view functions:
fn view(_model: Model) -> Component(Model, Message, Element(Message)) {
component.fragment([guest_form_view(), guest_list()])
}
fn guest_form_view() -> Component(Model, Message, Element(Message)) {
component.static(fn(nest) {
html.form([], [
nest(field("name", "Name")),
nest(field("email", "Email")),
html.button([attribute.type_("submit")], [html.text("Add guest")]),
])
})
|> event.on_submit(handler: Submitted)
}
fn field(
name: String,
placeholder: String,
) -> Component(Model, Message, Element(Message)) {
component.dynamic(
slice: fn(model: Model) { model.form },
render: fn(current, _nest) {
html.p([], [
html.input([
attribute.name(name),
attribute.placeholder(placeholder),
attribute.value(form.field_value(current, name)),
]),
..list.map(form.field_error_messages(current, name), fn(error) {
html.small([], [html.text(" " <> error)])
})
])
},
)
|> event.on_input(handler: fn(value) { Edited(name: name, value: value) })
}
fn guest_list() -> Component(Model, Message, Element(Message)) {
component.dynamic(
slice: fn(model: Model) { model.guests },
render: fn(guests, _nest) {
html.ul(
[],
list.map(guests, fn(guest: Guest) {
html.li([], [html.text(guest.name <> " <" <> guest.email <> ">")])
}),
)
},
)
}
We’ve added an event.on_input onto each input field to track the values of the form. To the actual form itself, we’ve added an event.on_submit which then sets a Submitted message. On actually running the form itself using formal’s form.run, we can use the Result to determine whether or not there has been a validation error. Check back on the update function to see how it works. You can also see that on error, we set add error messages to the appropriate field, which then allows us to display these right after each field within the field component.
The main thing left to do now is to just update our main function, and then you can serve and play around with the code!
pub fn main() {
store.new(init: Model(form: guest_form(), guests: []), update: update)
|> client.start
|> component.mount(
selector: "#app",
to_html: element.to_string,
to_placeholder: fn() { element.element("lily-nest", [], []) },
view: view,
)
}
Check out the /examples folder in the GitHub repo for a copy of this example under /examples/04-forms.