php Symfony2:具有空值的实体表单字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29030418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:12:33  来源:igfitidea点击:

Symfony2: Entity form field with empty value

phpsymfonydoctrine-orm

提问by Joshua

i have a form definition which uses the so-far great field type entity. With the option query_builderI select my values and the are displayed.

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

The sad part is, I am required to display a nulldefault value, like all(it's a filter form). I don't like the choicesoption of entitybecause I have database values and a FormTypeshouldn't query the database.

可悲的是,我需要显示一个null默认值,比如all(它是一个过滤器表单)。我不喜欢 的choices选项,entity因为我有数据库值并且FormType不应该查询数据库。

My approach so far was to implement a custom field type which extends entityand adds a null entry to the top of the list. The field type is loaded and used but unfortunately the dummy value is not displayed.

到目前为止,我的方法是实现一个自定义字段类型,它扩展entity并在列表顶部添加一个空条目。字段类型已加载并使用,但遗憾的是未显示虚拟值。

The field definition:

字段定义:

$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');
    }
]);

The form type definition:

表单类型定义:

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';
    }
}

采纳答案by qooplmao

An alternative approach would be to use a ChoiceListwith choices that are generated from the database and then use that in a custom choice form type that will allow for an empty_value.

另一种方法是使用ChoiceList从数据库生成的with 选项,然后在允许empty_value.

Choice List

Choice List

namespace Acme\YourBundle\Form\ChoiceList;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;

class MachineChoiceList extends LazyChoiceList
{
    protected $repository;

    protected $mandator;

    public function __construct(ObjectManager $manager, $class)
    {
        $this->repository = $manager->getRepository($class);
    }

    /**
     * Set mandator
     *
     * @param $mandator
     * @return $this
     */
    public function setMandator($mandator)
    {
        $this->mandator = $mandator;

        return $this;
    }

    /**
     * Get machine choices from DB and convert to an array
     *
     * @return array
     */
    private function getMachineChoices()
    {
        $criteria = array();

        if (null !== $this->mandator) {
            $criteria['mandator'] = $this->mandator;
        }

        $items = $this->repository->findBy($criteria, array('name', 'ASC'));

        $choices = array();

        foreach ($items as $item) {
            $choices[** db value **] = ** select value **;
        }

        return $choices;
    }

    /**
     * {@inheritdoc}
     */
    protected function loadChoiceList()
    {
        return new SimpleChoiceList($this->getMachineChoices());
    }
}

Choice List Service (YAML)

Choice List Service (YAML)

acme.form.choice_list.machine:
    class: Acme\YourBundle\Form\ChoiceList\MachineChoiceList
    arguments:
        - @doctrine.orm.default_entity_manager
        - %acme.model.machine.class%

Custom Form Type

Custom Form Type

namespace Acme\YourBundle\Form\Type;

use Acme\YourBundle\Form\ChoiceList\MachineChoiceList;
..

class FirstNullEntityType extends AbstractType
{
    /**
     * @var ChoiceListInterface
     */
    private $choiceList;

    public function __construct(MachineChoiceList $choiceList)
    {
        $this->choiceList = $choiceList;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $choiceList = $this->choiceList;

        $resolver->setDefault('mandator', null);

        $resolver->setDefault('choice_list', function(Options $options) use ($choiceList) {
            if (null !== $options['mandator']) {
                $choiceList->setMandator($options['mandator']);
            }

            return $choiceList;
        });
    }

    public function getName()
    {
        return 'first_null_entity';
    }

    public function getParent()
    {
        return 'choice';
    }
}

Custom Form Type Service (YAML)

Custom Form Type Service (YAML)

acme.form.type.machine:
    class: Acme\YourBundle\Form\Type\FirstNullEntityType
    arguments:
        - @acme.form.choice_list.machine
    tags:
        - { name: form.type, alias: first_null_entity }

In Your Form

In Your Form

$builder
    ->add('machine', 'first_null_entity', [
        'empty_value'   => 'None Selected',
        'label'         => 'label.machine',
        'required'      => false,
    ])
;

回答by Pavel Petrov

Here is what works in Symfony 3.0.3

这是 Symfony 3.0.3 中的工作原理

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

use 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
));

回答by nvvetal

You can use placeholder from 2.6

您可以使用 2.6 中的占位符