gpt4 book ai didi

php - Symfony2 : Entity form field with empty value

转载 作者:可可西里 更新时间:2023-10-31 22:05:52 25 4
gpt4 key购买 nike

我有一个表单定义,它使用了迄今为止最棒的字段类型 entity。使用选项 query_builder 我选择我的值并显示。

可悲的是,我需要显示一个null 默认值,比如all(它是一个过滤器形式)。我不喜欢 entitychoices 选项,因为我有数据库值,而 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';
}
}

最佳答案

这是 Symfony 3.0.3 中的工作

使用 Symfony\Bridge\Doctrine\Form\Type\EntityType;

$builder->add('example' EntityType::class, array(
'label' => 'Example',
'class' => 'AppBundle:Example',
'placeholder' => 'Please choose',
'empty_data' => null,
'required' => false
));

关于php - Symfony2 : Entity form field with empty value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29030418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com