Turbo Forms and Validation Errors: Why Your Form Does Nothing

Turbo Forms and Validation Errors: Why Your Form Does Nothing

A form which does nothing is the classic Turbo question, we reproduced it with a small server and Turbo 8.0.23 in the browser, so we can show what exactly happens with every status code.

First the server answered the failed POST with status 200 and the error message inside. On the screen nothing changed, no error, the typed text still sitting in the field, and only in the console we found Form responses must redirect to another location. We changed only the status to 422, same HTML, and the error appeared. This is all the secret, render with status unprocessable entity.

While the request was running we looked at the button, with data-turbo-submits-with it said Saving... and was disabled, our server was sleeping 1.5 seconds on purpose, we clicked two more times and the server received 1 POST only.

Then inside a turbo frame we returned a 422 page without the frame with same id, and the frame was replaced by the words Content missing, the console telling that response did not contain the expected turbo-frame. So the failed template must have this frame.

And the 302 against 303 story, we did not want to repeat it from memory, we sent DELETE with fetch and logged on the server. After 302 the browser sent DELETE again to the target page. After 303 it sent GET. Imagine the target is something which accepts delete, so for update and destroy we always write status see_other.

def create
  @project = current_account.projects.new(project_params)

  if @project.save
    redirect_to @project, status: :see_other, notice: "Project created."
  else
    render :new, status: :unprocessable_entity
  end
end

Under the post we put our controller, the field with the error sitting near it, and a small test which sends blank name and wants 422 back, so the day when somebody cleans up the status line we find out from CI and not from a customer.

<%= form_with model: @project do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name,
        aria: { invalid: @project.errors[:name].any?,
                describedby:
                  ("project_name_error" if @project.errors[:name].any?) } %>

  <% if @project.errors[:name].any? %>
    <p id="project_name_error" class="field-error">
      <%= @project.errors.full_messages_for(:name).to_sentence %>
    </p>
  <% end %>

  <%= f.submit "Save", data: { turbo_submits_with: "Saving..." } %>
<% end %>
test "keeps the form open when the name is blank" do
  sign_in users(:owner)
  post projects_path, params: { project: { name: "" } }

  assert_response :unprocessable_entity
  assert_select "p.field-error", /can't be blank/
end

See also: the accessibility post and building UIs with Hotwire.