【问题标题】:Symfony - Form with multiple entity objectsSymfony - 具有多个实体对象的表单
【发布时间】:2020-03-13 18:10:34
【问题描述】:

我正在运行 Symfony 3.4 LTS,并且我有一个实体 Attribute

<?php

class Attribute
{

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

    // My getters and setters

数据库表下方:

我想在一个表单中获取所有带有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 没有成功。

【问题讨论】:

  • 我迷路了,尝试了多种方法,仍然没有结果。有什么想法吗?

标签: symfony symfony-3.4


【解决方案1】:

我找到了解决方案:创建 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) }}

【讨论】:

    【解决方案2】:

    您可以在 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))
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2012-10-06
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多