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



我有一个表单定义,它使用到目前为止伟大的字段类型entity。使用选项query_builder我选择我的值并显示。

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

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

您可以使用 2.6 中的占位符

另一种方法是将ChoiceList与从数据库生成的选项一起使用,然后在允许empty_value的自定义选择表单类型中使用它。

选择列表

namespace AcmeYourBundleFormChoiceList;
use DoctrineCommonPersistenceObjectManager;
use SymfonyComponentFormExtensionCoreChoiceListLazyChoiceList;
use SymfonyComponentFormExtensionCoreChoiceListChoiceListInterface;
use SymfonyComponentFormExtensionCoreChoiceListSimpleChoiceList;
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: AcmeYourBundleFormChoiceListMachineChoiceList
    arguments:
        - @doctrine.orm.default_entity_manager
        - %acme.model.machine.class%

自定义表单类型

namespace AcmeYourBundleFormType;
use AcmeYourBundleFormChoiceListMachineChoiceList;
..
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: AcmeYourBundleFormTypeFirstNullEntityType
    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,
    ])
;

相关内容

  • 没有找到相关文章

最新更新