Repeat the same fields in a form

心已入冬 提交于 2019-12-24 07:49:09

问题


What is the best way of repeating the same form fields within a form?


I'd like the user to submit multiple Name / Phone number rows.

class contactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name1', 'text')
            ->add('phone1', 'text');

            ->add('name2', 'text')
            ->add('phone2', 'text');

            ->add('name3', 'text')
            ->add('phone3', 'text');

            ....etc
    }
}

Ideally, I would like the user to enter as many fields as he wants...

1- Is there a way to avoid repeating the code here?

2- How should I store these name/phone in the underlying object?

3- Can I store it as an array, but still apply some validation rules?


回答1:


Try using:

$builder->add('phones', 'collection', array('type' => new PhoneType()));

And 'allow_add' => true in your Form Builder.

Take a look at the How to Embed a Collection of Forms Cookbook page.



来源:https://stackoverflow.com/questions/13132338/repeat-the-same-fields-in-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!