How can I make a lens to extract a possibly empty ...
# http4k
m
How can I make a lens to extract a possibly empty list of values from form data? I tried this:
Copy code
val idsField = FormField.string().multi.optional("ids")
val idsLens = Body.webForm(Validator.Ignore, idsField).map { idsField(it) }.toLens()
but if the form data is empty, I get this error:
Copy code
org.http4k.lens.LensFailure: formData 'ids' is required
	at org.http4k.lens.BodyLensSpec$toLens$1$1.invoke(body.kt:50)
	at org.http4k.lens.BodyLensSpec$toLens$1$1.invoke(body.kt:50)
	at org.http4k.lens.BodyLens.invoke(body.kt:19)
I came up with this workaround:
Copy code
val idsField = FormField.string().multi.required("ids")
val idsLens =
    Body.webForm(Validator.Ignore, idsField).map { if (it.fields.containsKey("ids")) idsField(it) else emptyList() }
        .toLens()
a
Instead of having a multi field, would merging them into a single csv field be acceptable?
Copy code
val field = FormField.csv().optional("my_field")
m
Not really, that would complicate the htmx based front end unnecessarily. https://htmx.org/examples/bulk-update/
Then I rather stick with my workaround (see above).