Skip to content

Commit b6cecff

Browse files
marxjohnsonandrewnicols
authored andcommitted
Add question bank filter API guide
This functionality was added in MDL-72321. MDL-78220 will add several new filters, so this guide may expand as the children of that tracker are developed.
1 parent 4e7ab1a commit b6cecff

2 files changed

Lines changed: 245 additions & 0 deletions

File tree

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
---
2+
title: Question bank filters
3+
tags:
4+
- Plugins
5+
- Question
6+
- qbank
7+
description: Question bank plugins allow you to define new filters for the question bank view and random question sets.
8+
documentationDraft: true
9+
---
10+
11+
<Since
12+
version="4.3"
13+
issueNumber="MDL-72321"
14+
/>
15+
16+
Question bank plugins allow you define additional filters. These can be used when viewing the question bank, and are included
17+
in the URL so that a filtered view of the question bank can be shared. They are also used when defining the criteria for adding
18+
random questions to a quiz.
19+
20+
## Creating a new filter condition
21+
22+
A filter condition consists of two parts - the backend "condition" PHP class, and the frontend "filter" JavaScript class.
23+
24+
The "condition" class defines the general properties of the filter - its name, various options, and how it is applied to the
25+
question bank query.
26+
The "filter" class defines how the filter is displayed in the UI, and how values selected in the UI are passed back to the condition.
27+
28+
Each new filter condition must define a new "condition" class in the qbank plugin based on `core_question\local\bank\condition`.
29+
By default this will use the `core/datafilter/filtertype` "filter" class, although this can be overridden too if required.
30+
31+
### Basic example
32+
33+
This outlines the bare minimum required to implement a new filter condition. This will give you a field that allows you to
34+
enter keywords and add them to a list of selected search terms, the filter the questions by that list of terms.
35+
This assumes that you already have the basic framework of a qbank plugin in place. For real-world examples,
36+
look for classes that extend `core_question\local\bank\condition`.
37+
38+
Create a `condition` class within your plugin's namespace. For a plugin called `qbank_myplugin` this would look something like:
39+
40+
```php title="question/bank/myplugin/classes/myfilter_condition.php"
41+
namespace qbank_myplugin;
42+
43+
use core_question\local\bank\condition;
44+
45+
class myfilter_condition extends condition {
46+
47+
}
48+
```
49+
50+
Modify your `plugin_feature` class to return an instance of your condition from the `get_question_filters()` method:
51+
52+
```php title="question/bank/myplugin/classes/plugin_feature.php"
53+
namespace qbank_myplugin;
54+
55+
class plugin_feature extends core_question\local\bank\plugin_features_base {
56+
public function get_question_filters(?core_question\local\bank\view $qbank = null): array {
57+
return [
58+
new myfilter_condition($qbank),
59+
];
60+
}
61+
}
62+
```
63+
64+
Back in your `condition` class, define the `get_name()` method, which returns the label displayed in the filter UI.
65+
66+
```php title="Define the condition name"
67+
public function get_name(): string {
68+
return get_string('myfilter_name', 'myplugin');
69+
}
70+
```
71+
72+
Define `get_condition_key()`, which returns a unique machine-readable ID for this filter condition, used when passing the filter
73+
as a parameter.
74+
75+
```php title="Define the condition key"
76+
public function get_condition_key(): string {
77+
return 'myfilter';
78+
}
79+
```
80+
81+
To actually filter the results, define `build_query_from_filter()` which returns an SQL `WHERE` condition, and an array of parameters.
82+
The `$filter` parameter receives an array with a `'values'` key, containing an array of the selected values, and a `'jointype'` key,
83+
containing one of the `JOINTTYPE_ANY`, `JOINTYPE_ALL` or `JOINTYPE_NONE` constants. Use these to build your condition as required.
84+
85+
The conditions from each filter are combined with the query in
86+
[`core_question\local\bank\view::build_query()`](https://github.com/moodle/moodle/blob/c741492c38b9945abbfc7e90dfe8f943279f8265/question/classes/local/bank/view.php#L733)
87+
to select the filtered question list.
88+
89+
```php title="Filter questions"
90+
public function build_query_from_filter(array $filter): array {
91+
$andor = ' AND ';
92+
$equal = '=';
93+
if ($filter['jointype'] === self::JOINTYPE_ANY) {
94+
$andor = ' OR ';
95+
} else if ($filter['jointype'] === self::JOINTYPE_NONE) {
96+
$equal = '!=';
97+
}
98+
$conditions = [];
99+
$params = [];
100+
// In real life we'd probably use $DB->get_in_or_equal here.
101+
foreach ($filter['values'] as $key => $value) {
102+
$conditions[] = 'q.fieldname ' . $equal . ' :myfilter' . $key;
103+
$params['myfilter' . $key] = $value;
104+
}
105+
return [
106+
'(' . implode($andor, $conditions) . ')',
107+
$params,
108+
];
109+
}
110+
```
111+
112+
Following this pattern with your own fields and options will give you a basic functional filter. Most filters will require
113+
more complex functionality, which can be achieved through additional methods.
114+
115+
### Additional options
116+
117+
#### Pre-defined values
118+
119+
To define the list of possible filter values, define `get_initial_values()`, which returns an array of `['value', 'title']` for each
120+
option. These will then be searchable and selectable in the autocomplete field.
121+
122+
```php title="Define initial filter values"
123+
public function get_initial_values(): string {
124+
return [
125+
[
126+
'value' => 0,
127+
'title' => 'Option 1',
128+
],
129+
[
130+
'value' => 1,
131+
'title' => 'Option 2',
132+
]
133+
];
134+
}
135+
```
136+
137+
#### Restrict custom keywords
138+
139+
To restrict the possible filter terms to only those returned from `get_initial_values()`, define `allow_custom()` and have it return `false`.
140+
141+
```php title="Disable custom terms"
142+
public function allow_custom(): bool {
143+
return false;
144+
}
145+
```
146+
147+
#### Restrict join types
148+
149+
Not all join types are relevant to all filters. If each question will only match one of the selected values, it does not make
150+
sense to allow `JOINTYPE_ALL`. Define `get_join_list()` and return an array of the applicable join types.
151+
152+
```php title="Define a restricted list of join types"
153+
public function get_join_list(): array {
154+
return [
155+
datafilter::JOINTYPE_ANY,
156+
datafilter::JOINTYPE_NONE,
157+
];
158+
}
159+
```
160+
161+
#### Allow multiple values?
162+
163+
By default, conditions allow multiple values to be selected and use the selected join type to decide how they are applied.
164+
If your condition should only allow a single value at a time, override `allow_multiple()` to return false.
165+
166+
```php title="Disable selection of multiple values"
167+
public function allow_multiple(): bool {
168+
return false;
169+
}
170+
```
171+
172+
#### Allow empty values?
173+
174+
By default, conditions can be left empty, and therefore will not be included in the filter. To make it compulsory to select a
175+
value for this condition when it is added, override `allow_empty()` to return false.
176+
177+
```php title="Disable empty values"
178+
public function allow_empty(): bool {
179+
return false;
180+
}
181+
```
182+
183+
#### Is the condition required?
184+
185+
If it is compulsory that your condition is always displayed, override `is_required()` to return true.
186+
187+
```php title="Make the condition compulsory"
188+
public function is_required(): bool {
189+
return true;
190+
}
191+
```
192+
193+
#### Custom filter class
194+
195+
By default, the filter will be displayed and processed using the `core/datafilter/filtertype` JavaScript class.
196+
This will provide a single autocomplete field for selecting one or multiple numeric IDs with textual labels.
197+
If this does not fit your filter's use case, you can tell your condition to use a different filter class.
198+
199+
You can either use a different core filter type from `/lib/amd/src/datafilter/filtertypes`, or define your own.
200+
201+
To tell your filter condition to use a different filter class, override the `get_filter_class()` method to return the namespaced
202+
path to your JavaScript class.
203+
204+
```php title="Override the default filter class"
205+
public function get_filter_class(): string {
206+
return 'qbank_myplugin/datafilter/filtertype/myfilter';
207+
}
208+
```
209+
210+
To create your own filter class, a new JavaScript file in your plugin under `amd/src/datafilter/filtertypes/myfilter.js`.
211+
In this file, export a default class that extends `core/datafilter/filtertype`
212+
(or another core filter type from `/lib/amd/src/datafilter/filtertypes`) and override the base methods as required.
213+
For example, if your filter uses textual rather than numeric values, you can override `get values()` to return the raw values
214+
without running `parseInt()` (see
215+
[`qbank_viewquestiontype/datafilter/filtertypes/type`](https://github.com/moodle/moodle/blob/main/mod/quiz/tests/behat/editing_add_from_question_bank.feature)).
216+
217+
If you want a different UI for selecting your filter values instead of a single autocomplete, you can override `addValueSelector()`.
218+
This also provides flexibility over how the values provided by `get_initial_values()` are used by the UI.
219+
220+
#### Filter options
221+
222+
If your condition supports additional options as to how the selected values are applied to the query, such as whether child
223+
categories are included when parent categories are selected, you can define "Filter options".
224+
225+
In your condition class, define `get_filteroptions()` which returns an object containing the current filter options. You will
226+
probably want to add some code to the constructor to read in the current filter options, and some code the `build_query_from_filter()`
227+
to use the option. See
228+
[`qbank_managecategories\category_condition`](https://github.com/moodle/moodle/blob/main/question/bank/managecategories/classes/category_condition.php)
229+
as an example.
230+
231+
You JavaScript filter class will also need to support your filter options. Override the constructor an add additional code
232+
for the UI required to set your filter options, and override `get filterOptions()` to return the current value for any options set
233+
in this UI. See
234+
[`qbank_managecategories/datafilter/filtertypes/categories`](https://github.com/moodle/moodle/blob/main/question/bank/managecategories/amd/src/datafilter/filtertypes/categories.js)
235+
as an example.
236+
237+
#### Context-sensitive configuration
238+
239+
You may want your filter to behave differently depending on where it is being displayed. In this case you can override the
240+
constructor which receives the current `$qbank` view object, and extract some data that is used later on by your other methods.
241+
242+
For example, the
243+
[tag condition](https://github.com/moodle/moodle/blob/main/question/bank/tagquestion/classes/tag_condition.php)
244+
will find the context of the current page, and use that to control which tags are available in the filter.

docs/apis/plugintypes/qbank/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,6 @@ Question bank plugins can extend the question bank in many ways, including:
2222
- Bulk actions
2323
- Navigation node (tabs)
2424
- Question preview additions (via callback)
25+
- [Question filters](./filters.md)
2526

2627
The place to start implementing most of these is with a class `classes/plugin_features.php` in your plugin, that declares which features you want to add to the question bank. Until more documentation is written, looking at the examples of the plugins in Moodle core should give you a good idea what you need to do.

0 commit comments

Comments
 (0)