Search code examples
phpmoodlemoodle-api

assign roles using moodle core api functions


I'm creating a block in moodle to assign specific system roles to a user. Not sure the best way to do this..

I know you can assign roles from Site administration > User > Permissions > Assign System roles but my block needs to do other things in custom tables.. I have done the part which creates the record in custom tables but this system role is the only item left..and not sure how to do this

could someone please direct me to how I can do this (assign system roles using moodle core api (functions))

or if its a good idea to add record in the role_assignments table.. manually using database queries? and will it work?


Solution

  • $context = context_system::instance();
    role_assign($roleid, $userid, $context->id);
    

    Don't directly update the DB table, as that won't trigger event handlers for the role change (or clear relevant caches, etc.).