首页 > 解决方案 > Symfony 嵌入式 ChoiceType 表单更新每个实体实例

问题描述

我有一个EditAnnouncementType嵌入在表单中的CollectionType表单。嵌入表单有两种ChoiceType形式,一种可以正确更新映射的Announcement实体。但是,另一个将尝试更新我的数据库中实体的所有实例,从而导致此错误。

类型错误:传递给 AppBundle\Entity\Announcement::setType() 的参数 1 必须是整数类型,给定 null,在 /Users/dperezpe/dev/grand-central/673/grand-central/vendor/symfony/ 中调用symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php 第 528 行

EditAnnouncementType.phptype表单是错误之一。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('edit', SubmitType::class,
            array
            (
                'label' => 'Save changes',
                'attr' => ['class' => 'btn btn-primary']

            ))

        ->add('type', ChoiceType::class,
            [
                'choices' =>
                    [
                    'info_type' => 1,
                    'star_type' => 2,
                    'alert_type' => 3,
                    'lightbulb_type' => 4,
                    'event_type' => 5,
                    'statement_type' => 6,
                    'cat_type' => 7,
                    'hands_type' => 8
                ],
                'expanded' => true,
                'multiple' => false,
                'required' => true,
                'label_attr' => array(
                    'class' => 'sr-only'
                ),
            ])


          ->add('audience', ChoiceType::class,
              [
                  'choices' =>
                      [
                          'Students: anybody with a student level field populated' => 'students',
                          'Employees: anybody with an employee ID number' => 'employees'
                      ],
                  'expanded' => true,
                  'required' => true,
                  'multiple' => true
                      ])

集合类型

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('announcements', CollectionType::class,
        [
            'entry_type' => EditAnnouncementType::class,
            'entry_options' => ['label' => false],
        ]);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => AnnouncementManager::class
    ]);
}

我怀疑这与呈现给它的 HTML 名称的差异有关,其中类型输入缺少一个空[]

<input type="radio" 
id="announcement_edit_collection_announcements_221_type_0" 
name="announcement_edit_collection[announcements][221][type]" 
required="required" value="1">


<input type="checkbox" id="announcement_edit_collection_announcements_221_audience_0"
 name="announcement_edit_collection[announcements][221][audience][]
"value="students">

标签: phpsymfonysymfony-forms

解决方案


推荐阅读