-->

Repeat the same fields in a form

2019-08-10 01:36发布

问题:

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.