我正在尝试做一个表格,我可以在其中添加尽可能多的产品选项(所以用原型收集)。为此,我需要两个字段,一个是选项定义,第二个是选项值。
我有这样的实体:产品、选项、选项定义和产品选项连接(我决定使用两个多对一而不是一个多对多,所以在产品定义连接中我得到了选项的多对多和产品的多对多)。
当我向产品添加选项时,我想首先选择选项定义,然后使用选项更新选择框。这一切正常,但问题是当我想编辑产品时,它会向我显示默认选项定义。例如,当我创建产品时,我添加了带有选项定义尺寸的产品,尺寸的值为 40。当我要编辑产品时,我得到选项定义颜色和尺寸 40。
这是我的意思的图片:
在第二行应该有一个大小而不是颜色。
在这里,您还可以看到我是如何连接表的:
ProductOptionsType 类
public function buildForm(FormBuilderInterface $builder, array $options)
{
$factory = $builder->getFormFactory();
$builder
->add('optiondefinitions', 'entity', array(
'mapped' => false,
'class' => 'ePOS\ProductsBundle\Entity\OptionsDefinitions',
'query_builder' => function ($repository) { return $repository->createQueryBuilder('p')->orderBy('p.name', 'ASC'); },
'property' => 'name',
'attr' => array('class' => 'option-definitions')))
;
$refreshOptions = function ($form, $option) use ($factory) {
$form->add($factory->createNamed('options', 'entity', null, array(
'class' => 'ePOS\ProductsBundle\Entity\Options',
'property' => 'value',
'label' => false,
'auto_initialize' => false,
'query_builder' => function ($repository) use ($option) {
$qb = $repository->createQueryBuilder('options')
->innerJoin('options.optionDefinition', 'optionDefinitions');
if($option instanceof OptionsDefinitions) {
$qb = $qb->where('options.optionDefinition = :optiondefinitions')
->setParameter('optiondefinitions', $option);
} elseif(is_numeric($option)) {
$qb = $qb->where('options.id = :option_id')
->setParameter('option_id', $option);
} else {
$qb = $qb->where('options.optionDefinition = 1');
}
return $qb;
}
)));
};
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) use ($refreshOptions, $factory) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return ;
}
$refreshOptions($form, $data->getOptions()->getOptionDefinition());
});
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($refreshOptions) {
$form = $event->getForm();
$data = $event->getData();
if($data == null)
$refreshOptions($form, null); //As of beta2, when a form is created setData(null) is called first
if($data instanceof Location) {
$refreshOptions($form, $data->getOptions()->getOptionDefinition());
}
});
$builder->addEventListener(FormEvents::PRE_BIND, function (DataEvent $event) use ($refreshOptions) {
$form = $event->getForm();
$data = $event->getData();
if(array_key_exists('optiondefinitions', $data)) {
$refreshOptions($form, $data['optiondefinitions']);
}
});
}