Skip to content

Commit 835077e

Browse files
committed
[DoctrineBridge] Fixed submitting invalid ids when using queries with limit
1 parent bf877b8 commit 835077e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php

+15
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,21 @@ public function getEntities()
5555
*/
5656
public function getEntitiesByIds($identifier, array $values)
5757
{
58+
if (null !== $this->queryBuilder->getMaxResults() || null !== $this->queryBuilder->getFirstResult()) {
59+
// an offset or a limit would apply on results including the where clause with submitted id values
60+
// that could make invalid choices valid
61+
$choices = [];
62+
$metadata = $this->queryBuilder->getEntityManager()->getClassMetadata(current($this->queryBuilder->getRootEntities()));
63+
64+
foreach ($this->getEntities() as $entity) {
65+
if (in_array(current($metadata->getIdentifierValues($entity)), $values, true)) {
66+
$choices[] = $entity;
67+
}
68+
}
69+
70+
return $choices;
71+
}
72+
5873
$qb = clone $this->queryBuilder;
5974
$alias = current($qb->getRootAliases());
6075
$parameter = 'ORMQueryBuilderLoader_getEntitiesByIds_'.$identifier;

src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php

+25
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,31 @@ public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleIdentifie
955955
$this->assertNull($field->getData());
956956
}
957957

958+
public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleIdentifierWithLimit()
959+
{
960+
$entity1 = new SingleIntIdEntity(1, 'Foo');
961+
$entity2 = new SingleIntIdEntity(2, 'Bar');
962+
$entity3 = new SingleIntIdEntity(3, 'Baz');
963+
964+
$this->persist([$entity1, $entity2, $entity3]);
965+
966+
$repository = $this->em->getRepository(self::SINGLE_IDENT_CLASS);
967+
968+
$field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [
969+
'em' => 'default',
970+
'class' => self::SINGLE_IDENT_CLASS,
971+
'query_builder' => $repository->createQueryBuilder('e')
972+
->where('e.id IN (1, 2, 3)')
973+
->setMaxResults(1),
974+
'choice_label' => 'name',
975+
]);
976+
977+
$field->submit('3');
978+
979+
$this->assertFalse($field->isSynchronized());
980+
$this->assertNull($field->getData());
981+
}
982+
958983
public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleAssocIdentifier()
959984
{
960985
$innerEntity1 = new SingleIntIdNoToStringEntity(1, 'InFoo');

0 commit comments

Comments
 (0)