Testing Symfony 2 Forms with Multiple Checkboxes

checkbox-gridThe thing I find most frustrating about Symfony’s documentation is that it always seems to fall just shy of getting me over the finish line.

And those extra few yards can take an absolute age to travel.

I needed to test a checkbox field – not the actual ‘checkbox‘ field type, rather an entity field type inside a collection that was rendered with checkboxes (multiple => true, expanded => true).

Three cheers for making that one confusing.

There’s a nice piece inside the dom crawler documentation that kinda explains how to do this, but not exactly:

// check or uncheck a checkbox


Well, great that is until you realise your form looks more like this:

// check or uncheck a checkbox

That is – you have maybe 5 checkboxes and they all have that exact same html form field name, but a slightly different ID.

So I tried the ID. No dice.

Then I tried to use the $form->setValue method described in the documentation. Turns out that method is not allowed – not sure why that’s still on there.

Then I found a poor soul who had been through the same trauma I just experienced, over at that wealth of obscure knowledge, Stack Overflow.

Craig, being the good man that he is, not only posted up the problem, but replied – the only reply I might add – with the solution.

It’s people like Craig who make the Internet a better place.

Anyway, for those of you who can’t be arsed clicked all these links I have so helpfully provided, the solution is as follows:

// check or uncheck a checkbox

Where the number is the zero index of the array of buttons you are trying to click.

After that it works like a PyCharm.