我有两个实体,其中包含许多 - >多个关系, appli 和服务 我想创建一个允许我编辑,添加或删除关系的表单。
这些实体链接如下..
Appli.php:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Service", mappedBy="applis")
*/
private $services;
public function getService() {
return $this->services;
}
Service.php:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Appli", inversedBy="services")
* @ORM\JoinTable(name="service_to_app",
* joinColumns={@ORM\JoinColumn(name="services", referencedColumnName="id_service")},
* inverseJoinColumns={@ORM\JoinColumn(name="applis", referencedColumnName="id_apps")}
* )
*/
private $applis;
请注意,$ services和$ applis是arrayCollections。
这是我的formType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$item = $builder->getData();
$builder /* ... */
->add('serviceCol', CollectionType::class, array(
'entry_type' => ServiceType::class,
'entry_options' => array('label' => false,),
'property_path' => 'service',
'allow_add' => true, 'allow_delete' => true,
));
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => Appli::class,
));
}
和serviceType:
class ServiceType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('service', EntityType::class, array(
'class' => Service::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('s')
->orderBy('s.id_service', 'ASC');},
'choice_label' => 'nom', 'property_path' => 'nom', 'label' => false));
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => Service::class,
));
}
}
到目前为止我的问题是预先选择关系,我确实有正确数量的字段,但它只是默认值,并没有显示现有的关系。 我可以在不使用CollectionType字段的情况下使用它,但之后,我将无法添加/删除字段。
我无法填写数据'选项,因为$ item-> getService()给出了一个arrayCollection,我找不到在Collection定义中迭代它的方法。
对此有什么简单的解决方案吗?
答案 0 :(得分:0)
所以修复非常简单,解决方案在Symfony form - Access Entity inside child entry Type in a CollectionType 它还让我重新注意了How to Dynamically Modify Forms Using Form Events!
这里是我的ServiceType formBuilder:
$builder->addEventListener(FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($builder) {
$form = $event->getForm();
$service = $event->getData();
if($service instanceof Service) {
$form->add('service', EntityType::class, array(
'class' => Service::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('s')
->orderBy('s.id_service', 'ASC');},
'choice_label' => 'nom',
'property_path' => 'nom',
'label' => false,
'data' => $service ));
}
})
;