[英]Symfony 4 - ChoiceType field null when form submitted
I'm trying to pass associative array as options for a ChoiceType field in my OrdreMissionType form :我正在尝试将关联数组作为我的 OrdreMissionType 表单中的 ChoiceType 字段的选项传递:
$typeJour = ['Travaillée(s)' => "T", 'Calendaire(s)' => "C"];
$form = $this->createForm(OrdreMissionType::class, $odm,[
'user' => $user,
'affairesOdm' => $affairesForm,
'typeJour' => $typeJour,
'method' => 'PUT'
]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$odm = $form->getData();
dd($odm);
$em = $this->getDoctrine()->getManager();
$em->persist($odm);
$em->flush();
}
My FormType class :我的 FormType 类:
class OrdreMissionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
//...
$typeJour = $options['typeJour'];
$builder->add('typeJour', ChoiceType::class, [
'label' => 'Type de(s) journée(s)',
'placeholder' => 'Sélectionnez une option',
'choices' => $typeJour,
'label_attr' => ['class' => 'radio-inline'],
]);
//...
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'typeJour' => false,
'data_class' => OrdreMission::class
]);
}
}
My Entity :我的实体:
class OrdreMission
{
//...
/**
* @ORM\Column(type="string", length=255)
*/
private $typeJour;
//...
}
My problem is, when I submit the form, the 'typeForm' field is always null, here's the output of the 'dd' line :我的问题是,当我提交表单时,“typeForm”字段始终为空,这是“dd”行的输出:
I don't want to put the choices in a specific table on my database, because they will never change.我不想将这些选择放在我数据库的特定表中,因为它们永远不会改变。 Does somebody knows how to fix this problem ?有人知道如何解决这个问题吗? Any help would be grateful.任何帮助将不胜感激。 Thank you in advance !先感谢您 !
You need to add optinon 'empty_data' into field properties of your form.您需要将 optinon 'empty_data' 添加到表单的字段属性中。
public function buildForm(FormBuilderInterface $builder, array $options)
{
//...
$typeJour = $options['typeJour'];
$builder->add('typeJour', ChoiceType::class, [
'empty_data' => 'T', //OR C
'label' => 'Type de(s) journée(s)',
'placeholder' => 'Sélectionnez une option',
'choices' => $typeJour,
'label_attr' => ['class' => 'radio-inline'],
]);
//...
}
FYI: method configureOptions() is not for confugure particular fields, it is form configuration.仅供参考:方法 configureOptions() 不是用于配置特定字段,它是表单配置。 Also, you can't assign default value not from scope(T or C in your case)此外,您不能指定不在范围内的默认值(在您的情况下为 T 或 C)
I found a workaround for this problem, I added the option "expanded => true" and my field takes now the value selected.我找到了解决此问题的方法,我添加了选项“expanded => true”,我的字段现在采用所选值。 I do not have the same graphic rendering, but at least, it's working !我没有相同的图形渲染,但至少,它正在工作!
$builder->add('typeJour', ChoiceType::class, [
'label' => 'Type de(s) journée(s)',
'placeholder' => 'Sélectionnez une option',
'expanded' => true,
'choices' => ['Travaillée(s)' => "T", 'Calendaire(s)' => "C"]
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.