我不知道我是面临错误还是做错了什么。我正试图从自定义类加载ChoiceType表单的选项,但我得到了以下错误:
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
我的自定义类:
<?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);
}
}
在我的表格中类型:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('birthDepartment', ChoiceType::class, array(
'label' => 'Département :',
'required' => false,
'choices' => new DepartmentsChoiceList(),
)
);
我发现这个功能的文档很少。
以下是我在Symfony 5.4上的过程。这可能不是最好的方法,但这是我发现的唯一有效的方法。
<?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;
}
}
和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)
;
}