在 Symfony 的 EntityType 上设置默认选项 [英] Setting a default choice on Symfony's EntityType
本文介绍了在 Symfony 的 EntityType 上设置默认选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Symfony 的 EntityType 上设置默认选项,以便在绑定的表单对象没有值时使用?
How can I set a default choice on Symfony's EntityType, to use when the bound form object does not have a value?
我已经尝试了以下(在这个答案中建议),但是data
option 甚至会覆盖一个绑定值.
I've tried the following (suggested in this answer), but the data
option overwrites even a bound value.
class FooEntityType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
...
$resolver->setDefaults([
'choices' => $fooEntities,
'class' => 'FooBundle:FooEntity',
'choice_label' => 'name',
'expanded' => true,
'multiple' => false,
'data' => $fooEntities[0],
]);
}
public function getParent()
{
return EntityType::class;
}
}
推荐答案
- 您应该将此代码移至 Type 中的 buildForm(FormBuilderInterface $builder, array $options) 方法
试试这个
- you should move this code to buildForm(FormBuilderInterface $builder, array $options) method in your Type
try this
$entity = $options['data']; // this will be your entity
// form builder
$builder->add('entityProperty', EntityType::class, [
'choices' => $fooEntities,
'class' => 'FooBundle:FooEntity',
'choice_label' => 'name',
'expanded' => true,
'multiple' => false,
'data' => $entity->getEntityProperty() ? $entity->getEntityProperty() : $fooEntities[0]
]);
你也可以通过表单事件来解决这个问题,但不值得
Also you can solve this workaround by form events, but it does not worth it
这篇关于在 Symfony 的 EntityType 上设置默认选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文