表单视图对称中的多对多关系2


many to many relation in a form view symfony 2

我有两个实体之间的多对多关系。

然后显示一个表单,将entityA添加到entityB。不可能添加自定义表单(我的意思是在小枝视图),以使用户有时选择一个值,有时多于一个?

当我想让用户选择多个值时,我使用这个

<select multiple>
{% for entity in entitys %}
<option> 
{{entity.id}}
 </option>
{%endfor%}
</select>

否则

 <select >
    {% for entity in entitys %}
    <option> 
    {{entity.id}}
     </option>
    {%endfor%}
    </select>

但是现在的问题是如何提交表单。

<button  type="submit"  class="btn btn-info"    value="NEXT STEP " /> 

这是整个表格

<form method="post">
  <select >
    {% for entity in entitys %}
    <option> 
    {{entity.id}}
     </option>
    {%endfor%}
    </select>
<input  type="submit"     /> 
</form>

不再提交表单。有什么想法吗??

这是我的整个树枝视图

  <h2> STEP {{step}} </h2>
  <form method="post">
<select >
{% for entity in entitys %}
<option value="{{entity.id}}"> 
{{entity.id}}
 </option>
{%endfor%}
</select>
<input  type="submit"  class="btn btn-info"     /> 
</form>
  <br>
  <br>

在您的formbuilder中,您可以添加一些选项,如我的例子:

目的是将您的字段映射到实体(以设置列表)。别忘了给你的映射实体添加一个_tostring方法,使symfony能够在你的select中以文本的形式表示你的实体。

在你的formType
public function buildForm(FormBuilder $builder, array $options) {
        $id = $this->id;
        $builder->add(
            'addressees',
            'entity',
            array(
                        'class' => 'Pref27'MailBundle'Entity'Addressee',
                        'property' => 'name',
                        'multiple' => true,
                    'expanded' => false,
                        'required' => true,
                        'label' => 'mail.add.theme';
                }
            )
        );
    }

在formcontroller

$editForm = $this->createForm(new FormType(), $entity);
return array(
            'form'   => $editForm->createView()
        );

在你的视图

<form action="{{ path('theControllerActionWitchIsResponsibeOfRecordingIntoDatabase' }}" method="post" {{ form_enctype(edit_form) }}>
        {{ form_widget(edit_form) }}
        <p>
            <button type="submit">Next step</button>
        </p>
</form>

呈现的字段类型将取决于多个和扩展

的设置。
select tag                                  expanded=false  multiple=false
select tag (with multiple attribute)        expanded=false  multiple=true
radio buttons                               expanded=true   multiple=false
checkboxes                                  expanded=true   multiple=true

您可以在这里找到更多关于实体类型的信息:http://symfony.com/doc/2.0/reference/forms/types/entity.html

编辑:

从您的小枝视图表单的动作丢失尝试添加

<form method="post" action="{{ path("theRouteOfYourControllerWitchRecordTheData")}}">

不要忘记添加{{form_rest(form) }}告诉twig添加CSRF令牌

,不要忘记在你的select选项中添加value

<select multiple>
  {% for entity in entitys %}
       <option value="{{entity.id}}">{{entity.name}}</option>
  {%endfor%}
</select>