Skip to content

Instantly share code, notes, and snippets.

@eaton
Created June 8, 2016 18:50
Show Gist options
  • Save eaton/807d40d393f73c376d223fa7a004df18 to your computer and use it in GitHub Desktop.
Save eaton/807d40d393f73c376d223fa7a004df18 to your computer and use it in GitHub Desktop.
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Component\Utility\Html;
use \Drupal\node\Entity\Node;
function relater_node_presave(EntityInterface $node) {
if ($node->bundle() == 'my_custom_node') {
$embeds = _relater_get_embeds($node);
$node->field_my_entityref->setValue($embeds);
}
}
/**
* @param EntityInterface $node
* @return array
*/
function _relater_get_embeds(EntityInterface $node) {
$entities = array();
$text = $node->field_description[0]->value;
// Our parsing is cribbed from EntityEmbedFilter's process function.
if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $embed) {
/** @var \DOMElement $embed */
$entity = NULL;
try {
$id = $embed->getAttribute('data-entity-id');
$entity = Node::load($id);
if ($entity) {
$entities[] = array('target_id' => $entity->id());
}
} finally {
// We're going to rudely ignore this case.
}
}
}
return $entities;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment