我有一个表单定义,它使用了迄今为止最棒的字段类型entity
。使用选项query_builder
我选择我的值并显示。Symfony2:具有空值的实体表单字段
可悲的是,我需要显示null
默认值,如all
(这是一个过滤器形式)。我不喜欢选项entity
,因为我有数据库值,FormType
不应该查询数据库。
我到目前为止的做法是实现一个自定义字段类型,它扩展了entity
并在列表顶部添加了一个空条目。字段类型被加载和使用,但不幸的是,虚拟值不被显示。
字段定义:
$builder->add('machine', 'first_null_entity', [
'label' => 'label.machine',
'class' => Machine::ident(),
'query_builder' => function (EntityRepository $repo)
{
return $repo->createQueryBuilder('m')
->where('m.mandator = :mandator')
->setParameter('mandator', $this->mandator)
->orderBy('m.name', 'ASC');
}
]);
形式类型定义:
class FirstNullEntityType extends AbstractType
{
/**
* @var unknown
*/
private $doctrine;
public function __construct(ContainerInterface $container)
{
$this->doctrine = $container->get('doctrine');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setRequired('query_builder');
$resolver->setRequired('class');
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$class = $options['class'];
$repo = $this->doctrine->getRepository($class);
$builder = $options['query_builder']($repo);
$entities = $builder->getQuery()->execute();
// add dummy entry to start of array
if($entities) {
$dummy = new \stdClass();
$dummy->__toString = function() {
return '';
};
array_unshift($entities, $dummy);
}
$options['choices'] = $entities;
}
public function getName()
{
return 'first_null_entity';
}
public function getParent()
{
return 'entity';
}
}
你可以使用$ choices [''] ='All';在你的表单类型定义 – 2015-03-13 12:10:06