Setting an activity availability condition in code

Setting an activity availability condition in code

על ידי Tim Hunt בתאריך
מספר תגובות: 3
תמונה של Core developers תמונה של Documentation writers תמונה של Particularly helpful Moodlers תמונה של Peer reviewers תמונה של Plugin developers

I just had to learn this by asking sam. Since not everyone is lucky enough to share an office with sam, I thought I would put it here:

If you want to programmatically set up an availability condition (e.g. set an activity to only be available to users of a particular group, the best code to do that is:

$restriction = \core_availability\tree::get_root_json(
[\availability_group\condition::get_json($group->id)]);
$DB->set_field('course_modules', 'availability',
json_encode($restriction), ['id' => $cmid]);
rebuild_course_cache($course->id, true);
I also added this to https://docs.moodle.org/dev/Availability_API. I hope that helps somebody.
ממוצע דרוגים:Useful (4)
בתגובה ל: Tim Hunt

Re: Setting an activity availability condition in code

על ידי Mihir J בתאריך

Hi Tim

This is great!

I have one query - the above code part is actually removes all existing condition and add only the group one.

Rather than replacing, how can I add a new restriction along with existing one.

Say, i already have a date condition for a cm, now programming i want to add an AND condition of group along with that.

How do i do this?

Thanks again!

Mihir

בתגובה ל: Mihir J

Re: Setting an activity availability condition in code

על ידי Tim Hunt בתאריך
תמונה של Core developers תמונה של Documentation writers תמונה של Particularly helpful Moodlers תמונה של Peer reviewers תמונה של Plugin developers
I don't know. Have a look at the other methods on the \core_availability\tree class. I guess you need to start with the current value of the setting, and parse it into a tree structure, then modify the structure to add the new rules, then save it again.
בתגובה ל: Tim Hunt

Re: Setting an activity availability condition in code

על ידי Mihir J בתאריך
Hi Tim,

Thank you, yes, we can do that using tree class and parsing. Then by json encode, save it back only that particular new children

Thanks again!
Mihir