簡體   English   中英

Symfony2:具有空值的實體表單字段

[英]Symfony2: Entity form field with empty value

我有一個表單定義,使用迄今為止偉大的字段類型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中的工作原理

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

您可以使用2.6中的占位符

另一種方法是使用ChoiceList和從數據庫生成的選項,然后在允許empty_value的自定義選擇表單類型中使用empty_value

選擇清單

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());
    }
}

選擇清單服務(YAML)

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

自定義表單類型

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

自定義表格類型服務(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 }

在你的形式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM