Symfony3表单删除实体

时间:2016-05-27 16:22:27

标签: html-form symfony

我想用Symfony3创建一个表单。它将是一个表格,显示数据库中表格中的所有实体,删除按钮允许通过javascripts删除行。然后单击“应用”按钮,删除缺少的实体:

+----+------+--------+
| ID | Name | Delete |
+----+------+--------+
| 1  | Foo  |   X    |
+----+------+--------+
| 2  | Bar  |   X    |
+----+------+--------+
| 3  | Plop |   X    |
+----+------+--------+

+-------+
| Apply |
+-------+

根据我的理解,CollectionType允许我这样做。但我无法弄清楚如何使用它。确切地说,我不明白实体将在什么时候链接到表单并通过树枝中的表单函数显示。

这是我的代码:

控制器:

class TurnamentController extends Controller
{
    /**
     * @Route("/admin/turnament", name="adminTurnament")
     */
    public function indexAction( Request $request )
    {
        $em = $this->getDoctrine()->getManager();
        $turnaments = $em->getRepository( 'AppBundle:Turnament' )->findAll();

        $form = $this->createFormBuilder()
            ->add( 'turnaments', CollectionType::class, array(
                'entry_type' => TurnamentType::class,
                'entry_options' => $turnaments,
            ))
            ->add( 'apply', SubmitType::class, array(
                'label' => 'Appliquer'
            ))
            ->getForm();

        $form->handleRequest( $request );
        if ( $form->isSubmitted() )
        {
            //...
        }

        return $this->render(
            'admin/turnament.html.twig',
            array(
                'turnamentsForm' => $form
            )
        );
    }
}

TurnamentType:

class TurnementType extends AbstractType
{
    public function buildForm( FormBuilderInterface $builder, array $options )
    {
        $builder->add( 'delete', SubmitType::class );
    }

    public function configureOptions( OptionsResolver $resolver )
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Turnament',
        ));
    }
}

模板:

{{ form_start( turnamentsForm ) }}
{% for turnament in turnamentsForm.turnaments %}
    {{ form_widget(turnament.delete) }}
{% endfor %}
{{ form_widget( turnamentsForm.apply ) }}
{{ form_end( turnamentsForm ) }}

我很失落,我试图使用dump()来查看发生了什么。看起来我在entry_options中传递的$ turnaments不会生成TurnamentTypes ...

欢迎任何帮助!

1 个答案:

答案 0 :(得分:0)

' entry_options' CollectionType的选项会选择直接传递给您输入的entry_type的选项。您正试图直接将锦标赛选项作为选项传递给TurnamentTypeCollectionType如果不包含任何数据,则不会呈现任何字段。因此,您应该将锦标赛设置为集合类型的数据:

$form = $this->createFormBuilder()
    ->add( 'turnaments', CollectionType::class, array(
        'entry_type' => TurnamentType::class,
        'data' => $turnaments,
    ));

有关CollectionType的更多信息,请查看参考指南:http://symfony.com/doc/current/reference/forms/types/collection.html

有关自定义表单类型的一些信息: http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html