Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a select field's value using only the option's label, not its direct value, when writing a functional test in Symfony2

When writing functional tests, how can I set the value of a select box if I only have the label of the option I want, but not the actual value?

like image 917
mattalxndr Avatar asked Sep 13 '12 21:09

mattalxndr


1 Answers

I'm not sure I got exactly what you need, I suppose you have a form like this

<form action="..." method="post">
    ...
    <select id="my_form_category" name="my_form[category]"> 
        <option value="1">category1</option>
        <option value="2">category2</option>
        <option value="3">category3</option>
   </select>
   ...
   <button type="submit">Edit</button>

 </form>

and you want to select category2. Even if you don't know the option value you can use the crawler to extract it

$client = static::createClient();
// go to form
$crawler = $client->request('GET', '...');
$value = $crawler->filter('#my_form_category option:contains("category2")')->attr('value');
$form = $crawler->selectButton('Edit')->form();
$form['my_form[category]']->select($value);
// ... set other values
$client->submit($form);
like image 69
mgiagnoni Avatar answered Sep 19 '22 00:09

mgiagnoni