Skip to content

Commit aa2f51b

Browse files
feature #52503 [DoctrineBridge][Form] Introducing new LazyChoiceLoader class and choice_lazy option for ChoiceType (yceruto)
This PR was merged into the 7.2 branch. Discussion ---------- [DoctrineBridge][Form] Introducing new `LazyChoiceLoader` class and `choice_lazy` option for `ChoiceType` | Q | A | ------------- | --- | Branch? | 7.2 | Bug fix? | no | New feature? | yes | Deprecations? | no | Issues | #57724 | License | MIT It's quite usual to work with forms that process large datasets. In Symfony Form + Doctrine ORM, if you define an `EntityType`, it typically loads all choices/entities fully into memory, and this can lead to serious performance problems if your entity table contain several hundred or thousands of records. The new `LazyChoiceLoader` class addresses this performance issue by implementing an on-demand choice loading strategy. This class is integrated with any `ChoiceType` subtype by using a new boolean option named `choice_lazy`, which activates the feature. Basic usage in a Symfony form looks like this: ```php $formBuilder->add('user', EntityType::class, [ 'class' => User::class, // a ton of users... 'choice_lazy' => true, ]); ``` **How does it work?** The loader operates by keeping the choice list empty until values are needed (avoiding unnecessary database queries). When form values are provided or submitted, it retrieves and caches only the necessary choices. As you can see in the code, all this happens behind the `LazyChoiceLoader` class, which delegates the loading of choices to a wrapped `ChoiceLoaderInterface` adapter (in this case, the `DoctrineChoiceLoader`). **Frontend Considerations** Certainly, you may need a JavaScript component for dynamically loading `<select>` options, aka autocomplete plugins. You'll need to develop the endpoint/controller to fetch this data on your own, ensuring it corresponds to the form field data source. This aspect is not included in this project. As a point of reference, the [Autocomplete UX Component](https://symfony.com/bundles/ux-autocomplete/current/index.html) now uses this choice loading strategy, simplifying its autocomplete form type to a single field: <img src="https://symfony.com/doc/bundles/ux-autocomplete/2.x/ux-autocomplete-animation.gif"/> **A Handy Use Case without Javascript?** The `disabled` option renders an `EntityType` form field read-only, and when combined with the `choice_lazy` option, it prevents the loading of unnecessary entities in your choice list (only the pre-selected entities will be loaded), thereby enhancing performance. --- Hope this helps to create simpler autocomplete components for Symfony forms. Cheers! Commits ------- d73b5eecc90 add LazyChoiceLoader and choice_lazy option
2 parents 5235274 + b113970 commit aa2f51b

File tree

1 file changed

+125
-0
lines changed

1 file changed

+125
-0
lines changed

Tests/Form/Type/EntityTypeTest.php

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringCastableIdEntity;
3131
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity;
3232
use Symfony\Component\Form\ChoiceList\LazyChoiceList;
33+
use Symfony\Component\Form\ChoiceList\Loader\LazyChoiceLoader;
3334
use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView;
3435
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
3536
use Symfony\Component\Form\Exception\RuntimeException;
@@ -1758,4 +1759,128 @@ public function testWithSameLoaderAndDifferentChoiceValueCallbacks()
17581759
$this->assertSame('Foo', $view['entity_two']->vars['choices']['Foo']->value);
17591760
$this->assertSame('Bar', $view['entity_two']->vars['choices']['Bar']->value);
17601761
}
1762+
1763+
public function testEmptyChoicesWhenLazy()
1764+
{
1765+
if (!class_exists(LazyChoiceLoader::class)) {
1766+
$this->markTestSkipped('This test requires symfony/form 7.2 or superior.');
1767+
}
1768+
1769+
$entity1 = new SingleIntIdEntity(1, 'Foo');
1770+
$entity2 = new SingleIntIdEntity(2, 'Bar');
1771+
$this->persist([$entity1, $entity2]);
1772+
1773+
$view = $this->factory->create(FormTypeTest::TESTED_TYPE)
1774+
->add('entity_one', self::TESTED_TYPE, [
1775+
'em' => 'default',
1776+
'class' => self::SINGLE_IDENT_CLASS,
1777+
'choice_lazy' => true,
1778+
])
1779+
->createView()
1780+
;
1781+
1782+
$this->assertCount(0, $view['entity_one']->vars['choices']);
1783+
}
1784+
1785+
public function testLoadedChoicesWhenLazyAndBoundData()
1786+
{
1787+
if (!class_exists(LazyChoiceLoader::class)) {
1788+
$this->markTestSkipped('This test requires symfony/form 7.2 or superior.');
1789+
}
1790+
1791+
$entity1 = new SingleIntIdEntity(1, 'Foo');
1792+
$entity2 = new SingleIntIdEntity(2, 'Bar');
1793+
$this->persist([$entity1, $entity2]);
1794+
1795+
$view = $this->factory->create(FormTypeTest::TESTED_TYPE, ['entity_one' => $entity1])
1796+
->add('entity_one', self::TESTED_TYPE, [
1797+
'em' => 'default',
1798+
'class' => self::SINGLE_IDENT_CLASS,
1799+
'choice_lazy' => true,
1800+
])
1801+
->createView()
1802+
;
1803+
1804+
$this->assertCount(1, $view['entity_one']->vars['choices']);
1805+
$this->assertSame('1', $view['entity_one']->vars['choices'][1]->value);
1806+
}
1807+
1808+
public function testLoadedChoicesWhenLazyAndSubmittedData()
1809+
{
1810+
if (!class_exists(LazyChoiceLoader::class)) {
1811+
$this->markTestSkipped('This test requires symfony/form 7.2 or superior.');
1812+
}
1813+
1814+
$entity1 = new SingleIntIdEntity(1, 'Foo');
1815+
$entity2 = new SingleIntIdEntity(2, 'Bar');
1816+
$this->persist([$entity1, $entity2]);
1817+
1818+
$view = $this->factory->create(FormTypeTest::TESTED_TYPE)
1819+
->add('entity_one', self::TESTED_TYPE, [
1820+
'em' => 'default',
1821+
'class' => self::SINGLE_IDENT_CLASS,
1822+
'choice_lazy' => true,
1823+
])
1824+
->submit(['entity_one' => '2'])
1825+
->createView()
1826+
;
1827+
1828+
$this->assertCount(1, $view['entity_one']->vars['choices']);
1829+
$this->assertSame('2', $view['entity_one']->vars['choices'][2]->value);
1830+
}
1831+
1832+
public function testEmptyChoicesWhenLazyAndEmptyDataIsSubmitted()
1833+
{
1834+
if (!class_exists(LazyChoiceLoader::class)) {
1835+
$this->markTestSkipped('This test requires symfony/form 7.2 or superior.');
1836+
}
1837+
1838+
$entity1 = new SingleIntIdEntity(1, 'Foo');
1839+
$entity2 = new SingleIntIdEntity(2, 'Bar');
1840+
$this->persist([$entity1, $entity2]);
1841+
1842+
$view = $this->factory->create(FormTypeTest::TESTED_TYPE, ['entity_one' => $entity1])
1843+
->add('entity_one', self::TESTED_TYPE, [
1844+
'em' => 'default',
1845+
'class' => self::SINGLE_IDENT_CLASS,
1846+
'choice_lazy' => true,
1847+
])
1848+
->submit([])
1849+
->createView()
1850+
;
1851+
1852+
$this->assertCount(0, $view['entity_one']->vars['choices']);
1853+
}
1854+
1855+
public function testErrorOnSubmitInvalidValuesWhenLazyAndCustomQueryBuilder()
1856+
{
1857+
if (!class_exists(LazyChoiceLoader::class)) {
1858+
$this->markTestSkipped('This test requires symfony/form 7.2 or superior.');
1859+
}
1860+
1861+
$entity1 = new SingleIntIdEntity(1, 'Foo');
1862+
$entity2 = new SingleIntIdEntity(2, 'Bar');
1863+
$this->persist([$entity1, $entity2]);
1864+
$qb = $this->em
1865+
->createQueryBuilder()
1866+
->select('e')
1867+
->from(self::SINGLE_IDENT_CLASS, 'e')
1868+
->where('e.id = 2')
1869+
;
1870+
1871+
$form = $this->factory->create(FormTypeTest::TESTED_TYPE, ['entity_one' => $entity2])
1872+
->add('entity_one', self::TESTED_TYPE, [
1873+
'em' => 'default',
1874+
'class' => self::SINGLE_IDENT_CLASS,
1875+
'query_builder' => $qb,
1876+
'choice_lazy' => true,
1877+
])
1878+
->submit(['entity_one' => '1'])
1879+
;
1880+
$view = $form->createView();
1881+
1882+
$this->assertCount(0, $view['entity_one']->vars['choices']);
1883+
$this->assertCount(1, $errors = $form->getErrors(true));
1884+
$this->assertSame('The selected choice is invalid.', $errors->current()->getMessage());
1885+
}
17611886
}

0 commit comments

Comments
 (0)