Textbox is getting blank on submit if any error in rails 5

62 Views Asked by At

I am new in rails I have 7 fields in my forms in rails 5 and validations on some of them When i am filling all correct data it's working fine. When i do not fill any field which is mandatory it shows error message problem is it clear all the 4 or 5 or 6 textboxes and i need to fill all the same data again. Is there any option to retain the data and show alert message? I have tried redirect_to and render both but both are not working and refreshes the page and clear all the data.

def create
    if user.save
        redirect_to user_path, notice: 'User saved'
    else
        #redirect_to new_user_path, alert: user.errors.full_messages.first
        flash[:alert] =  user.errors.full_messages.first
        render '/admin/user/new'
    end
end

new.html.erb

<%= form_with(url: create_user_path+'?'+request.query_string, id: 'new_user', class: 'new_user', local: true) do |f| %>
<%= render 'form', f: f %>
  <br><br>
  <%= f.submit 'Submit' %>
<% end %>

_form.html.erb

<table class='mui-table mui-table--bordered'>
    <%= f.fields_for :user do |f| %>
      <tr>
        <td><strong>First Name</strong></td>
        <td><%= f.text_field :first_name %></td>
      </tr>
      <tr>
        <td><strong>Last Name</strong></td>
        <td><%= f.text_field :last_name %></td>
      </tr>
      <tr>
        <td><strong>Name of Bank</strong></td>
        <td><%= f.text_field :bank_name %></td>
      </tr>
      <tr>
        <td><strong>Branch Name</strong></td>
        <td><%= f.text_field :branch_name %></td>
      </tr>
      <tr>
        <td><strong>Account Name</strong></td>
        <td><%= f.text_field :account_name %></td>
      </tr>
      <tr>
        <td><strong>Account Number</strong></td>
        <td><%= f.text_field :account_number, { onkeypress: 'return isNumberKey(event)' } %></td>
      </tr>
      <tr>
        <td><strong>Membership Number</strong></td>
        <td><%= f.text_field :sf_membership_number, { onkeypress: 'return isNumberKey(event)' } %></td>
      </tr>
  <% end %>
  </table>

Create method is above.

1

There are 1 best solutions below

0
Yusuf On

Two steps need to follow:-

  1. Use form_for instead of form_with
  2. remove <%= f.fields_for :user do |f| %>

Its works