MediaWiki master
HTMLMultiSelectField.php
Go to the documentation of this file.
1<?php
2
4
12use RuntimeException;
13
20
21 private bool $mDropdown = false;
22
23 private ?string $mPlaceholder = null;
24
39 public function __construct( $params ) {
40 parent::__construct( $params );
41
42 // If the disabled-options parameter is not provided, use an empty array
43 if ( !isset( $this->mParams['disabled-options'] ) ) {
44 $this->mParams['disabled-options'] = [];
45 }
46
47 if ( isset( $params['dropdown'] ) ) {
48 $this->mDropdown = true;
49 if ( isset( $params['placeholder'] ) ) {
50 $this->mPlaceholder = $params['placeholder'];
51 } elseif ( isset( $params['placeholder-message'] ) ) {
52 $this->mPlaceholder = $this->msg( $params['placeholder-message'] )->text();
53 }
54 }
55
56 if ( isset( $params['flatlist'] ) ) {
57 $this->mClass .= ' mw-htmlform-flatlist';
58 }
59 }
60
65 public function validate( $value, $alldata ) {
66 $p = parent::validate( $value, $alldata );
67
68 if ( $p !== true ) {
69 return $p;
70 }
71
72 if ( !is_array( $value ) ) {
73 return false;
74 }
75
76 // Reject nested arrays (T274955)
77 $value = array_filter( $value, 'is_scalar' );
78
79 if ( isset( $this->mParams['required'] )
80 && $this->mParams['required'] !== false
81 && $value === []
82 ) {
83 return $this->msg( 'htmlform-required' );
84 }
85
86 if ( isset( $this->mParams['max'] ) && ( count( $value ) > $this->mParams['max'] ) ) {
87 return $this->msg( 'htmlform-multiselect-toomany', $this->mParams['max'] );
88 }
89
90 # If all options are valid, array_intersect of the valid options
91 # and the provided options will return the provided options.
92 $validOptions = HTMLFormField::flattenOptions( $this->getOptions() );
93
94 $validValues = array_intersect( $value, $validOptions );
95 if ( count( $validValues ) == count( $value ) ) {
96 return true;
97 } else {
98 return $this->msg( 'htmlform-select-badoption' );
99 }
100 }
101
106 public function getInputHTML( $value ) {
107 $value = HTMLFormField::forceToStringRecursive( $value );
108 $html = $this->formatOptions( $this->getOptions(), $value );
109
110 return $html;
111 }
112
121 public function formatOptions( $options, $value ) {
122 $html = '';
123
124 $attribs = $this->getAttributes( [ 'disabled', 'tabindex' ] );
125
126 foreach ( $options as $label => $info ) {
127 if ( is_array( $info ) ) {
128 $html .= Html::rawElement( 'h1', [], $label ) . "\n";
129 $html .= $this->formatOptions( $info, $value );
130 } else {
131 $thisAttribs = [
132 'id' => "{$this->mID}-$info",
133 'value' => $info,
134 ];
135 if ( in_array( $info, $this->mParams['disabled-options'], true ) ) {
136 $thisAttribs['disabled'] = 'disabled';
137 }
138 $checked = in_array( $info, $value, true );
139
140 $checkbox = $this->getOneCheckbox( $checked, $attribs + $thisAttribs, $label );
141
142 $html .= ' ' . Html::rawElement(
143 'div',
144 [ 'class' => 'mw-htmlform-flatlist-item' ],
145 $checkbox
146 );
147 }
148 }
149
150 return $html;
151 }
152
153 protected function getOneCheckbox( $checked, $attribs, $label ) {
154 if ( $this->mParent instanceof OOUIHTMLForm ) {
155 throw new RuntimeException( __METHOD__ . ' is not supported' );
156 } else {
157 $checkbox =
158 Xml::check( "{$this->mName}[]", $checked, $attribs ) .
159 "\u{00A0}" .
160 Html::rawElement(
161 'label',
162 [ 'for' => $attribs['id'] ],
163 $this->escapeLabel( $label )
164 );
165 return $checkbox;
166 }
167 }
168
169 public function getOptionsOOUI() {
170 $optionsOouiSections = [];
171 $options = $this->getOptions();
172
173 // If the options are supposed to be split into sections, each section becomes a separate
174 // CheckboxMultiselectInputWidget.
175 foreach ( $options as $label => $section ) {
176 if ( is_array( $section ) ) {
177 $optionsOouiSections[ $label ] = Html::listDropdownOptionsOoui( $section );
178 unset( $options[$label] );
179 }
180 }
181
182 // If anything remains in the array, they are sectionless options. Put them at the beginning.
183 if ( $options ) {
184 $optionsOouiSections = array_merge(
185 [ '' => Html::listDropdownOptionsOoui( $options ) ],
186 $optionsOouiSections
187 );
188 }
189
190 return $optionsOouiSections;
191 }
192
205 public function getInputOOUI( $value ) {
206 $this->mParent->getOutput()->addModules( 'oojs-ui-widgets' );
207 if ( $this->mDropdown ) {
208 $this->mParent->getOutput()->addModuleStyles( 'mediawiki.widgets.TagMultiselectWidget.styles' );
209 }
210
211 // Reject nested arrays (T274955)
212 $value = array_filter( $value, 'is_scalar' );
213
214 $out = [];
215 $optionsSections = $this->getOptionsOOUI();
216 foreach ( $optionsSections as $sectionLabel => &$groupedOptions ) {
217 $attr = [];
218 $attr['name'] = "{$this->mName}[]";
219
220 $attr['value'] = $value;
221
222 foreach ( $groupedOptions as &$option ) {
223 $option['disabled'] = in_array( $option['data'], $this->mParams['disabled-options'], true );
224 }
225 foreach ( $groupedOptions as &$option ) {
226 $option['label'] = $this->makeLabelSnippet( $option['label'] );
227 }
228 unset( $option );
229 $attr['options'] = $groupedOptions;
230
231 $attr += \OOUI\Element::configFromHtmlAttributes(
232 $this->getAttributes( [ 'disabled', 'tabindex' ] )
233 );
234
235 if ( $this->mClass !== '' ) {
236 $attr['classes'] = [ $this->mClass ];
237 }
238
239 $widget = new \OOUI\CheckboxMultiselectInputWidget( $attr );
240 if ( $sectionLabel ) {
241 $out[] = new \OOUI\FieldsetLayout( [
242 'items' => [ $widget ],
243 // @phan-suppress-next-line SecurityCheck-XSS Key is html, taint cannot track that
244 'label' => new \OOUI\HtmlSnippet( $sectionLabel ),
245 ] );
246 } else {
247 $out[] = $widget;
248 }
249 }
250 unset( $groupedOptions );
251
252 $params = [];
253 if ( $this->mPlaceholder ) {
254 $params['placeholder'] = $this->mPlaceholder;
255 }
256 if ( isset( $this->mParams['max'] ) ) {
257 $params['tagLimit'] = $this->mParams['max'];
258 }
259 if ( $this->mDropdown ) {
260 return new MenuTagMultiselectWidget( [
261 'name' => $this->mName,
262 'options' => $optionsSections,
263 'default' => $value,
264 'noJsFallback' => $out,
265 'allowReordering' => false,
266 ] + $params );
267 } elseif ( count( $out ) === 1 ) {
268 $firstFieldData = $out[0]->getData() ?: [];
269 $out[0]->setData( $firstFieldData + $params );
270 // Directly return the only OOUI\CheckboxMultiselectInputWidget.
271 // This allows it to be made infusable and later tweaked by JS code.
272 return $out[0];
273 }
274
275 return implode( '', $out );
276 }
277
278 protected function getOOUIModules() {
279 return $this->mDropdown ? [ 'mediawiki.widgets.MenuTagMultiselectWidget' ] : [];
280 }
281
282 protected function shouldInfuseOOUI() {
283 return $this->mDropdown;
284 }
285
292 public function loadDataFromRequest( $request ) {
293 $fromRequest = $request->getArray( $this->mName, [] );
294 // Fetch the value in either one of the two following case:
295 // - we have a valid submit attempt (form was just submitted)
296 // - we have a value (an URL manually built by the user, or GET form with no wpFormIdentifier)
297 if ( $this->isSubmitAttempt( $request ) || $fromRequest ) {
298 // Checkboxes are just not added to the request arrays if they're not checked,
299 // so it's perfectly possible for there not to be an entry at all
300 // @phan-suppress-next-line PhanTypeMismatchReturnNullable getArray does not return null
301 return $fromRequest;
302 } else {
303 // That's ok, the user has not yet submitted the form, so show the defaults
304 return $this->getDefault();
305 }
306 }
307
312 public function getDefault() {
313 return $this->mDefault ?? [];
314 }
315
320 public function filterDataForSubmit( $data ) {
322 $options = HTMLFormField::flattenOptions( $this->getOptions() );
323 $forcedOn = array_intersect( $this->mParams['disabled-options'], $this->getDefault() );
324
325 $res = [];
326 foreach ( $options as $opt ) {
327 $res["$opt"] = in_array( $opt, $forcedOn, true ) || in_array( $opt, $data, true );
328 }
329
330 return $res;
331 }
332
337 protected function needsLabel() {
338 return false;
339 }
340}
341
343class_alias( HTMLMultiSelectField::class, 'HTMLMultiSelectField' );
needsLabel()
Should this field have a label, or is there no input element with the appropriate id for the label to...
shouldInfuseOOUI()
Whether the field should be automatically infused.
filterDataForSubmit( $data)
Support for separating multi-option preferences into multiple preferences Due to lack of array suppor...
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.Don't forget to call pare...
getOOUIModules()
Get the list of extra ResourceLoader modules which must be loaded client-side before it's possible to...
getInputHTML( $value)
This function must be implemented to return the HTML to generate the input object itself....
getInputOOUI( $value)
Get the OOUI version of this field.
getOptionsOOUI()
Get options and make them into arrays suitable for OOUI.
The parent class to generate form fields.
makeLabelSnippet( $label)
The keys in the array returned by getOptions() can be either HTML or plain text depending on $this->m...
static flattenOptions( $options)
flatten an array of options to a single array, for instance, a set of "<options>" inside "<optgroups>...
static forceToStringRecursive( $array)
Recursively forces values in an array to strings, because issues arise with integer 0 as a value.
getOptions()
Fetch the array of options from the field's parameters.
getAttributes(array $list)
Returns the given attributes from the parameters.
msg( $key,... $params)
Get a translated interface message.
isSubmitAttempt(WebRequest $request)
Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to just v...
escapeLabel( $label)
The keys in the array returned by getOptions() can be either HTML or plain text depending on $this->m...
Compact stacked vertical format for forms, implemented using OOUI widgets.
This class is a collection of static functions that serve two purposes:
Definition Html.php:56
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:672
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Module of static functions for generating XML.
Definition Xml.php:37