对于表单,我需要一个实体集合,因此使用另一种表单,通过使用原型,我可以添加和删除元素。
问题是我需要用symfony原型来生成新的原型,但是当我具有“ prototype = true”时,event-> getData()每次都会返回null。
常规格式:
->add('profils', CollectionType::class,
array('entry_options' => ['entity_manager' => $this->em],
'entry_type' => ProfilType::class,
'prototype' => true, 'allow_add' => true, 'allow_delete' => true))
profilType(子表单):
class ProfilType extends AbstractType {
private $em;
public function buildForm(FormBuilderInterface $builder, array $options) {
$this->em = $options['entity_manager'];
$builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
$builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
}
protected function addElement(FormInterface $form, Domaine $domaine = null) {
$form->add('fkDomaine', EntityType::class, array(
'class' => 'PDFRecrutementBundle:Domaine',
'choice_label' => 'doLibelle',
'multiple' => false,
'required' => true,
'placeholder' => 'Domaine',
'attr' => array(
'class' => 'select-domaine'
)
));
$sousDomaines = array();
if ($domaine) {
$repoSousDomaine = $this->em->getRepository('PDFRecrutementBundle:Sousdomaine');
$sousDomaines = $repoSousDomaine->createQueryBuilder("q")
->where('q.fkDomaine = :domaineId')
->setParameter('domaineId', $domaine->getDoId())
->getQuery()
->getResult();
}
$form->add('fkSousDomaine', EntityType::class, array(
'class' => 'PDFRecrutementBundle:Sousdomaine',
'choice_label' => 'sdLibelle',
'multiple' => false,
'required' => true,
'choices' => $sousDomaines,
'placeholder' => 'Sous domaine',
'attr' => array(
'class' => 'select-sousdomaine'
)
));
}
function onPreSetData(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$domaine = $data->getFkDomaine() ? $data->getFkDomaine() : null;
$this->addElement($form, $domaine);
}
function onPreSubmit(FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
$domaine = $this->em->getRepository('PDFRecrutementBundle:Domaine')->find($data['fkDomaine']);
$this->addElement($form, $domaine);
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'PDF\RecrutementBundle\Entity\Profil'
));
$resolver->setRequired('entity_manager');
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix() {
return 'pdf_recrutementbundle_profil';
}
}
如果我离开prototype = true,则会出现错误:
在null上调用成员函数
所以我需要在true和event-> getData()处获取原型,而不会返回null,你知道怎么做吗?
答案 0 :(得分:0)
以下是我们其中一个项目的有效示例:
->add('subType', CollectionType::class, [
'entry_type' => MySubClassType::class,
'entry_options' => array ('label' => false),
'label' => 'Awesome label',
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => 0,
'attr' => [
'class' => 'hidden'
]
]
在树枝上
{{ form_widget(form.subtype.vars.prototype.text) }}
即使以这种方式工作,如果“ subType”没有值,它也将为null,因此您仍然必须控制该值...