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

时间:2022-10-16 18:01:41

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

我有一个表单定义,使用迄今为止伟大的字段类型实体。使用query_builder选项,我选择我的值并显示。

The sad part is, I am required to display a null default value, like all (it's a filter form). I don't like the choices option of entity because I have database values and a FormType shouldn't query the database.

可悲的是,我需要显示一个空的默认值,就像所有(它是一个过滤器形式)。我不喜欢实体的选项选项,因为我有数据库值,而FormType不应该查询数据库。

My approach so far was to implement a custom field type which extends entity and 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.

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

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

3 个解决方案

#1


3  

An alternative approach would be to use a ChoiceList with 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,其中包含从数据库生成的选项,然后在允许empty_value的自定义选择表单类型中使用该选项。

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)

选择清单服务(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

自定义表格类型

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)

自定义表格类型服务(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

在你的形式

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

#2


26  

Here is what works in Symfony 3.0.3

这是Symfony 3.0.3中的工作原理

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

使用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
));

#3


4  

You can use placeholder from 2.6

您可以使用2.6中的占位符

#1


3  

An alternative approach would be to use a ChoiceList with 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,其中包含从数据库生成的选项,然后在允许empty_value的自定义选择表单类型中使用该选项。

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)

选择清单服务(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

自定义表格类型

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)

自定义表格类型服务(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

在你的形式

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

#2


26  

Here is what works in Symfony 3.0.3

这是Symfony 3.0.3中的工作原理

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

使用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
));

#3


4  

You can use placeholder from 2.6

您可以使用2.6中的占位符