gpt4 book ai didi

forms - symfony 2 表单类型集合,为模型中的每个新属性更改标签

转载 作者:行者123 更新时间:2023-12-02 02:19:50 24 4
gpt4 key购买 nike

我有 4 个实体作为 ProductProductFeaturesGoodsGoodsFeaturesValue 以及它们之间的关系。我为 Product 添加了一些 Features 然后我想用静态字段 Goods + 一些来自 Product 的新 Features 创建表单对于这个 GoodsGoodsFeaturesValue 中保存的每个 Goods 的值。

如何以“symfony 方式”构建此表单?

更新

我将集合用于其他 Features 并且这个工作正常,但是我如何为每个值设置 ProductFeatures 关系的标签?我可以在渲染 templemate 时执行此操作,但这很糟糕 :)?

//GoodsFormType class
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
//other property...
->add('values', 'collection', array(
'required' => true,
'type' => new GoodsFeaturesValueFormType(),
'allow_add' => false,
'allow_delete' => false,
'by_reference' => false,
))
;
}

//GoodsFeaturesValueFormType
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('value', 'text')
;
}
//controller
public function saveAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$product = $em->getRepository('ShopCoreBundle:Product')->find($id);

if (!$product)
throw $this->createNotFoundException(sprintf('Product with id %s not found', $id));

$features = $em->getRepository('ShopCoreBundle:ProductFeatures')->findByProduct($id);
$goods = new Goods();
$goods->setProduct($product);

foreach ($features as $feature) {
$entity = new GoodsFeaturesValue();
$entity->setFeatures($feature);
$entity->setGoods($goods);
$entity->setProduct($product);
$goods->addGoodsFeaturesValue($entity);
}

$request = $this->getRequest();

$form = $this->createForm(new GoodsFormType(), $goods);
$form->bindRequest($request);

if ($form->isValid()) {
$em->persist($goods);
$em->flush();
return $this->redirect($this->generateUrl('core_product_index'));
}



return array(
'form' => $form->createView(),
'goods' => $goods,
'product' => $product,
'features' => $features,
);
}

最佳答案

这正是我想要的动态属性。您可以使用 FormEventEventSubscriber 作为动态生成表单来执行此操作。 http://symfony.com/doc/master/cookbook/form/dynamic_form_generation.html

因此,在 GoodsFeaturesValueFormType 类中,您创建新的 EventSubscriber 并使用 preSetData 设置带有数据的标签。

更新:Symfony 默认的ResizeFormListener 不会将值传递给它,因此,这将是一个错误。为了支持这一点,修改 ResizeFormListener(使用哪个集合)如下

[before]
91 // Then add all rows again in the correct order
92 foreach ($data as $name => $value) {
93 $form->add($this->factory->createNamed($this->type, $name, null, array_replace(array(
94 'property_path' => '['.$name.']',
95 ), $this->options)));
96 }

[modified]
91 // Then add all rows again in the correct order
92 foreach ($data as $name => $value) {
93 $form->add($this->factory->createNamed($this->type, $name, $value, array_replace(array(
94 'property_path' => '['.$name.']',
95 ), $this->options)));
96 }

关于forms - symfony 2 表单类型集合,为模型中的每个新属性更改标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com