Skip to content

Instantly share code, notes, and snippets.

@kerasai
Last active July 31, 2017 19:00
Show Gist options
  • Save kerasai/2624299241e93cda387c2610aa155bce to your computer and use it in GitHub Desktop.
Save kerasai/2624299241e93cda387c2610aa155bce to your computer and use it in GitHub Desktop.
Sets and clears values from a Drupal entity reference field widget.
<?php
use Behat\Mink\Mink;
use Behat\MinkExtension\Context\MinkAwareContext;
/**
* Class EntityReferenceContext.
*/
class EntityReferenceContext implements MinkAwareContext {
/**
* Mink instance.
*
* @var \Behat\Mink\Mink
*/
protected $mink;
/**
* Mink parameters.
*
* @var array
*/
protected $minkParameters = [];
/**
* {@inheritdoc}
*/
public function setMink(Mink $mink) {
$this->mink = $mink;
}
/**
* {@inheritdoc}
*/
public function setMinkParameters(array $parameters) {
$this->minkParameters = $parameters;
}
/**
* Clears values from an entity reference widget.
*
* @When I clear the references for :name
*/
public function assertClearReferences($name) {
$widget = $this->findEntityReferenceWidget($name);
foreach ($widget->findAll('css', 'table input') as $inputEl) {
/** @var \Behat\Mink\Element\NodeElement $inputEl */
$inputEl->setValue('');
}
}
/**
* Add a value to an entity reference widget.
*
* @When I set a reference to :value for :name
*/
public function assertAddReference($value, $name) {
$widget = $this->findEntityReferenceWidget($name);
/** @var \Behat\Mink\Element\NodeElement[] $inputEls */
$inputEls = $widget->findAll('css', 'table input');
$inputEl = array_pop($inputEls);
// If the last input already has a value, we'll need to press the "add more"
// button and try again.
if ($inputEl->getValue()) {
// @TODO: Make this compatible with JS browsers (AJAX interaction).
$widget->pressButton('Add another item');
$inputEls = $widget->findAll('css', 'table input');
$inputEl = array_pop($inputEls);
}
$inputEl->setValue($value);
}
/**
* Finds an entity reference widget.
*
* @param string $name
* The field name.
*
* @return \Behat\Mink\Element\NodeElement
* The widget.
*
* @throws \Exception
* The the widget is not found.
*/
protected function findEntityReferenceWidget($name) {
$name = trim($name);
// Find all the widgets.
/** @var \Behat\Mink\Element\NodeElement[] $tables */
$widgets = $this->mink->getSession()->getPage()->findAll('css', '.field--widget-entity-reference-autocomplete');
// Filter down to ones with labels matching the name.
$widgets = array_filter($widgets, function ($widget) use ($name) {
/** @var \Behat\Mink\Element\NodeElement $widget */
if ($label = $widget->find('css', '.label')) {
return trim($label->getText()) == $name;
}
return FALSE;
});
// Return the first one.
if (!$widget = reset($widgets)) {
throw new \Exception(sprintf('Unable to find entity reference field "%s".', $name));
}
return $widget;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment