【问题标题】:How to embed a form multiple times in Symfony如何在 Symfony 中多次嵌入表单
【发布时间】:2016-12-15 04:49:56
【问题描述】:

我有 2 个实体:Tarifa 和 TarifaPeso(这个实体必须在 Tarifa 表单中出现 20 次)。

Tarifa 中的关系是:

    /**
 * @ORM\OneToMany(targetEntity="TarifaPeso", mappedBy="tarifa", cascade={"persist"})
 */
private $pesos;

我已经嵌入了 Symfony2 文档所说的表单,一切正常,但我不想动态地这样做,它必须只出现 20 次。所以Tarifa是一个表格,必须嵌入20个TarifaPeso表格。

你知道怎么做吗?谢谢

【问题讨论】:

  • 不要使用实体类“Tarifa”作为表单的底层数据类,而是创建另外两个类,例如“[your bundle]/Form/Model/Tarifa”和“[your bundle] /Form/Model/TarifaPeso”。然后将 20 个 TarifaPeso 实例添加到 Tarifa 并显示表单。提交表单后,从 Tarifa 中选择所有数据,实例化并存储您的实体。为此做一个服务,不要在控制器中做。

标签: php forms symfony embed


【解决方案1】:

由于您维护了 @ORM\OneToMany 关联,Collection Field Type 应该可以解决您的目的。在生成表单之前,您只需要将 TarifaPeso 的 20 个实例与 Tarifa 实体关联起来。

See here如何嵌入集合表单类型。

确保您已从 Tarifa 实体自动启用 cascade-persist insertupdate TarifaPeso 实体。

根据我对 Collection 字段类型的经验。就数据完整性而言,这将更快、更容易。

【讨论】:

    【解决方案2】:

    最后我在父表单类的构造函数中(在实体中)做到了:

        $this->envios = new \Doctrine\Common\Collections\ArrayCollection();
        for ($i = 0; $i < count(self::$KILOS); $i++) {
            $peso = new TarifaPeso();
            $peso->setKilosMaxlim(self::$KILOS[$i]);
            $this->addPeso($peso);
        }
    

    拥有$KILOS:

    private static $KILOS = array(1,2,3,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,300,500,1000,1001);
    

    这样我用 eventListener 修改表单:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('precio', null, array(
                'attr' => array('autofocus' => true),
                'label' => 'label.precio ' ,
            ));
        ;
    
        $builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event)
        {
            $form = $event->getForm();
            $data = $event->getData();
            if ($data) {
                $valor = $data->getKilosMaxlim();
    
                $field = $form->get('precio');
                $config = $field->getConfig();
                $options = $config->getOptions();
                $options['label'] = 'Valor para '.$valor; // change the label
                $form->add($field->getName(), $config->getType()->getName(), $options);
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多