4

I am using the below code in my current Joomla custom component

Joomla\CMS\Plugin\PluginHelper::importPlugin('captcha');
$dispatcher = JEventDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);

It seems 'JEventDispatcher' is deprecated in Joomla 4

What would be the equivalent in Joomla 4 style of coding.

1 Answer 1

4

The ideal way is to have dependencies injected into your objects. Event dispatcher is registered with the global service container so you can fetch it when registering your component services in provider.php. However, there isn't a good way to pass it down to MVC elements without a custom MVC factory. Core components don't use anything like that yet.

That said, if you just want to get your code working, you can trigger the event through the application:

$res = Joomla\CMS\Factory::getApplication()->triggerEvent('onCheckAnswer', [$post['recaptcha_response_field']]);

Note that this method is already deprecated and will be removed in 5.0. Going forward, an event object should be created and passed to dispatcher's dispatch() method:

$dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();
$event = new Joomla\Event\Event('onCheckAnswer', [$post['recaptcha_response_field']]);
$res = $dispatcher->dispatch('onCheckAnswer', $event);
2
  • Thanks for your answer. I do not want to simply make my code to run. I want the right way to do. When I tried with your code snippet, it looks like getDispatcher is an undefined method inside Joomla\CMS\Factory::getApplication(). Can you please help on that. Commented Aug 31, 2021 at 15:10
  • Are you getting an error when running the code? Or does the error appear only in your editor?
    – Sharky
    Commented Aug 31, 2021 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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