Symfony - 具有多个实体的表单 objects

Symfony - Form with multiple entity objects

我是 运行 Symfony 3.4 LTS,我有一个实体 Attribute:

<?php

class Attribute
{

    private $id;
    private $code;
    private $value;
    private $active;

    // My getters and setters

数据库下方table:

我想在一个表格中获取带有 code == 'productstatus' 的所有行。我试过了:

<?php

$attributes = $this->getDoctrine()->getRepository(Attribute::class)->findBy(['code' => 'productstatus']);
// $attributes contains array with 3 objects 'Attribute'
$form = $this->createFormBuilder($attributes);
$form->add('value', TextType::class);
$output = $form->getForm()->createView();

如果我 dump() Twig 中的 $output 变量:

...我无法循环显示带值的 3 个字段。

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

结果:

我的目标是允许用户在同一个表单(或多个表单,但在同一个页面)中编辑特定属性的所有值。我已经尝试使用 CollectionType 但没有成功。

您可以在您的 AttributeType 中使用 if 语句,如下例所示:

$builder->add('entree',EntityType::class,array('class'=>'cantineBundle:plat','choice_label'=>function($plat){if($plat->getType()=='Entree'&&$plat->getStatus()=="non reserve"){return $plat->getNomPlat();}},'multiple'=>false))

我找到了一个解决方案:创建 2 个嵌套表单并使用 CollectionType。希望对你有帮助。

<?php

// Controller

$attributes = $this->getDoctrine()->getRepository(Attribute::class)->findBy(['code' => 'productstatus']);
$form = $this->createForm(AttributeForm::class, ['attributes' => $attributes]);

// AttributeForm

$builder
    ->add('attributes', CollectionType::class, [
        'entry_type' => AttributeValueForm::class,
        'allow_add' => true,
        'by_reference' => false,
        'allow_delete' => true,
    ]);

// AttributeValueForm

$builder
    ->add('value', TextType::class, ['label' => false, 'required' => false])
    ->add('active', CheckboxType::class, ['label' => false, 'required' => false])

// Twig view

{{ form_start(form) }}
    {% for attribute in form.attributes.children %}
        <tr>
            <td>{{ form_widget(attribute.value) }}</td>
            <td>{{ form_widget(attribute.active) }}</td>
        </tr>
    {% endfor %}
{{ form_end(form) }}