Mike K.
Mike K.

Reputation: 3789

Show/Hide Field Based on Value of Selection in rails_admin

I'm using the rails_admin gem to provide some UI for managing data in my application. I have an edit form for a model, and I want to be able to show or hide form fields in the edit screen, to gather additional information based on the selection of a 'type' within the form. I can't find an example that does this with rails_admin, is this possible?

config.model 'MediaObject' do
    edit do   
     field :title
     field :type, :belongs_to_association
     field :asset, :carrierwave
    end
end

Upvotes: 1

Views: 3611

Answers (2)

Collossus
Collossus

Reputation: 21

Here is what you do for rails_admin

  1. Add the following to your model (assuming you are defining rails_admin in your models):

    edit do
      field :my_field_1
      field :my_field_2
      field "load_js", :hidden do
        def render
          bindings[:view].render partial: "load_js"
        end
      end
    end
    
  2. Create the file you will render in "apps/views/rails_admin/main/_load_js.html.erb" or haml if you prefer.

  3. Add your javascript addition to the above file:

    <script type="text/javascript">
      $(document).ready(function() {
        //whatever you would like to do to the form here
      });
    </script>
    

Upvotes: 2

Joe Kennedy
Joe Kennedy

Reputation: 9443

I'm not sure of a way to do this that involves instantly showing the relevant fields when you select the :type. If you don't mind saving the object first, you could do the following:

field :field_name do
  visible do
    bindings[:object].type == # Put your type here
  end
end

This makes :field_name visible only if the type is relevant after you've already saved the object. Additionally, you could do two things to make this workaround a bit cleaner.

First, make the :type read-only after the object has been created. Put this after your edit block:

update do
  configure :type do
    readonly true
  end
end

Second, make all fields that are specific to your :type selection not visible before the object has been created. Put this after your edit block:

create do
  configure :field_name do
    visible false
  end

  # you could also do this for multiple fields
  include_fields :field_name1, :field_name2, :field_name3 do
    visible false
  end
end 

While this isn't ideal, I've done things similar to this and I don't mind it. I hope this helps.

Upvotes: 4

Related Questions