Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Create Menu Item in Joomla

I have created a component in joomla 2.5 that creates a new article and adds that article to a menu item.

Creating the article is working fine, but I am having some trouble with creating the menu item.

I have the following code:

                //add the article to a menu item
                $menuTable = JTable::getInstance('Menu', 'JTable', array());

                    $menuData = array(
                    'menutype' => 'client-pages',
                    'title' => $data[name],
                    'type' => 'component',
                    'component_id' => 22,                  
                    'link' => 'index.php?option=com_content&view=article&id='.$resultID,
                    'language' => '*',
                    'published' => 1,
                    'parent_id' => '1',
                    'level' => 1,
                );

                // Bind data
                if (!$menuTable->bind($menuData))
                {
                    $this->setError($menuTable->getError());
                    return false;
                }

                // Check the data.
                if (!$menuTable->check())
                {
                    $this->setError($menuTable->getError());
                    return false;
                }

                // Store the data.
                if (!$menuTable->store())
                {
                    $this->setError($menuTable->getError());
                    return false;
                }

The error seems to be with setting the parent_id and level. On debugging libraries/joomla/database/tablenested.php sets the parent_id and level to 0. This caused the following error on my administrator page:

Warning: str_repeat() [function.str-repeat]: Second argument has to be greater than or equal to 0 in /Applications/MAMP/htdocs/joomla_2_5/administrator/components/com_menus/views/items/tmpl/default.php on line 129

like image 823
GWed Avatar asked Feb 20 '23 00:02

GWed


1 Answers

Try using JTableNested::setLocation($referenceId, $position = 'after'):

$table->setLocation($parent_id, 'last-child');

I also think that you need to rebuild the path:

// Rebuild the tree path.
if (!$table->rebuildPath($table->id)) {
    $this->setError($table->getError());
    return false;
}

If it still doesn't work, try to find out what MenusModelItem::save does that you don't.

like image 50
Matteus Hemström Avatar answered Feb 27 '23 01:02

Matteus Hemström