Availability API for items within a module
The Availability API provides availability controls for activity modules (course-modules) and sections. It can also be used, with some limitations, to implement an interface for availability restrictions within a module (if you wanted to add different restrictions to different pages within a Book, for example).
The following limitations currently apply:
- The editing interface must be within a Moodle form.
- You may only have a single 'Restrict access' control on a page. (This means that you can't have a second one on your main module settings form, as that already has one; you would have to put this on a separate form.)
- The API only works within a course. You can't use it for system-level items.
- None of this has been tested for real. The API wasn't really designed for this so although it seems to work perfectly well, there may be some catch.
How to implement
To implement the API for an item within your module, assuming that item has its own editing form, you need to do the following:
- Editing interface:
- Add code to the form validation to check its results.
- Store the returned 'availabiltyconditionsjson' value in a suitable database location when the form is saved, and ensure this value is provided in the normal form data when displaying the form.
- Back-end class:
- Implement a new class that extends \core_availability\info with regard to your type of item.
- This class needs to provide the availability settings value to the parent class, supply a name for debugging purposes, have a mechanism to set the value in the database, and return a Moodle context relating to the item.
- Implement backup and restore:
- Include the availabilityconditionsjson value in backup and restore as usual.
- After restore completes (NOT during restore of your individual module - must be after all modules were restored), create an instance of your class and call the update_after_restore function.
- Check availability:
- Check Moodle capabilities that may mean the current user bypasses the restrictions.
- Construct an object of your class and call the is_available function.
- Use the returned data to control whether your item displays (or whether we show information about when it will be available, or whether we don't show anything at all).
This example is a complete script, demonstrating everything except backup/restore. If you save it as silly.php within mod/page, and then call it as silly.php?id=1234 where 1234 is a valid page id, you'll be able to set an availability condition with the form and see the result.
Note: For real use you would probably create several suitably namespaced classes, rather than slinging everything into one script. The single script here is just an example.