【问题标题】:Symfony 2 : How to correctly add an element in collection in the formSymfony 2:如何在表单中正确添加集合中的元素
【发布时间】:2014-09-11 16:45:49
【问题描述】:

在实体 A 的形式中,我希望能够添加某种形式的实体 B。

我知道如何显示一个表单,但是当我将属性 'collection' 与 'allow_add' 放在一起时......它不会添加任何东西,只是一个空的

  • 这是我的看法:

    <.form action="{{ path('our_bundle_building_entityACreate')}}" method="post" {{ form_enctype(form) }} >
    {{ form_widget(form) }}
    
    {{ form_row(form.entity) }}
    
    <ul id="price-fields-list" data-prototype="{{ form_widget(form.entityB.vars.prototype) | e }}">
        {% for entityB in form.entityB %}
            <li>
                {{ form_errors(entityB) }}
                {{ form_widget(entityB) }}
            </li>
        {% endfor %}
    </ul>
    <a href="#" id="add-another-entityB">Add another entityB price</a>
    
    <input type="submit" />
    <./form>
    
    <.script type="text/javascript">
    var entityBCount = '{{ form.entityB | length }}';
    
    jQuery(document).ready(function() {
        jQuery('#add-another-entityB').click(function() {
            var entityBList = jQuery('#entityB-fields-list');
    
            var newWidget = entityBList.attr('data-prototype');
    
            newWidget = newWidget.replace(/__name__/g, entityBCount);
            entityBCount++;
    
            var newLi = jQuery('<li></li>').html(newWidget);
            newLi.appendTo(jQuery('#entityB-fields-list'));
    
            return false;
        });
    })
    <./script>`
    

    我的 entityB 形式运行良好,所以我不会展示它(只有几个常用的输入)

    我在 buildForm 中的 entityA 形式:

    ->add('entityB', 
                    'collection', 
                    array('type' => new entityBType($this->id),
                          'allow_add' => true,
                          'allow_delete'  => true,
                          'by_reference' => false,));
    

    顺便说一句,我并没有真正理解“原型”,所以问题可能来自这里。

    感谢和问候,

    我:)

  • 【问题讨论】:

      标签: forms symfony collections prototype


      【解决方案1】:

      如果您只想嵌入一个表单,最简单的方法是这样做:

      ...    
      
      ->add('entityB', new entityBType($this->id));
      

      【讨论】:

      • 我需要一个表单集合,正如我所说的,我已经知道了,这是可行的,但集合不是
      • 您实际上是在构建 entityB 表单的集合吗?因为从上面的示例中不清楚。如果它只是您想要嵌入的一种形式,那么从功能上讲,“集合”不是必需的。一个子表单的集合不是集合。 :/ 在这种情况下,只需将 entityB 表单类型设为父 entityA 表单类型的子属性即可。否则,查看app/logs 中的日志文件,看看 Symfony 是否在抱怨你的集合配置。上面的 sn-p 不足以确定问题所在。
      • 事实上 entityA 与 entityB 有一对多的关系,所以我认为我需要一个集合。我会检查应用程序/日志
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2012-06-12
      • 1970-01-01
      相关资源
      最近更新 更多