Skip to content

Instantly share code, notes, and snippets.

@akovalyov
Created September 29, 2015 12:06
Show Gist options
  • Save akovalyov/0e9e1a827d95fd96a3ee to your computer and use it in GitHub Desktop.
Save akovalyov/0e9e1a827d95fd96a3ee to your computer and use it in GitHub Desktop.
<?php
class Select2Context{
public function iCompleteSelect2($term, $field, $entry)
{
if (!($driver = $this->getDriver()) instanceof Selenium2Driver) {
throw new \InvalidArgumentException('Don\'t use select2 in non-selenium env');
}
$this->openField($field);
$this->fillSearchField($field, $term);
$this->selectValue($field, $entry);
}
/**
*
* @param string $field
* @throws \Exception
*/
private function openField($field)
{
$this->getDriver()->evaluateScript(sprintf('$("#%s").select2("open");', $field));
}
/**
* Fill Select2 search field
*
* @param string $field
* @param string $value
* @throws \Exception
*/
private function fillSearchField($field, $value)
{
$driver = $this->getDriver();
// Can't use `$this->getSession()->getPage()->find()` because of https://github.com/minkphp/MinkSelenium2Driver/issues/188
$select2Input = $driver->getWebDriverSession()->element(LocatorStrategy::CSS_SELECTOR, ".select2-container--open .select2-search__field");
if (!$select2Input) {
throw new \Exception(sprintf('No field "%s" found', $field));
}
$chars = str_split($value);
foreach($chars as $char){
$select2Input->postValue(['value' => [$char]]);
}
//so async
sleep('5');
//$this->getSession()->wait(10000, '(0 === jQuery.active)');
}
/**
* @param string $field
* @param string $value
* @throws \Exception
*/
private function selectValue($field, $value)
{
$chosenResults = $this->findElements('.select2-results__option--highlighted');
foreach ($chosenResults as $result) {
if ($result->getText() == $value) {
$result->click();
return;
}
}
throw new \Exception(sprintf('Value "%s" not found for "%s"', $value, $field));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment