【问题标题】:How do I dynamically add a new option to a set of Formtastic checkboxes for associated resources?如何为关联资源的一组 Formtastic 复选框动态添加新选项?
【发布时间】:2011-03-30 22:10:51
【问题描述】:

假设我有一个创建商店并允许选择它提供的服务的表单:

<%= semantic_form_for @store do |f| %>
  <%= f.inputs :services, :as => :check_boxes, :collection => Service.all %>
  <%= f.buttons %>
<% end -%>

我想允许用户添加一个新服务,以防他在选项中没有看到它,就在表单中。

有很多简单的嵌套表单元素添加示例,例如项目中的任务条目,甚至 a gem that helps with this,但我没有找到任何创建新资源的示例,因此它将显示为部分 os 复选框或选择选项。

【问题讨论】:

  • HTML 根本不允许嵌套表单,无论是否使用 Rails。
  • 好的,然后有任何关于在没有表单的情况下提交该字段并将新复选框附加到新资源的示例吗?自从发布问题后,我发现了 onclick 提交的 sn-ps,只是在寻找一个优雅的解决方案来处理整个往返过程

标签: ruby-on-rails ajax nested-forms formtastic


【解决方案1】:

以这种方式工作:

<%= semantic_form_for @store do |f| %>
  <%= f.inputs :services, :as => :check_boxes, 
                          :collection => Service.all,
                          :wrapper_html => { :id => 'service_fields' } %>  
  <%= f.buttons %>
<% end -%>

在复选框字段列表周围的父列表项中添加了一个id,以便在提交具有新服务名称的文本字段后,此js可以访问它:

<input type="text" id="new_service_name" />
<input type="button" value="ok" id="btnSave" />                                

<script type="text/javascript">        
  $(document).ready(function() {
    $('#btnSave').click(function() {
      $.ajax({
        url: '/admin/services.json',
        type: 'POST',
        dataType: 'json',
        data: 'service[name]=' + $('#new_service_name').val(),
          success: function(data) {
            addCheckbox(data);
          }
        });
      });
    });

    function addCheckbox(name) {
      var container = $('#service_fields fieldset ol');
      var inputs = container.find('input');
      var id = inputs.length+1;

      //var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
      var html = '<li><label for="store_services_'+id+'"><input id="store_services_'+id+'" name="store[services][]" type="checkbox" value="'+id+'" />'+name+'</label></li>';
      container.append($(html));
    }
</script>

然后,在 ServicesController 中:

class ServicesController < ApplicationController  
  respond_to :json

  def create
    service = Service.create!(params[:service])    
    respond_with(service)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    相关资源
    最近更新 更多