Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 functional test to select checkboxes

I'm having trouble writing a Symfony 2 functional test to set checkboxes that are part of an array (i.e. a multiple and expanded select widget)

In the documentation the example is

$form['registration[interests]']->select(array('symfony', 'cookies'));

But it doesn't show what html that will work with and it doesn't work with mine. Here is a cutdown version of my form

<form class="proxy" action="/proxy/13/update" method="post" >
    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_1" name="niwa_pictbundle_proxytype[chronologyControls][]" value="1" />

    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_2" name="niwa_pictbundle_proxytype[chronologyControls][]" value="2" />

    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_3" name="niwa_pictbundle_proxytype[chronologyControls][]" value="3" />
</form>   

Once it get it working there I'm going to move on to a manually made form

<input type="checkbox" id="13" name="proxyIDs[]" value="13">
<input type="checkbox" id="14" name="proxyIDs[]" value="14">
<input type="checkbox" id="15" name="proxyIDs[]" value="15">

I have tried things like

$form = $crawler->selectButton('Save')->form();
$form['niwa_pictbundle_proxytype[chronologyControls]']->select(array('3'));
$form['niwa_pictbundle_proxytype[chronologyControls][]']->select(array('3'));

but the first fails saying select is being run on a non-object and the second says Unreachable field "".

like image 222
Craig Avatar asked Dec 17 '12 00:12

Craig


2 Answers

I think the most bulletproof solution working in 2017 is to extend your test class:

/**
 * Find checkbox
 * 
 * @param \Symfony\Component\DomCrawler\Form $form
 * @param string $name Field name without trailing '[]'
 * @param string $value
 */
protected function findCheckbox($form, $name, $value)
{
    foreach ($form->offsetGet($name) as $field) {
        $available = $field->availableOptionValues();
        if (strval($value) == reset($available)) {
            return $field;
        }
    }
}

And in the test call:

$this->findCheckbox($form, 'niwa_pictbundle_proxytype[chronologyControls]', 3)->tick();
like image 150
Grzegorz Pietrzak Avatar answered Nov 15 '22 11:11

Grzegorz Pietrzak


Try

$form['niwa_pictbundle_proxytype[chronologyControls]'][0]->tick();

It indexes it from 0 even in the form it says []

Or if it doesn't really helps you, you can try POSTing an array directly to the action instead of using symfony's form selectors. See: Symfony2: Test on ArrayCollection gives "Unreachable field"

Hope one of them helps you.

like image 35
jkrnak Avatar answered Nov 15 '22 11:11

jkrnak