12

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.

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.

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';
    }
}
1
  • you can use $choices[''] = 'All'; in your form type definition Commented Mar 13, 2015 at 12:10

3 Answers 3

30

Here is what works in Symfony 3.0.3

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
));
Sign up to request clarification or add additional context in comments.

2 Comments

Be aware empty_data => null will not work with ChoiceType
Setting the placeholder to an empty string like this: 'placeholder' => '' works well.
4

You can use placeholder from 2.6

1 Comment

placeholder doesnt seems to work with query_builder
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.

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)

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)

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,
    ])
;

7 Comments

Thank you for your great answer. This way, I have to register both MachineChoiceList and FirstNullEntityType as service and have to pass the list to the type, don't I?
Yeah, that's correct. I've updated my answers with the YAML versions of those services.
Thank you for your help. I ended up building the ChoiceList directly in the field type as it appears more flexible to me. The key was to extend the choice field as you suggested.
What ever float your boat, man. Glad to have helped a little.
Notice: empty_value is replaced in Symfony v2.6 with a placeholder, for all the choice fields (symfony.com/doc/2.6/reference/forms/types/…)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.