I have what I thought would be a simple challenge: to automate publishing an article and trigger the onAfterContentSave event for saving the article. This code ultimately has to run within another plugin: Community Builder Auto Actions triggered by a Joomla! 4 Task Scheduler task. For now I am testing this at the command line using a verified working framework loading script.
I am not sure what I am doing wrong, but here's the code thus far. The techniques used below (middle to end of code) were obtained elsewhere online.
include ("joomla-framework.php");
use Joomla\CMS\Plugin\PluginHelper;
// (THIS WORKS) Get the oldest unpublished article whose title includes the word "test" and whose publish date is in the future.
$db = JFactory::getDbo();
$db->setQuery("SELECT id FROM `#__content` WHERE title LIKE '%test%' AND state=0 ORDER BY created ASC LIMIT 1;");
$articleId = $db->loadResult();
if ($articleId) // if there isn't one, don't do anything.
{
// (THIS WORKS) make sure the article is published
$article = JTable::getInstance('content');
$article->load($articleId);
$article->state = 1;
$article->store();
$params = new stdClass();
/*
// (THIS DOESN'T WORK) trigger the onContentAfterSave event for this article
PluginHelper::importPlugin('content');
$app = JFactory::getApplication();
$app->triggerEvent('onContentAfterSave', array('com_content.article', &$article, &$params, 0));
*/
// This doesn't seem to work either, but it was my last attempt
$dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();
$event = new Joomla\Event\Event('onContentAfterSave', array('com_content.article', &$article, &$params, 0));
$res = $dispatcher->dispatch('onContentAfterSave', $event);
The idea here is to trigger onContentAfterSave on the identified article, which has a custom field (flag) telling one of my plugins to send an email containing the article. That plugin works perfectly when saving a published article in either the site front or back end, but I need to be able to trigger it from a Task Scheduler cronjob.
Any assistance would be truly appreciated. Thanks in advance!
P.S. No errors are occurring with either of the two above triggering methods.
Edit: Looking around a bit more, I think that first method was along the right line. Here's what I think that last part should look like. Note that this doesn't trigger the event either.
// trigger the onContentAfterSave event for this article (THIS DOESN'T WORK)
Factory::getApplication()->triggerEvent('onContentAfterSave', ['com_content.article', &$article, false, array()]);
Bruce
Joomla\CMS\Factory::getApplication()
is actually causing an error. Would need to see contents ofjoomla-framework.php
to confirm. And if you intend to use Joomla's task scheduler, you should develop a task plugin instead of creating an external script.