Create dynamic forms in ActiveAdmin

别等时光非礼了梦想. 提交于 2019-12-20 10:57:45

问题


Hi guys I'm pretty stuck with building a customised form in active admin. I've figured out and even set up my own customised forms using active admin. However I need to create a dynamic form here. This involves making some ajax calls and returning partials of a form for the user to fill out.

It seems that you can create a member action but that is on resources that have been created. In my case I need to create multiple entries on a resource that is yet to be created.


回答1:


This might get you started. A way could be to add your ajax route to config.routes (just some random example code):

match '/admin/search/authors' =>  'admin/articles#search_authors',  :via => 'post', :as => :admin_search_authors

Then in the correct register block, in this case in app/admin/articles.rb you can put your controller logic

ActiveAdmin.register Article do
  ...
  controller do
    def search_authors
      @authors = Author.find_by_query params[:query]
      render :layout => false, :template => 'admin/authors/search'
    end
  end

end

In this case the template just renders an unordered list to be put in the form. Located at app/views/admin/authors/search.html.erb and looks like:

<ul>
  <% if @authors.count < 1 %>
    <li>None</li>
  <% else %>
    <% @authors.each do |a| %>
      <li>
      <a href="#" onclick="javascript:insert_your_own_voodoo_function_here();return false;">
        <%= raw a.listname %>
      </a>
      </li>
    <% end %>
  <% end %>
</ul>

Your custom jquery to trigger the ajax-call could look like this, here a delayedObserver is used (thanks to http://code.google.com/p/jquery-utils/wiki/DelayedObserver ):

$(function() { 
     $('#search_author').delayedObserver(function() {
       $('#search_author').after('<img class="ajax-loader" id="ajax-loader" alt="Ajax-loader" src="/images/ajax-loader.gif">');
       $.ajax({
         url: '<%= admin_search_authors_path %>',
         dataType: 'html',
         type: 'post',
         data: { query: $('#search_author').val(), authenticity_token: $('meta[name=csrf-token]').attr("content")},
         success: function(data) {
           $('.ajax-loader').remove();
           $('#chooseauthor').html(data);
           $("#artikel_edit_auteurs").effect("highlight", {}, 1500);
         }
       });
     }, 0.5);
   });

Anything is possible. Just analyze what you really need: form partials, nested form partials? Depending selects? Maybe you want to build a multiple step form instead. Good luck.



来源:https://stackoverflow.com/questions/10370775/create-dynamic-forms-in-activeadmin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!