Skip to content

[Form] DoctrineType, Add widget property to avoid retrieving the whole ChoiceList #3095

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ interface EntityLoaderInterface
* @return array
*/
function getEntities();

/**
* Return an entity that is valid choice in the corresponding choice list.
*
* @return object entity
*/
function getEntity($field, $value);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

namespace Symfony\Bridge\Doctrine\Form\ChoiceList;

use Doctrine\DBAL\Connection;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Doctrine\ORM\QueryBuilder;

Expand Down Expand Up @@ -64,4 +62,15 @@ public function getEntities()
{
return $this->queryBuilder->getQuery()->execute();
}
}

/**
* {@inheritDoc}
*/
public function getEntity($field, $value)
{
$alias = $this->queryBuilder->getRootAlias();
$where = $this->queryBuilder->expr()->eq($alias.'.'.$field, ':getEntity'.$field);

return $this->queryBuilder->andWhere($where)->setParameter('getEntity'.$field, $value)->getQuery()->getOneOrNullResult();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\Form\DataTransformer;

use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\Form\Util\PropertyPath;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\NoResultException;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should not have ORM specific code in this class, and so no use statements from the ORM

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unused use statement


class EntityToIdentifierAndPropertyTransformer implements DataTransformerInterface
{
/**
* @var ObjectManager
*/
private $em;

/**
* @var string
*/
private $class;

/**
* @var \Doctrine\Common\Persistence\Mapping\ClassMetadata
*/
private $classMetadata;

/**
* Contains the query builder that builds the query for fetching the
* entities
*
* This property should only be accessed through queryBuilder.
*
* @var EntityLoaderInterface
*/
private $entityLoader;

/**
* The fields of which the identifier of the underlying class consists
*
* This property should only be accessed through identifier.
*
* @var array
*/
private $identifier = array();

/**
* Property path to access the property value.
*
* @var PropertyPath
*/
private $propertyPath;

/**
* Property field name
*
* @var string
*/
private $property;

/**
* Constructor.
*
* @param ObjectManager $manager An EntityManager instance
* @param string $class The class name
* @param array $identifier The fields of which the identifier of the underlying class consists
* @param string $property The property name
* @param EntityLoaderInterface $entityLoader An optional query builder
*/
public function __construct(ObjectManager $manager, $class, $identifier, $property = null, EntityLoaderInterface $entityLoader = null)
{
$this->em = $manager;
$this->class = $class;
$this->property = $property;
$this->classMetadata = $this->em->getClassMetadata($class);
$this->entityLoader = $entityLoader;
$this->identifier = $identifier;

// The property option defines, which property (path) is used for
// displaying entities as strings
if ($property) {
$this->propertyPath = new PropertyPath($property);
} elseif (!method_exists($this->classMetadata->getName(), '__toString')) {
// Otherwise expect a __toString() method in the entity
throw new FormException('Entities passed to the choice field must have a "__toString()" method defined (or you can also override the "property" option).');
}
}

/**
* Transforms entities into choice keys.
*
* @param object a single entity or NULL
*
* @return mixed An array of choice keys, a single key or NULL
*/
public function transform($entity)
{
if (null === $entity || '' === $entity) {
return array();
}

if (!is_object($entity)) {
throw new UnexpectedTypeException($entity, 'object');
}

if ($entity instanceof Collection) {
throw new \InvalidArgumentException('Expected an object, but got a collection.');
}

$values = array(current($this->identifier) => current($this->getIdentifierValues($entity)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

according to the phpdoc of your constructor, $this->identifier is a string so calling current on it is wrong


if ($this->property) {
$values[$this->property] = $this->propertyPath->getValue($entity);
}

return $values;
}

/**
* Transforms choice keys into entities.
*
* @param mixed $key An array of keys, a single key or NULL
*
* @return object a single entity or NULL
*/
public function reverseTransform($value)
{
if (null === $value) {
return null;
}

if (!is_array($value)) {
throw new UnexpectedTypeException($value, 'array');
}

if (implode('', $value) === '') {
return null;
}

if (count($this->identifier) > 1 && !is_numeric($key)) {
throw new UnexpectedTypeException($key, 'numeric');
}

$id = current($this->identifier);

if (isset($value[$id]) && !ctype_digit($value[$id]) && !is_int($value[$id])) {
throw new TransformationFailedException('Identifier is invalid');
}

$key = $value[$id];

if(null === $key) {
return null;
}

if ($loader = $this->entityLoader) {
$entity = $loader->getEntity(current($this->identifier), $key);
} else {
$entity = $this->em->find($this->class, $key);
}

return $entity;
}

/**
* Returns the values of the identifier fields of an entity.
*
* Doctrine must know about this entity, that is, the entity must already
* be persisted or added to the identity map before. Otherwise an
* exception is thrown.
*
* @param object $entity The entity for which to get the identifier
*
* @return array The identifier values
*
* @throws FormException If the entity does not exist in Doctrine's identity map
*/
public function getIdentifierValues($entity)
{
if (!$this->em->contains($entity)) {
throw new FormException('Entities passed to the choice field must be managed');
}

$this->em->initializeObject($entity);

return $this->classMetadata->getIdentifierValues($entity);
}
}
60 changes: 48 additions & 12 deletions src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
use Symfony\Bridge\Doctrine\Form\EventListener\MergeCollectionListener;
use Symfony\Bridge\Doctrine\Form\DataTransformer\EntitiesToArrayTransformer;
use Symfony\Bridge\Doctrine\Form\DataTransformer\EntityToIdTransformer;
use Symfony\Bridge\Doctrine\Form\DataTransformer\EntityToIdentifierAndPropertyTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Exception\FormException;

abstract class DoctrineType extends AbstractType
{
Expand All @@ -35,13 +37,44 @@ public function __construct(ManagerRegistry $registry)

public function buildForm(FormBuilder $builder, array $options)
{
if ($options['multiple']) {
if ($options['widget'] === 'choice') {
if ($options['multiple']) {
$builder
->addEventSubscriber(new MergeCollectionListener())
->prependClientTransformer(new EntitiesToArrayTransformer($options['choice_list']))
;
} else {
$builder->prependClientTransformer(new EntityToIdTransformer($options['choice_list']));
}
} else {
if ($options['multiple']) {
throw new FormException(sprintf('Using multiple entities is currently only supported with the widget "choice".'));
}

$propertyOptions = $identifierOptions = array();

foreach (array('required', 'translation_domain') as $passOpt) {
$propertyOptions[$passOpt] = $identifierOptions[$passOpt] = $options[$passOpt];
}

if ($options['property']) {
$builder->add($options['property'], 'text', $propertyOptions);
}

//retrieve the identifier to create the child widget.
$manager = $this->registry->getManager($options['em']);
$identifier = $manager->getClassMetadata($options['class'])->getIdentifierFieldNames();

$builder
->addEventSubscriber(new MergeCollectionListener())
->prependClientTransformer(new EntitiesToArrayTransformer($options['choice_list']))
->add(current($identifier), $options['widget'], $identifierOptions)
->prependClientTransformer(new EntityToIdentifierAndPropertyTransformer(
$manager,
$options['class'],
$identifier,
$options['property'],
$options['loader']
))
;
} else {
$builder->prependClientTransformer(new EntityToIdTransformer($options['choice_list']));
}
}

Expand All @@ -50,21 +83,24 @@ public function getDefaultOptions(array $options)
$defaultOptions = array(
'em' => null,
'class' => null,
'identifier' => null,
'property' => null,
'query_builder' => null,
'loader' => null,
'choices' => null,
'group_by' => null,
'widget' => 'choice',
'multiple' => false,
);

$options = array_replace($defaultOptions, $options);

if (!isset($options['choice_list'])) {
$manager = $this->registry->getManager($options['em']);
if (isset($options['query_builder'])) {
$options['loader'] = $this->getLoader($manager, $options);
}
$manager = $this->registry->getManager($options['em']);
if (isset($options['query_builder']) && !isset($options['loader'])) {
$options['loader'] = $defaultOptions['loader'] = $this->getLoader($manager, $options);
}

if (!isset($options['choice_list']) && $options['widget'] === 'choice') {
$defaultOptions['choice_list'] = new EntityChoiceList(
$manager,
$options['class'],
Expand All @@ -89,6 +125,6 @@ abstract protected function getLoader(ObjectManager $manager, array $options);

public function getParent(array $options)
{
return 'choice';
return $options['widget'] === 'choice' ? 'choice' : 'form';
}
}
}
3 changes: 0 additions & 3 deletions src/Symfony/Bridge/Doctrine/Form/Type/EntityType.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
namespace Symfony\Bridge\Doctrine\Form\Type;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\FormBuilder;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;

class EntityType extends DoctrineType
Expand Down