Get parent menu item object in plugin

by thednp   Last Updated April 26, 2019 07:10 AM - source

Problem

Working with a code variation from this tutorial I'm trying to get the parent menu item instance object of a given item (currently editing) and it always returns null.

/**
 * Prepare form and add my field.
 *
 * @param   JForm  $form  The form to be altered.
 * @param   mixed  $data  The associated data for the form.
 *
 * @return  boolean
 *
 * @since   0.0.1
 */
function onContentPrepareForm($form, $data)
{
    $app    = JFactory::getApplication();
    $menu   = $app->getMenu();
    $pid    = $data->parent_id;
    $parent = $menu->getItem($pid);
    $items  = $menu->getItems('menutype', $data->menutype);

    var_dump($data->parent_id); 
    // returns the parent_id string of the currently edited menu item

    var_dump($parent); 
    // returns null

    var_dump($items); 
    // returns null as well
}

Questions:

  • Should I change the order of the plugins so mine executes last or hopefully after everything is initialized?
  • Should I use a different callback other than onContentPrepareForm?
  • Should I include/require anything from Joomla? If so, what is it?


Answers 1


Since you are editing from administrator section, $app->getMenu() returns administrator menu items. Pass client argument if you need site items:

$menu = $app->getMenu('site');

Should I change the order of the plugins so mine executes last or hopefully after everything is initialized?

Probably not. Just note that plugin order does decide the order in which the form is altered. E.g. you might need to tweak the order in case you have multiple plugins modifying the same field. Or if you have dependencies on other plugins.

Should I use a different callback other than onContentPrepareForm?

No, if you want to modify a form, this is the event to use. But at the very least you should check that you are modifying the correct form (or multiple forms).

public function onContentPrepareForm($form, $data)
{
    // Check that we are editing a menu item.
    if ($form->getName() !== 'com_menus.item')
    {
        return true;
    }

    // Do our stuff.
}
Sharky
Sharky
April 26, 2019 07:14 AM

Related Questions


Fieldparams from custom field

Updated September 13, 2017 19:10 PM


Decorate Menu Option

Updated May 23, 2017 18:10 PM

How do I add custom HTML into a menu?

Updated January 01, 2018 03:10 AM

Custom fields depending on admin menu

Updated March 25, 2018 09:10 AM