ChoiceLoader example

return self::loader($formTypenew CallbackChoiceLoader($choices)$vary);
    }

    /** * Decorates a loader to make it cacheable. * * @param ChoiceLoaderInterface $loader A loader responsible for creating loading choices or grouped choices * @param mixed $vary Dynamic data used to compute a unique hash when caching the loader */
    public static function loader(FormTypeInterface|FormTypeExtensionInterface $formType, ChoiceLoaderInterface $loader, mixed $vary = null): ChoiceLoader
    {
        return new ChoiceLoader($formType$loader$vary);
    }

    /** * Decorates a "choice_value" callback to make it cacheable. * * @param callable|array $value Any pseudo callable to create a unique string value from a choice * @param mixed $vary Dynamic data used to compute a unique hash when caching the callback */
    public static function value(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $value, mixed $vary = null): ChoiceValue
    {
        return new ChoiceValue($formType$value$vary);
    }
use Symfony\Component\Form\Tests\Fixtures\ArrayChoiceLoader;

class ChoiceLoaderTest extends TestCase
{
    public function testSameFormTypeUseCachedLoader()
    {
        $choices = ['f' => 'foo', 'b' => 'bar', 'z' => 'baz'];
        $choiceList = new ArrayChoiceList($choices);

        $type = new FormType();
        $decorated = new CallbackChoiceLoader(static fn () => $choices);
        $loader1 = new ChoiceLoader($type$decorated);
        $loader2 = new ChoiceLoader($typenew ArrayChoiceLoader());

        $this->assertEquals($choiceList$loader1->loadChoiceList());
        $this->assertEquals($choiceList$loader2->loadChoiceList());

        $this->assertSame($choices$loader1->loadChoicesForValues($choices));
        $this->assertSame($choices$loader2->loadChoicesForValues($choices));

        $this->assertSame($choices$loader1->loadValuesForChoices($choices));
        $this->assertSame($choices$loader2->loadValuesForChoices($choices));
    }
}
Home | Imprint | This part of the site doesn't use cookies.