-
-
Save jasonawant/c897f69a44da2910dd97fbbb8cd33612 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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