Skip to content

Commit

Permalink
feature #6427 [Testing] Explain how to add or remove data in a collec…
Browse files Browse the repository at this point in the history
…tion of forms (alexislefebvre)

This PR was merged into the 2.3 branch.

Discussion
----------

[Testing] Explain how to add or remove data in a collection of forms

| Q             | A
| ------------- | ---
| Doc fix?      | no
| New docs?     | no
| Applies to    | all (based on 2.3)
| Fixed tickets | -

I added a part that explain how to test a [*Collection of Forms*](http://symfony.com/doc/2.3/cookbook/form/form_collections.html).

Commits
-------

41276ff Tests: Explain how to add or remove data in a collection of forms
  • Loading branch information
weaverryan committed Apr 26, 2016
2 parents dc7cc73 + 41276ff commit 0882fb5
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions book/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,48 @@ their type::
PHP format (it converts the keys with square brackets notation - e.g.
``my_form[subject]`` - to PHP arrays).

If you use a :doc:`Collection of Forms </cookbook/form/form_collections>`,
you can't add fields to an existing form with
``$form['task[tags][0][name]'] = 'foo';``. This results in an error
``Unreachable field "…"`` because ``$form`` can only be used in order to
set values of existing fields. In order to add new fields, you have to
add the values to the raw data array::

// Get the form.
$form = $crawler->filter('button')->form();

// Get the raw values.
$values = $form->getPhpValues();

// Add fields to the raw values.
$values['task']['tag'][0]['name'] = 'foo';
$values['task']['tag'][1]['name'] = 'bar';

// Submit the form with the existing and new values.
$crawler = $this->client->request($form->getMethod(), $form->getUri(), $values,
$form->getPhpFiles());

// The 2 tags have been added to the collection.
$this->assertEquals(2, $crawler->filter('ul.tags > li')->count());

Where ``task[tags][0][name]`` is the name of a field created
with JavaScript.

You can remove an existing field, e.g. a tag::

// Get the values of the form.
$values = $form->getPhpValues();

// Remove the first tag.
unset($values['task']['tags'][0]);

// Submit the data.
$crawler = $client->request($form->getMethod(), $form->getUri(),
$values, $form->getPhpFiles());

// The tag has been removed.
$this->assertEquals(0, $crawler->filter('ul.tags > li')->count());

.. index::
pair: Tests; Configuration

Expand Down

0 comments on commit 0882fb5

Please sign in to comment.