如何在Symfony的EntityType上设置默认选项,以便在绑定的表单对象没有值时使用?
我已尝试过以下内容(this answer中建议),但data
选项甚至会覆盖绑定值。
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;
}
}
答案 0 :(得分:0)
创建表单后,您应该将实体添加到该方法(假设您在控制器中):
# src/Controller/MainController.php
$entity = new Entity();
$entity->setCertainValue('choice-value');
$form = $this->createForm(EntityType::class, $entity);
$form->handleRequest($request);
if ($form->isValid()) {
// Do something nice with the entity, data is filled here
}
答案 1 :(得分:0)
试试这个
$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]
]);
此外,您可以通过表单事件解决此变通方法,但它不值得