How to disable all form_for input fields in Ruby on Rails app?

前端 未结 3 2007
故里飘歌
故里飘歌 2021-01-05 00:54

I am trying to DRY up my Rails application a bit, so I would like to render a form in my show view but disable all input fields.

// sho         


        
相关标签:
3条回答
  • 2021-01-05 01:01

    You can use stylesheets for this thing.

    The show action might be in controller say 'Project', hence you might be having a file in stylesheets with the name of your controller.

    Now enclose your form in show.html.erb in a div, and give it a unique id ,say 'disable_input', that you wont be giving to any element in any page.

    Now disable all input fields in you css under this div. You can write it like this..

    disable_input input{
    # whatever you want to do
    }

    Hence no need to code.

    0 讨论(0)
  • 2021-01-05 01:08

    Javascript

    One way would be to do it using JS. Include a div with a specific class in the show view :

    // show.html.erb
    
    <div class='disable_input'>
      <%= form_for(@project) do |f| %>
        <%= render 'fields', :f => f %>
      <% end %>
    </div>
    

    Then in your JS file :

    $('.disable_input :input').prop('disabled', true);
    

    Rails

    If you want to actually generate it server side, you can pass a variable to your partial that will tell the partial if it has to add the disabled option on each field. It's a bit more work though!

    Using a variable, you could do something like this :

    <%= form_for(@project) do |f| %>
      <%= render 'fields', :f => f, :disabled => true %>
    <% end %>
    

    In the partial :

    <% disabled ||= false  
       #We do this so if disabled is not passed to the partial it doesn't crash. 
       # We default it to false 
    %>
    
    <% # Then for all your fields, add disabled: disabled %>
    <%= f.text_field :some_attribute, disabled: disabled %>
    

    Form builder

    Edit : actually, one way to avoid explicitly passing disabled everywhere would be to create a Custom form builder. There's some good resources talking about it, like this one : http://johnford.is/writing-a-custom-formbuilder-in-rails/

    In this example, it's done for onkeypress, shouldn't be hard to adapt for your case!

    0 讨论(0)
  • 2021-01-05 01:18

    You can wrap all fields in <fieldset disabled>

    // show.html.erb
    
    <%= form_for(@project) do |f| %>
      <fieldset disabled>
        <%= render 'fields', :f => f %>
      </fieldset>
    <% end %>
    
    0 讨论(0)
提交回复
热议问题