I am trying to create a Joomla 4 Plugin that copies a menu item with its module assignments. My code works well on J3, but not J4. What am I missing?
Here is my plugin's code:
<?php
/**
* @package Joomla.Plugin
* @subpackage Content.CopyModuleAssignments
* @since 4.0
*
* @copyright Copyright (C) 2022
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
declare(strict_types=1);
namespace Joomla\Plugin\Content;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Table\Table;
use Joomla\Registry\Registry;
/**
* Copy Module Assignments Plugin
*/
class CopyModuleAssignmentsPlugin extends CMSPlugin
{
/**
* Plugin that copies module assignments from original to new menu item when using "Save as copy"
*
* @param string $context The context of the content being passed to the plugin.
* @param Table $table An object with a "text" property
* @param bool $isNew True if this item is being created.
*
* @return bool True on success.
*/
public function onContentAfterSave(string $context, Table $table, bool $isNew): bool
{
// Return if invalid context
if ($context !== 'com_menus.item')
{
return true;
}
// Return if items is not a product of "Save as copy"
if (!($table->get('_location_id') > 1 && $isNew === false))
{
return true;
}
// Get the database object
$db = Factory::getDbo();
// Find all assigned modules
$query1 = $db->getQuery(true)
->select($db->quoteName('moduleid'))
->from($db->quoteName('#__modules_menu'))
->where($db->quoteName('menuid') . ' = ' . $table->get('_location_id'));
$db->setQuery($query1);
$modules = (array) $db->loadColumn();
// Assign all found modules to copied menu item
if (!empty($modules))
{
foreach ($modules as $mid)
{
$mdl = new \stdClass();
$mdl->moduleid = $mid;
$mdl->menuid = $table->get('id');
$db->insertObject('#__modules_menu', $mdl);
}
}
// Check if menu item is on the assign to all except list
$query2 = $db->getQuery(true)
->select($db->quoteName('moduleid'))
->from($db->quoteName('#__modules_menu'))
->where($db->quoteName('menuid') . ' = -' . $table->get('_location_id'));
$db->setQuery($query2);
$modulesExcept = (array) $db->loadColumn();
// Add menu item to the exception list for all modules that have the original one in there
if (!empty($modulesExcept))
{
foreach ($modulesExcept as $mid)
{
$mdl = new \stdClass();
$mdl->moduleid = $mid;
$mdl->menuid = $table->get('id') * -1;
$db->insertObject('#__modules_menu', $mdl);
}
}
return true;
}
}