Using checkboxes in MaterializedCSS

I am setting up a site with MaterialzedCSS and trying to get a checkbox to work.

at first, I was using:

<%= label f, :active %>
<%= checkbox f, :active %>
<%= error_tag f, :active %>

but this renders to something like:

<input id="episode_active" name="episode[active]" type="checkbox" value="true">

And this is invisible and doesn’t render.

Using the docs (Checkboxes - Materialize) as a guide, I roughed this in:

 <label>
        <% checked_value = if @episode.active, do: "checked=checked", else: "" %>
        <input id="episode_active" name="episode[active]" type="checkbox" <%= checked_value %> />
        <span>Active?</span>
    </label>

this will handle the checked state of the box, but it doesn’t send the correct value when checked… it sends:

%{"active" => "on"}

Which errors out the boolean field.

curiously, if I submit the form without this field checked, it sends

 %{"active" => "false"

And everything is cool.

Any ideas on how I should handle this?

Thanks!

Phoenix by default sends the values for unchecked checkboxes as false, to make up for the shortcoming of http form handling, that’s why you receive that second part.

You should be doing your form and let the CSS work on the class not dictate how you should be using your form. I have used that Materialized CSS thing for a project and ended ditching it because of mish mash like this.

%= checkbox f, :active, checked: helper_function_to_return_boolean?(@changeset......) %>

or

handle the logic in your controller before passing into your view as a clean boolean
1 Like

Thanks for your help! In order to get it to render, I had to do this:

<p>
    <label>
        <%= hidden_input f, :active %>
        <%= checkbox f, :active, value: @episode.active %>
        <span>Active</span>
    </label>
    <% error_tag f, :active %>
</p>

not super proud of it, but it works for now.

what did you end up using, instead of Materialized CSS?

Thanks!

looks good but that might cause you some headache in the future.

I have looked into tinycss, got sick of it’s global overrides too and ditched that one also.

ended up writing custom CSS for only the stuff I needed. Gave me a very tidy html definition, performance, and size reduction as well as theming

1 Like