首页 > 解决方案 > 如何使用基于数据库行的 N 个表单填充 Smyfony CollectionType

问题描述

我有一个我创建的 EditAnnouncementType 类型表单的 CollectionType。此 CollectionType 将用于呈现表单以处理用户编辑公告的某些文本,其中每个公告都有自己的打开的编辑模式(模式具有唯一的 ID)

$editForm = $this->createFormBuilder()
        ->add('editForms', CollectionType::class,
            [
                'entry_type' => EditAnnouncementType::class,
                'allow_add' => true,
                'prototype' => true,
                'by_reference' => false,
                'required' => false,
        ])
        ->add('edit', SubmitType::class,
            array
            (
                'label' => 'Save changes',
                'attr' => ['class' => 'btn btn-primary']
            ))
        ->setData($this->getDoctrine()->getRepository(Announcement::class)->findAll())
        ->getForm()
        ;

如何根据 N 行(又名 N 个公告实体)预填 N 个表单。

表单类型代码

class EditAnnouncementType extends AbstractType

{ /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('edit', SubmitType::class, array ( 'label ' => '保存更改', 'attr' => ['class' => 'btn btn-primary'] )) ->add('id', HiddenType::class, []) ; }

/**
 * Returns the name of this type.
 *
 * @return string
 */
public function getName()
{
    return 'edit_announcement';
}

}

标签: phpsymfony

解决方案


试试这个

$editForm = $this->createFormBuilder()
        ->add('editForms', CollectionType::class,
            [
                'entry_type' => EditAnnouncementType::class,
                'allow_add' => true,
                'prototype' => true,
                'by_reference' => false,
                'required' => false,
        ])
        ->add('edit', SubmitType::class,
            array
            (
                'label' => 'Save changes',
                'attr' => ['class' => 'btn btn-primary']
            ))
        ->setData(['editForms' => $this->getDoctrine()->getRepository(Announcement::class)->findAll()])
        ->getForm()
        ;

推荐阅读