Search code examples
templateselixirphoenix-framework

Referencing a field value in a Phoenix form


In a Phoenix .eex/.leex form created with <%= f = form_for @changeset…, is there a way to reference one of the field values in a CSS class definition?

For example, I’d like to hide a div element if field1's value is “”. This is the code that I drafted that doesn't seem to work.

<div class= <%= if :field1 == "" do %>
                 "hidden"
            <% else %>
                 " "
             <% end %>

Solution

  • You can use Ecto.Changeset.get_field/3, Ecto.Changeset.get_change/3 or just go for @changeset.data.field1.

    Check the docs for the differences between those three and put a temporary <%= inspect @changeset %> inside your form to see what data and changes are all about.

    So one way of doing what you want is:

    <div class="<%= if @changeset.data.value1 == "", do: "hidden", else: "" %>">
    

    (Notice that I've put the <%= ... %> tags inside the double qoutes.)