2

I need to collect array of data via input fields. For example:

<input name="customer_name" type="text">
<input name="customer_emails[]" type="text">
<input name="customer_emails[]" type="text">
<input name="customer_emails[]" type="text">

How to render this type of form in Symfony2 form builder?

Documentation says:

$builder->add('emails', 'collection', array(
    // each item in the array will be an "email" field
    'type'   => 'email',
    // these options are passed to each "email" type
    'options'  => array(
        'required'  => false,
        'attr'      => array('class' => 'email-box')
    ),
));

It is not clear to me where I should provide the number of email fields I want.

2 Answers 2

3

The exact number of collection fields is determined by the model that's bound to the form. Take a closer look at the last paragraph in Symfony's collection field type documentation:

In both cases, no input fields would render unless your emails data array already contained some emails.

In this simple example, it's still impossible to add new addresses or remove existing addresses. Adding new addresses is possible by using the allow_add option (and optionally the prototype option) (see example below). Removing emails from the emails array is possible with the allow_delete option.

Thus, if you need to accept three email addresses, make sure that the data that's bound to the form has the according values set up, or consider 'allow_add' option of the collection type.

Sign up to request clarification or add additional context in comments.

Comments

2

What @kix said was absolutely correct.

However, if you want to offer initial number of fields you could:

$object = ... # Some object... 
$object->setEmail(array("", "", "")); # for example, 3 addresses
$form = $this->createForm(new SomeFormType(), $object);

####
# REST OF YOUR LOGIC
####

$view = $form->createView();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.