带有子集合的 Symfony 3 表单集合 [英] Symfony 3 form collection with sub-collection

查看:31
本文介绍了带有子集合的 Symfony 3 表单集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为planes"的字段的表单.

I have a form with a field named "planes".

此字段可以是多个(集合),具有以下子字段:- 速度- 重量- 颜色- 引擎

This field is can be multiple (collection) with the following sub-fields: - speed - weight - color - engines

子字段engines"也是字段的集合:- 转速- 汽油种类- 重量

The subfield "engines" is also a collection of field: - rpm - fuel_type - weight

我想知道 Symfony 表单构建器会是什么样子,因为用户应该有可能添加尽可能多的平面.这同样适用于引擎.

I'm wondering what would the Symfony form builder would looks like since the user should have the possibility to add as much planes as he want. The same apply for engines.

推荐答案

看起来像这样:

具有平面集合的类中的构建器:

builder in class which has planes collection:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('planes', CollectionType::class, array(
            'entry_type' => PlaneType::class,
            'allow_add'    => true,
            'allow_delete' => true, 
            'by_reference' => false,// this will call get/set of your entity
            'prototype' => true, // is needed coz there will be 2 prototypes 
            'prototype_name'=> '__planes__'//1-st prototype name

        ));
    }

PlaneType 类中的构建器:

builder in PlaneType class:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('speed');
        $builder->add('weight');
        $builder->add('color');
        $builder->add('engines', CollectionType::class, array(
            'entry_type' => EngineType::class,
            'allow_add'    => true,
            'allow_delete' => true, 
            'by_reference' => false,// this will call get/set of your entity
            'prototype' => true, // is needed coz there will be 2 prototypes 
            'prototype_name'=> '__engines__'//2 -nd prototype

        ));
    }

EngineType 类中的构建器:

builder in EngineType class:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('rpm');
        $builder->add('fuel_type');
        $builder->add('weight');
    }

另外你应该添加一些javascript来动态添加/删除字段,在添加过程中你应该用字段数的id交换原型名称.

Also you should add some javascript for dynamic adding/removing fields, during adding you should exchange prototype names with the id of number of the fields.

这篇关于带有子集合的 Symfony 3 表单集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆