Course View Event Not Working

Course View Event Not Working

by Mayank Tyagi -
Number of replies: 5

Hi folks,

I want to execute some code on the Course viewed event. But in my case the event doesn't work. I tried this event on two different versions of moodle but it does not work. All other events are working fine. I am using moodle 3.6.1.

Average of ratings: -
In reply to Mayank Tyagi

Re: Course View Event Not Working

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Moving to general developer forum...

Given that the view event is triggered right before the footer is rendered, I would be surprised if it doesn't work. 

You'll probably need to share the relevant bits of your code.

In reply to Howard Miller

Re: Course View Event Not Working

by Mayank Tyagi -
Here is my code...
//*********events.php  ***************/
defined('MOODLE_INTERNAL') || die();

$observers = array(
    array(
        'eventname' => '\core\event\user_loggedin',
        'callback'  => '\local_injecting\observers::inject'
    ),
	array(
        'eventname' => '\core\event\course_viewed',
        'callback'  => '\local_injecting\observers::injectCourse'
    )
); 
//observers.php
namespace local_injecting;

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

require_once(dirname(__DIR__).'/lib.php');

class observers {
	public static function inject(\core\event\user_loggedin $event) {
		if( empty($event->objectid)) {
		
	      return;
        }
		injecting($event);
    }
	
	public static function injectCourse(\core\event\course_viewed $event) {
		if( empty($event->objectid)) {
		
	      return;
        }
		injectingCourse($event);
    }
}
//lib.php
function injecting($event) {  
	global $DB, $CFG;

	$currentDate =  date("Y/m/d"); 
	
	print_object($event);
	die;
	
	

}

function injectingCourse($event) {  
	global $DB, $CFG;

	file_put_contents($CFG->dirroot . '/local/injecting/testing.php', '');
		file_put_contents($CFG->dirroot . '/local/injecting/tt.php', '');
		// purge_all_caches();
	
	// print_object($event);
	// die;
	
}
Average of ratings: Useful (1)
In reply to Howard Miller

Re: Course View Event Not Working

by Mayank Tyagi -

I found there is no object id generated for this event. Therefore when I removed the condition 

if( empty($event->objectid)) {
		
	      return;
        }

It's working fine. Is it fine?


In reply to Mayank Tyagi

Re: Course View Event Not Working

by Sooraj Singh -

Hello Guys

I also face the same issue .i'm trying to perform some action during view event but not able to do that.if you guys come up with the solution please let me know.

Regards:

Sooraj singh

In reply to Sooraj Singh

Re: Course View Event Not Working

by Mayank Tyagi -

Thanks for your response. Just skip the event objectid and it will work. But I don't think so it is standard way,