How to add an additional html markup to the autogenerated hidden input fields of the form helper

I use Phoenix and Tailwind and have the issue that Tailwind adds a y-space to hidden input fields by default. You can avoid this by adding a hidden attribute to the markup of hidden fields like this

<input type="hidden" hidden>

How can I add this attribute to the autogenerated hidden input fields for the _csrf_token. The field should look like this

<input type="hidden" name="_csrf_token" value="..." hidden>

Thx for your help

1 Like

You can define your own form component :smiley:

defmodule MyAppWeb.Components do
  use MyAppWeb, :component

  def form(assigns) do
    ~H"""
    <Phoenix.LiveView.Helpers.form let={f} csrf_token={false} {assigns}>
      <input name="_csrf_token" type="hidden" value={Phoenix.HTML.Tag.csrf_token_value(@action)} hidden>
      <%= render_slot(@inner_block, f) %>
    </Phoenix.LiveView.Helpers.form>
    """
  end
end

and then use it just like you would normally

<MyAppWeb.Components.form let={f} for={@conn} action={Routes.user_session_path(@conn, :create)} as={:user}>
  <%= if @error_message do %>
    <div class="alert alert-danger">
      <p><%= @error_message %></p>
    </div>
  <% end %>

  <%= label f, :email %>
  <%= email_input f, :email, required: true %>

  <%= label f, :password %>
  <%= password_input f, :password, required: true %>

  <%= label f, :remember_me, "Keep me logged in for 60 days" %>
  <%= checkbox f, :remember_me %>

  <div>
    <%= submit "Log in" %>
  </div>
</MyAppWeb.Components.form>

to generate this HTML

<form action="/admin/users/log_in" method="post">
  <input name="_csrf_token" type="hidden" value="A_VERY_LONG_AND_SECURE_CSRF_TOKEN" hidden>

  <label for="user_email">Email</label>
  <input id="user_email" name="user[email]" required="" type="email">

  <label for="user_password">Password</label>
  <input id="user_password" name="user[password]" required="" type="password">

  <label for="user_remember_me">Keep me logged in for 60 days</label>
  <input name="user[remember_me]" type="hidden" value="false"><input id="user_remember_me" name="user[remember_me]" type="checkbox" value="true">

  <div>
    <button type="submit">Log in</button>
  </div>
</form>
1 Like

Alternatively wrap all your form markup in a div and apply the .space-y-{number} class to it instead.

<.form for={...} let={...} >
  <div class="space-y-1">
    # form elements 
  </div>
</.form>
2 Likes

Thx to both msimonborg and 03juan! Both solutions work.

I finally decided to go with the one from 03juan, because I did something wrong: I added the class="space-y-x" to the form tag like this: <.form for={...} let={...} class="space-y-6"> and now I moved it to an div within the form as 03juan explained.

Thx a lot

1 Like