'Symfony3, how to load an external choice list in a form?
I don't know if I'm facing a bug or doing something wrong. I'm trying to load choices for a ChoiceType form from a custom class, but I get the following error:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\Form\ChoiceList\LazyChoiceList::__construct() must be an instance of Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface, none given
My custom class:
<?php
namespace AppBundle\Form\ChoiceLists;
use Symfony\Component\Form\ChoiceList\SimpleChoiceList;
use Symfony\Component\Form\ChoiceList\LazyChoiceList;
class DepartmentsChoiceList extends LazyChoiceList
{
public function loadChoiceList()
{
$choices = array(
'01' => "Ain",
'02' => "Aisne",
'03' => "Allier",
'04' => "Alpes de Haute Provence",
'05' => "Alpes (Hautes)",
//....
'94' => "Val de Marne",
'95' => "Val d´Oise",
'98' => "Mayotte",
'9A' => "Guadeloupe",
'9B' => "Guyane",
'9C' => "Martinique",
'9D' => "Réunion",
);
return new SimpleChoiceList($choices);
}
}
And in my formType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('birthDepartment', ChoiceType::class, array(
'label' => 'Département :',
'required' => false,
'choices' => new DepartmentsChoiceList(),
)
);
I found very few documentation for this feature.
Solution 1:[1]
Here is my procedure on Symfony 5.4. It may not be the best way to do it, but it's the only one I found that works.
<?php
namespace App\Form;
use App\Controller\ApiController;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
class DepartmentChoiceList implements ChoiceLoaderInterface
{
public function loadChoiceList($value = null)
{
$choices = array(
'01' => "Ain",
'02' => "Aisne",
'03' => "Allier",
'04' => "Alpes de Haute Provence",
'05' => "Alpes (Hautes)",
//....
'94' => "Val de Marne",
'95' => "Val d´Oise",
'98' => "Mayotte",
'9A' => "Guadeloupe",
'9B' => "Guyane",
'9C' => "Martinique",
'9D' => "Réunion",
);
return new ArrayChoiceList($choices);
}
public function loadChoicesForValues(array $values, $value = null)
{
$result = [];
return $result;
}
public function loadValuesForChoices(array $choices, $value = null)
{
$result = [];
return $result;
}
}
And formType
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('department', ChoiceType::class, [
'label' => 'Department',
'choice_loader' => new DepartmentChoiceList(),
'constraints' => [
new NotBlank(),
],
])
->add('save', SubmitType::class)
;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elell |
