Symfony2 functional test to select checkboxes

喜夏-厌秋 提交于 2020-01-29 06:28:10

问题


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 "".


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/13906928/symfony2-functional-test-to-select-checkboxes

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