Kvass
Kvass

Reputation: 8434

ActiveAdmin - Pass locals to form

In my photos.rb file I have:

ActiveAdmin.register Photo do
  form :partial => 'admin/forms/photo', :locals => { :events => Event.all }
end

In my _photo.html.erb file I want to be able to access the value of events, but it doesn't seem to be detectable. How can I do this?

As requested in a comment, here is my form:

<% if events.any? %>
  <%= form_for [:admin, @photo], :validate => true do |f| %>
    <!-- insert a bunch of standard field divs here -->
    <div class="actions" style="margin-top: 20px">
      <% if @photo.new_record? %>
        <%= f.submit 'Create photo' %>
      <% else %>
        <%= f.submit 'Update photo' %>
      <% end %>
    </div>
  <% end %>
<% else %>
  <div style="font-size: 14px">
    You cannot add photos until you have added at least one event.
  </div>
<% end %>

The error message I am getting is around the events.any? line:

Completed 500 Internal Server Error in 108ms

ActionView::Template::Error (undefined local variable or method `events' for #<#<Class:0x007fdb8e841b80>:0x007fdb8a93e7a8>)

Upvotes: 3

Views: 2331

Answers (3)

Jeans K. Real
Jeans K. Real

Reputation: 188

form do |f|
    render partial: 'admin/forms/photo', locals: { value: 'random_data' }
end

You can use f.render or just render.

Note that partial: is required to send locals to the form

Example Partial

#app/views/admin/forms/_photo.html.arb
active_admin_form_for [:admin, resource] do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs do
       f.input :name
       f.input :random if (value == 'random_data')
    end
   f.actions
end

Upvotes: 1

Halil &#214;zg&#252;r
Halil &#214;zg&#252;r

Reputation: 15945

form do |f|
  f.render partial: 'admin/forms/photo', locals: { f: f, events: Event.all }
end

Note that you will need to remove form_for, semantic_form_for, active_admin_form_for etc from your partial, since it will be covered by the form do part in the admin/photos.rb, otherwise there will be two nested forms.

Example partial:

# app/views/admin/forms/_photo.html.arb
if events.any?
  f.inputs do
    f.input :title, label: 'Etc'
    f.input :file
  end
  f.actions
else
  f.div 'You cannot add photos until you have added at least one event.', 
        style: 'font-size: 14px'
end

Upvotes: 3

rmagnum2002
rmagnum2002

Reputation: 11421

another thought on this, if you want to check only if there are any Events in db you can make any call directly on Class:

<% if Event.any? %>
  do this
<% else %>
  do that
<% end %>

without sending variables to partial, the above code result in:

2.0.0p0 :004 > Event.any?
   (0.6ms)  SELECT COUNT(*) FROM "events"
 => true

and leave the ActiveAdmin partial without locals:

ActiveAdmin.register Photo do
  form :partial => 'admin/forms/photo'
end

Upvotes: 0

Related Questions