How do I get the contextid of an assignment?

How do I get the contextid of an assignment?

by J m -
Number of replies: 2

Like here:  pluginfile.php/1518/mod_assignment/intro/

Moodle put 1518 for this.  Where did 1518 come from in the database?  It's different for various attachments in each assignment.  I looked in mdl_role_assignments but didn't see a 1518 in there.

How do I get the contextid?

I need to replace @@PLUGINFILE@@ with the right url and if I can get the contextid I think I can do it.

EDIT:  I found it in the files table but how is it related to the assignment?  I mean how do I know to look for 1518 to begin with.  What tables would I join with assignment to get 1518? 

Thank you.

Average of ratings: -
In reply to J m

Re: How do I get the contextid of an assignment?

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

If you are looking at the database, you can get from the assignment id => context id in the following steps:

  1. Look in the mdl_modules table to find the ID of the 'assignment' type (1 on my local install)
  2. Look in mdl_course_modules for module = the ID from step 1 AND instance = assignment id AND course = course id, note the course module ID
  3. Look in mdl_context for an entry with contextlevel = 70 (CONTEXT_MODULE) and instanceid = course module ID (from step 2).
If you are doing this in code, you can do this:
$cm = get_coursemodule_from_instance('assignment', $assignmentid, $courseid);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
echo "The context is: $context->id";
Note you can also find the $courseid by looking at the $assignment->course value.
Average of ratings: Useful (4)