简体   繁体   中英

How can i get ID of entity in Field form <select>

I have an entity A and BA(id,#Bid) B(id,name)

In Symfony i would like a form to create entity A with a select field which list all B entity with for label B.name and for value B.id

I currently have something like:

$builder->add('companyid', 'entity', array(
      'class' => 'Bundle:B',
      'property' => 'name',
));

I would like to generate something like this and only get the ID for value not the entire object :

<option value="id_of_B">name_of_B</option>

First way is to use DataTransformer to transform form value from entity to id property.

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

Define form as a service and inject DataTransformer class into it.

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>

Form class.

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

Second way is a bit easier. You can define your form as a service, inject entity manager into it and populate choice field with required values from repository method.

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>

Form class.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM