pluginsmoodlemoodle-apimoodle-theme

Observer function is not redirecting to my custom page in Moodle


I am fairly new to Moodle. I am working on a custom plugin in which I wanted to make a pop up that shows after the user has logged in for the first time. Exploring the forum, I came up with the idea of catching event and triggering something. Basically I tried to catch the user_loggedin event and in the observer function I tried to trigger a redirection which has my pop up but it didn't seems to work properly. I am not getting any kind of error (debugging is on) so it is hard for me to troubleshoot the actual problem. My db/events.php file:

<?php
/*
 * @package     local_message
 * @author      Kristian
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

$observer = array(
    array(
        'eventname' => '\core\event\user_loggedin',
        'callback' => '\local_custom_signup\local_first_signup_observer::first_signup',
    ),
);
//var_dump($observer);

My classes/observer.php file:

<?php
/*
 * @package     local_message
 * @author      Kristian
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_custom_signup;


defined('MOODLE_INTERNAL') || die();

 class local_first_signup_observer{

    public static function first_signup(\core\event\user_loggedin $event){
        global $CFG;
        redirect($CFG->wwwroot . '/local/custom_signup/signupform.php', get_string('cancelled_form', 'local_message'));
        
    }
 }

Solution

  • You cannot do that - event handlers cannot redirect to a new page, because Moodle is usually in the middle of making other changes (and there may well be other event handlers that are still wanting to have a go at handling that event).

    That said, the most likely reason why you're not seeing this do anything, is that you've called your file "classes/observers.php", but called the class "local_first_signup_observer". Moodle has no way of guessing that it needs to look in a "observers.php" to find this class.

    If you rename "observers.php" to "local_first_signup_observer.php" (and purge all caches), then it should find it (but it still won't do anything useful, as redirects aren't allowed here).