Phoenix Blog Post: Making a CheckboxGroup Input

Phoenix 1.7.0 brings a lot of new things when we run mix phx.gen my_app. These new and cool ways of doing things aren’t automatically brought to existing projects because they come from the generators. Of the many new things we could bring to an existing project, we focus on the new approach to form input components. Why? Because it’s both cool and useful! This post builds a custom multi-select checkbox group input for selecting which tags to associate with a database record in our Phoenix application. It’s surprisingly easy and elegant!

2 Likes

I recently build something like this as well: Scratchpad | Benjamin Milde

One problem, which I didn’t see discussed in the blog post is that you cannot submit an empty list due to how inputs are serialized in html. So no way to unselect everything and have it save properly. I do have one workaround to that in my code, but there are a few ones with different tradeoffs.

3 Likes

Good catch! Thanks for bringing that to my attention!

1 Like

I updated the article to support dealing with an empty list. This lets you assign tags and then remove all the tags.

Updates:

  • Tagging post - updated schema changeset functions to remove blank entries. Used by the UI.
  • This article - added a hidden input to always send a value. In this case, it sends "". The blank value is removed during processing. This is the fix.
  • gist - The gist was updated for the fix. Added the separate ChangesetHelpers file for a more complete solution in the gist.
2 Likes