Search code examples
symfonydomcrawler

Get list of select option values using symfony domcrawler


In a unit test, I want to obtain the list of select option values.

My page contains a form with a dropdown list

<form name='myform'>
  <select id='list' name='formvalues[list]'>
    <option value='1'>Option 1</option>
    <option value='2'>Option 2</option>
  </select>
</form>

In my unit test,

    $client = static::createClient();       
    $crawler    = $client->request('GET', 'http://my.testapp.com/');

    // Try 1
    $form1 = $crawler->selectButton('web_advert_search[search]')->form();
    // Try 2
    // $form2 = $crawler->filter('#web_advert_search_search');

    // I want something liks this
    $values = $form['formvalues[list]']->availableOptionValues();

form2->html() and form2->text() is giving me the details of the form button.


Solution

  • I managed to solve this by progressively traversing the returning elements.

    $client = static::createClient();
    $crawler    = $client->request('GET', 'http://my.testapp.com/');
    $response   = $client->getResponse();
    
    // web_advert_search[search] is the NAME of the submit button for the form.
    $searchForm = $crawler->selectButton('web_advert_search[search]')->form();
    $searchFormCategorySelect   = $searchForm['web_advert_search']['category'];
    $searchFormCategoryOptions  = $searchFormCategorySelect->availableOptionValues();
    $this->assertEquals(10, count($searchFormCategoryOptions));