如何在字段表单中获取实体ID <select>

时间:2015-07-08 15:25:12

标签: php forms entity-framework symfony select

我有一个实体A和B. A(ID,#BID) B(ID,姓名) 在Symfony中,我想要一个表单来创建一个带有select字段的实体A,该字段列出所有B实体,标签为B.name,值为B.id 我目前有类似的东西: $ builder-&gt; add(&#39; companyid&#39;,&#39; entity&#39;,array(       &#39;类&#39; =&GT; &#39;软件包:B&#39 ;,       &#39;属性&#39; =&GT; &#39;名称&#39 ;, )); 我想生成这样的东西,只获得值的ID而不是整个对象: &lt; option value =&#34; id_of_B&#34;&gt; name_of_B&lt; / option&gt;

1 个答案:

答案 0 :(得分:0)

第一种方法是使用DataTransformer将表单值从实体转换为id属性。

的services.xml

<service id="bundle.b_to_id_transformer" class="Bundle\Form\DataTransformer\BtoIdTransformer">
    <argument type="service" id="doctrine.orm.entity_manager" />
</service>

BtoIdTransformer.php

<?php

namespace Bundle\Form\DataTransformer;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Bundle\Entity\B;

class BtoIdTransformer implements DataTransformerInterface
{
    /**
     * @var ObjectManager
     */
    protected $om;

    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
    }

    /**
     * @param mixed $value
     * @return null|string
     */
    public function transform($value)
    {
        if (null === $value) {
            return null;
        }

        if (! $value instanceof B) {
            throw new UnexpectedTypeException($value, 'B');
        }

        return $value->getId();
    }

    /**
     * @param mixed $value
     * @return mixed|null
     */
    public function reverseTransform($value)
    {
        if (null === $value || '' === $value) {
            return null;
        }

        if (! is_string($value)) {
            throw new UnexpectedTypeException($value, 'string');
        }

        return $this->om->getRepository('Bundle:B')->find($value);
    }
}

将表单定义为服务并将DataTransformer类注入其中。

的services.xml

<service id="bundle.form.a" class="Bundle\Form\AType">
    <tag name="form.type" alias="bundle_a" />
    <argument type="service" id="bundle.b_to_id_transformer" />
</service>

表格课程。

<?php

namespace Bundle\Form;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class AType extends AbstractType
{
    /**
     * @var DataTransformerInterface
     */
    protected $transformer;

    /**
     * @param DataTransformerInterface $transformer
     */
    public function __construct(DataTransformerInterface $transformer)
    {
        $this->transformer = $transformer;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {          
        $builder->add($builder->create('companyid', 'entity', array(
            'label'         => 'companyid',
            'class'         => 'Bundle\Entity\B',
            'property'      => 'name',
            'query_builder' => function ($repository) {
                return $repository->createQueryBuilder('b');
            },
        ))->addModelTransformer($this->transformer));
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Bundle\Entity\A',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'bundle_a';
    }
}

第二种方式更容易一些。您可以将表单定义为服务,将实体管理器注入其中,并使用存储库方法中的必需值填充选择字段。

的services.xml

<service id="bundle.form.a" class="Bundle\Form\AType">
    <tag name="form.type" alias="bundle_a" />
    <argument type="service" id="doctrine.orm.entity_manager" />
</service>

表格类。

<?php

namespace Bundle\Form;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class AType extends AbstractType
{
    /**
     * @var EntityManagerInterface
     */
    protected $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('companied', 'choice', [
            'label'    => 'companyid',
            'choices'  => $this->em->getRepository('Bundle:B')->getChoices(),
        ]);
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Bundle\Entity\A',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'app_a';
    }
}

BRepository.php

public function getChoices()
{
    $bs = $this->createQueryBuilder('b')
        ->getQuery()
        ->getResult();

    $result = [];
    /** @var B $b */
    foreach ($bs as $b) {
        $result[$b->getId()] = $b->getName();
    }

    return $result;
}