function MenuUiUtility::menuUiNodeSave
Same name and namespace in other branches
- 11.x core/modules/menu_ui/src/MenuUiUtility.php \Drupal\menu_ui\MenuUiUtility::menuUiNodeSave()
Helper function to create or update a menu link for a node.
@internal
Parameters
\Drupal\node\NodeInterface $node: Node entity.
array $values: Values for the menu link.
File
-
core/
modules/ menu_ui/ src/ MenuUiUtility.php, line 33
Class
- MenuUiUtility
- Utility functions for menu_ui.
Namespace
Drupal\menu_uiCode
public function menuUiNodeSave(NodeInterface $node, array $values) : void {
/** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
if (!empty($values['entity_id'])) {
$entity = $this->entityRepository
->getActive('menu_link_content', $values['entity_id']);
if ($entity->isTranslatable() && $node->isTranslatable()) {
if (!$entity->hasTranslation($node->language()
->getId())) {
$entity = $entity->addTranslation($node->language()
->getId(), $entity->toArray());
}
else {
$entity = $entity->getTranslation($node->language()
->getId());
}
}
else {
// Ensure the entity matches the node language.
$entity = $entity->getUntranslated();
$entity->set($entity->getEntityType()
->getKey('langcode'), $node->language()
->getId());
}
}
else {
// Create a new menu_link_content entity.
$entity = $this->entityTypeManager
->getStorage('menu_link_content')
->create([
'link' => [
'uri' => 'entity:node/' . $node->id(),
],
'langcode' => $node->language()
->getId(),
]);
$entity->setPublished();
}
$entity->title->value = trim($values['title']);
$entity->description->value = trim($values['description']);
$entity->menu_name->value = $values['menu_name'];
$entity->parent->value = $values['parent'];
$entity->weight->value = $values['weight'] ?? 0;
if ($entity->isNew()) {
// @todo The menu link doesn't need to be changed in a workspace context.
// Fix this in https://www.drupal.org/project/drupal/issues/3511204.
if (!$node->isDefaultRevision() && $node->hasLinkTemplate('latest-version')) {
// If a new menu link is created while saving the node as a pending
// draft (non-default revision), store it as a link to the latest
// version. That ensures that there is a regular, valid link target
// that is only visible to users with permission to view the latest
// version.
$entity->get('link')->uri = 'internal:/node/' . $node->id() . '/latest';
}
}
else {
$entity->isDefaultRevision($node->isDefaultRevision());
if (!$entity->isDefaultRevision()) {
$entity->setNewRevision();
}
elseif ($entity->get('link')->uri !== 'entity:node/' . $node->id()) {
$entity->get('link')->uri = 'entity:node/' . $node->id();
}
}
$entity->save();
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.