Skip to content

Instantly share code, notes, and snippets.

@suresh-kumara-gist
Created November 18, 2017 07:14
Show Gist options
  • Save suresh-kumara-gist/0f66e94cab089dea7bec414971c28513 to your computer and use it in GitHub Desktop.
Save suresh-kumara-gist/0f66e94cab089dea7bec414971c28513 to your computer and use it in GitHub Desktop.
update menu item parent and weight
/**
* @param string $linkuri
* @param string $menuname
* @return Drupal\menu_link_content\Entity\MenuLinkContent
* An array of menu link content objects
*/
function getMenuLinkContent($linkuri, $menuname) {
return \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(
[
'link__uri' => $linkuri ,
'menu_name' => $menuname,
]
);
}
try {
// menu name.
// @to do change menu name
$menuname = "main";
// child entity id is the entity id whose parent menu link id has to be replaced.
// @to do change child entity id
$childentityid = 108;
$childlinkuri = "entity:node/" . $childentityid;
// @to do get childweight from d7 menu link.
$childweight = 0;
// child menu link content
$cmlc = getMenuLinkContent($childlinkuri, $menuname);
// if we found child menu link then find parent menu link.
If (!empty($cmlc)) {
// @to do change the parent entity id.
$parententityid = 124;
$parentlinkuri = "entity:node/" . $parententityid;
// parent menu link content
$pmlc = getMenuLinkContent($parentlinkuri, $menuname);
if (!empty($pmlc)) {
// parent menu link plugin id
$pmlpi = reset($pmlc)->getPluginId();
}
// get first menulink item ( we are assuming that each node will have only one menu link)
$cmlc = reset($cmlc);
// parent menu link plugin found then only update child menu link parent field.
if ($pmlpi) {
$cmlc->set("parent", $pmlpi);
}
$cmlc->set("weight", $childweight);
$cmlc->save();
}
}
catch (Exception $e) {
\Drupal::logger('widget')->error($e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment