1

Am using Drupal 7. Below is my code where am trying to create menu links programmatically:

$links[] = array(
'menu_name' => 'management',
'link_path' => 'myheader/config',
'link_title' => 'Header Settings',
'options' => array(),
'weight' => 2,
'parent' => 'custom/header-settings',
);
$links[] = array(
'menu_name' => 'mycustommenu',
'link_path' => 'myheader/config',
'link_title' => 'Header Settings',
'options' => array(),
'weight' => 2,
'parent' => 'custom/header-settings',
);

In the above code, only menu_name is different. Rest of them are same. Is there a way to pass multiple arguments to menu_name?

1

No. When you're building links for D7's menu system, you'll need to specify the entire link array because you're creating link metadata here. If you're trying to keep your code DRY you could try to create a template array (or function) then copy/update as you needed new links, but you're probably doing just as much work for little/no performance gain or clarity.

0

Your code seems to define some menu links. You have to return an array with all menu links you want to define, and there's no way to define multiple menu links using a parameter or similar.

What you can do is to construct the array programmatically:

$link_template = array(

  'link_path' => 'myheader/config',
  'link_title' => 'Header Settings',
  'options' => array(),
  'weight' => 2,
  'parent' => 'custom/header-settings',
);

$menu_names = array('management', 'mycustommenu');

$links = [];

foreach ($menu_names as $menu_name) {
  $links[] = array('menu_name' => $menu_name) + $link_template;
}

This way you have only one array where you can modify menu properties (the $link_template variable), and a list where you can easily add new menu entries ($menu_names variable).

No performance gain, but menu properties are defined just once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.