我的表格分几个阶段进行,包括:
步骤1:基于实体1的简单形式,其记录数据集的第一部分。步骤2:父表单(基于步骤1中的实体1),其实现子表单(基于实体2)=> CollectionType。父表单($ builder)包含步骤1中的数据,但不包含子表单。
我的目标很简单:我的子表单包含一个ChoiceType,它必须根据给定的内容而变化
我的问题:传递给子表单父表单的数据($ builder-> getData())为我的ChoiceType设置一个选项条件。
我寻找解决方案,但我没有找到任何结果。所以我认为我的问题不是一个错误,而是一个糟糕的方法。
我测试过:
//PARENT
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('wans', CollectionType::class,
[
'entry_type' => WanDType::class,
'entry_options' => [
'label' => false,
'data' => $builder->getData() // <- here
],
]);
}
//ENFANT
public function buildForm(FormBuilderInterface $builder, array $options)
{
$ma_valeur = $builder->getData()->getValue(); //<- here
if(in_array($ma_valeur, ['1'])) { //<- here
$builder->add('profil', ChoiceType::class, [
'choices' => [
[...]
],
'label' => false,
]);
} else { //<- here
$builder->add('profil', ChoiceType::class, [
'choices' => [
[...]
],
'label' => false,
]);
} //<- here
}
=>我得到一个错误,解释我的data_class与我的子表单不匹配。实际上,父表单的data_class已替换子表单的数据。该错误建议给它null值,但它会导致其他错误,symfony越来越不快乐(逻辑,在我看来不是一个好的做法)。
=>我试图使用$ options。 Symfony不高兴,因为他拒绝添加条目key =>他在原点不知道的值。
=>我想过以父母的形式表达自己的状况。但是这种情况会随着时间的推移而发展,所以在我看来,按照条件类型创建一个儿童形式并不是一个好习惯。
=>我还考虑过在视图中直接创建这个字段。但根据演变,这也不是最优的。
=>我测试了几件在这里没用的东西,每次都是负面的结果。
我强烈怀疑SensioLabs没有想到那种事情。我可能不需要很远,如果有人知道如何解释,那将是美好的。
谢谢你的帮助 :)
====================================================
编辑测试1
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
dump($event->getForm()->getParent()->getData());
die('ok');
});
die('ok2');
}
所以。我没有发现这非常直观。没有什么能解释当一个人想要影响集合所包含的实体时,如何在集合的上下文中理解这种技术。
所以,我们不关心父母和子女形式的概念。它只是干预受我们修改影响的表单(如果它是子代,它将在formType子代中)。
基本上,这给了这个:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add([....]); // without the fields I want to modulate.
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event){
$wan = $event->getData();
if(in_array($wan->getEquipment()->->getValue(),['1'])) {
$event->getForm()->add('profil', ChoiceType::class, [
'choices' => [
[...]
],
'label' => false,
]);
} else {
$event->getForm()->add('profil', ChoiceType::class, [
'choices' => [
[...]
],
'label' => false,
]);
}
});
}
我认为你正在寻找这样的事情可以提供:https://symfony.com/doc/current/form/dynamic_form_modification.html
有了这个,您将能够根据提供的数据更改您的表单