我想制作一个带有“选择”选项的表格,以选择一种语言。默认情况下,我想“选择”用户的区域设置选项。
(...)
use Symfony\Component\HttpFoundation\Request;
(...)
class VisitType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options, Request $request)
{
$locale = $request->getLocale();
if ($locale == 'fr'){
$prefLang = "Français";
}elseif ($locale == 'nl'){
$prefLang = "Nederlands";
}elseif ($locale == 'en') {
$prefLang = "English";
}
$builder->add('langvis', ChoiceType::class, [
'label' => 'form.input.langvis',
'choices' => [
'Français' => 'Français',
'Nederlands' => 'Nederlands',
'English' => 'English'
],
'preferred_choices' => [$prefLang]
])
->add('save', SubmitType::class, [
'label' => 'form.input.send',
'attr' => [
'class' => 'btn btn-primary form-control'
]
])
->getForm();
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Visit::class
]);
}
}
但是我有一个编译错误:
声明 App \ Form \ VisitType :: buildForm(Symfony \ Component \ Form \ FormBuilderInterface $ builder,数组$ options,Symfony \ Component \ HttpFoundation \ Request $ request)必须与 Symfony \ Component \ Form \ AbstractType :: buildForm(Symfony \ Component \ Form \ FormBuilderInterface $ builder,数组$ options)
我该怎么做?
答案 0 :(得分:0)
您无法在buildForm上传递请求,请尝试使用OptionsResolver
class VisitType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$locale = $options["locale"];
if ($locale == 'fr') {
$prefLang = "Français";
} elseif ($locale == 'nl') {
$prefLang = "Nederlands";
} elseif ($locale == 'en') {
$prefLang = "English";
}
$builder->add('langvis', ChoiceType::class, [
'label' => 'form.input.langvis',
'choices' => [
'Français' => 'Français',
'Nederlands' => 'Nederlands',
'English' => 'English'
],
'preferred_choices' => [$prefLang]
])
->add('save', SubmitType::class, [
'label' => 'form.input.send',
'attr' => [
'class' => 'btn btn-primary form-control'
]
])
->getForm();
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => Visit::class,
'locale' => 'Français'
]);
}
在控制器中,当您创建表单传递区域设置参数时:
$locale = $request->getLocale();
$formType = 'VisitType';
$entity = 'VisitEntity';
$form = $this->createForm($formType, $entity, array('locale' => $locale));