MediaWiki  master
HTMLMultiSelectField.php
Go to the documentation of this file.
1 <?php
2 
5 
12  /* @var string */
13  private $mPlaceholder;
14 
27  public function __construct( $params ) {
28  parent::__construct( $params );
29 
30  // If the disabled-options parameter is not provided, use an empty array
31  if ( !isset( $this->mParams['disabled-options'] ) ) {
32  $this->mParams['disabled-options'] = [];
33  }
34 
35  if ( isset( $params['dropdown'] ) ) {
36  $this->mClass .= ' mw-htmlform-dropdown';
37  if ( isset( $params['placeholder'] ) ) {
38  $this->mPlaceholder = $params['placeholder'];
39  } elseif ( isset( $params['placeholder-message'] ) ) {
40  $this->mPlaceholder = $this->msg( $params['placeholder-message'] )->text();
41  }
42  }
43 
44  if ( isset( $params['flatlist'] ) ) {
45  $this->mClass .= ' mw-htmlform-flatlist';
46  }
47  }
48 
53  public function validate( $value, $alldata ) {
54  $p = parent::validate( $value, $alldata );
55 
56  if ( $p !== true ) {
57  return $p;
58  }
59 
60  if ( !is_array( $value ) ) {
61  return false;
62  }
63 
64  // Reject nested arrays (T274955)
65  $value = array_filter( $value, 'is_scalar' );
66 
67  # If all options are valid, array_intersect of the valid options
68  # and the provided options will return the provided options.
69  $validOptions = HTMLFormField::flattenOptions( $this->getOptions() );
70 
71  $validValues = array_intersect( $value, $validOptions );
72  if ( count( $validValues ) == count( $value ) ) {
73  return true;
74  } else {
75  return $this->msg( 'htmlform-select-badoption' );
76  }
77  }
78 
83  public function getInputHTML( $value ) {
84  if ( isset( $this->mParams['dropdown'] ) ) {
85  $this->mParent->getOutput()->addModules( 'jquery.chosen' );
86  }
87 
88  $value = HTMLFormField::forceToStringRecursive( $value );
89  $html = $this->formatOptions( $this->getOptions(), $value );
90 
91  return $html;
92  }
93 
103  public function formatOptions( $options, $value ) {
104  $html = '';
105 
106  $attribs = $this->getAttributes( [ 'disabled', 'tabindex' ] );
107 
108  foreach ( $options as $label => $info ) {
109  if ( is_array( $info ) ) {
110  $html .= Html::rawElement( 'h1', [], $label ) . "\n";
111  $html .= $this->formatOptions( $info, $value );
112  } else {
113  $thisAttribs = [
114  'id' => "{$this->mID}-$info",
115  'value' => $info,
116  ];
117  if ( in_array( $info, $this->mParams['disabled-options'], true ) ) {
118  $thisAttribs['disabled'] = 'disabled';
119  }
120  $checked = in_array( $info, $value, true );
121 
122  $checkbox = $this->getOneCheckbox( $checked, $attribs + $thisAttribs, $label );
123 
124  $html .= ' ' . Html::rawElement(
125  'div',
126  [ 'class' => 'mw-htmlform-flatlist-item' ],
127  $checkbox
128  );
129  }
130  }
131 
132  return $html;
133  }
134 
135  protected function getOneCheckbox( $checked, $attribs, $label ) {
136  if ( $this->mParent instanceof OOUIHTMLForm ) {
137  throw new MWException( 'HTMLMultiSelectField#getOneCheckbox() is not supported' );
138  } else {
139  $elementFunc = [ Html::class, $this->mOptionsLabelsNotFromMessage ? 'rawElement' : 'element' ];
140  $checkbox =
141  Xml::check( "{$this->mName}[]", $checked, $attribs ) .
142  "\u{00A0}" .
143  call_user_func( $elementFunc,
144  'label',
145  [ 'for' => $attribs['id'] ],
146  $label
147  );
148  if ( $this->mParent->getConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere ) ) {
149  $checkbox = Html::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
150  $checkbox .
151  Html::closeElement( 'div' );
152  }
153  return $checkbox;
154  }
155  }
156 
162  public function getOptionsOOUI() {
163  // @phan-suppress-previous-line PhanPluginNeverReturnMethod
164  // Sections make this difficult. See getInputOOUI().
165  throw new MWException( 'HTMLMultiSelectField#getOptionsOOUI() is not supported' );
166  }
167 
180  public function getInputOOUI( $value ) {
181  $this->mParent->getOutput()->addModules( 'oojs-ui-widgets' );
182 
183  // Reject nested arrays (T274955)
184  $value = array_filter( $value, 'is_scalar' );
185 
186  $hasSections = false;
187  $optionsOouiSections = [];
188  $options = $this->getOptions();
189  // If the options are supposed to be split into sections, each section becomes a separate
190  // CheckboxMultiselectInputWidget.
191  foreach ( $options as $label => $section ) {
192  if ( is_array( $section ) ) {
193  $optionsOouiSections[ $label ] = Xml::listDropDownOptionsOoui( $section );
194  unset( $options[$label] );
195  $hasSections = true;
196  }
197  }
198  // If anything remains in the array, they are sectionless options. Put them in a separate widget
199  // at the beginning.
200  if ( $options ) {
201  $optionsOouiSections = array_merge(
202  [ '' => Xml::listDropDownOptionsOoui( $options ) ],
203  $optionsOouiSections
204  );
205  }
206  '@phan-var array[][] $optionsOouiSections';
207 
208  $out = [];
209  foreach ( $optionsOouiSections as $sectionLabel => $optionsOoui ) {
210  $attr = [];
211  $attr['name'] = "{$this->mName}[]";
212 
213  $attr['value'] = $value;
214 
215  $options = $optionsOoui;
216  foreach ( $options as &$option ) {
217  $option['disabled'] = in_array( $option['data'], $this->mParams['disabled-options'], true );
218  }
219  if ( $this->mOptionsLabelsNotFromMessage ) {
220  foreach ( $options as &$option ) {
221  // @phan-suppress-next-line SecurityCheck-XSS Labels are raw when not from message
222  $option['label'] = new OOUI\HtmlSnippet( $option['label'] );
223  }
224  }
225  unset( $option );
226  $attr['options'] = $options;
227 
228  $attr += OOUI\Element::configFromHtmlAttributes(
229  $this->getAttributes( [ 'disabled', 'tabindex' ] )
230  );
231 
232  if ( $this->mClass !== '' ) {
233  $attr['classes'] = [ $this->mClass ];
234  }
235 
236  $widget = new OOUI\CheckboxMultiselectInputWidget( $attr );
237  if ( $sectionLabel ) {
238  $out[] = new OOUI\FieldsetLayout( [
239  'items' => [ $widget ],
240  // @phan-suppress-next-line SecurityCheck-XSS Key is html, taint cannot track that
241  'label' => new OOUI\HtmlSnippet( $sectionLabel ),
242  ] );
243  } else {
244  $out[] = $widget;
245  }
246  }
247 
248  if ( !$hasSections && $out ) {
249  if ( $this->mPlaceholder ) {
250  $out[0]->setData( ( $out[0]->getData() ?: [] ) + [
251  'placeholder' => $this->mPlaceholder,
252  ] );
253  }
254  // Directly return the only OOUI\CheckboxMultiselectInputWidget.
255  // This allows it to be made infusable and later tweaked by JS code.
256  return $out[0];
257  }
258 
259  return implode( '', $out );
260  }
261 
268  public function loadDataFromRequest( $request ) {
269  $fromRequest = $request->getArray( $this->mName, [] );
270  // Fetch the value in either one of the two following case:
271  // - we have a valid submit attempt (form was just submitted)
272  // - we have a value (an URL manually built by the user, or GET form with no wpFormIdentifier)
273  if ( $this->isSubmitAttempt( $request ) || $fromRequest ) {
274  // Checkboxes are just not added to the request arrays if they're not checked,
275  // so it's perfectly possible for there not to be an entry at all
276  // @phan-suppress-next-line PhanTypeMismatchReturnNullable getArray does not return null
277  return $fromRequest;
278  } else {
279  // That's ok, the user has not yet submitted the form, so show the defaults
280  return $this->getDefault();
281  }
282  }
283 
288  public function getDefault() {
289  return $this->mDefault ?? [];
290  }
291 
296  public function filterDataForSubmit( $data ) {
297  $data = HTMLFormField::forceToStringRecursive( $data );
298  $options = HTMLFormField::flattenOptions( $this->getOptions() );
299  $forcedOn = array_intersect( $this->mParams['disabled-options'], $this->getDefault() );
300 
301  $res = [];
302  foreach ( $options as $opt ) {
303  $res["$opt"] = in_array( $opt, $forcedOn, true ) || in_array( $opt, $data, true );
304  }
305 
306  return $res;
307  }
308 
313  protected function needsLabel() {
314  return false;
315  }
316 }
The parent class to generate form fields.
static flattenOptions( $options)
flatten an array of options to a single array, for instance, a set of "<options>" inside "<optgroups>...
getOptions()
Fetch the array of options from the field's parameters.
isSubmitAttempt(WebRequest $request)
Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to just v...
msg( $key,... $params)
Get a translated interface message.
getAttributes(array $list)
Returns the given attributes from the parameters.
static forceToStringRecursive( $array)
Recursively forces values in an array to strings, because issues arise with integer 0 as a value.
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.Don't forget to call pare...
needsLabel()
Should this field have a label, or is there no input element with the appropriate id for the label to...
getOneCheckbox( $checked, $attribs, $label)
filterDataForSubmit( $data)
Support for separating multi-option preferences into multiple preferences Due to lack of array suppor...
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.
formatOptions( $options, $value)
getDefault()
Stability: stableto override mixed
getOptionsOOUI()
Get options and make them into arrays suitable for OOUI.
MediaWiki exception.
Definition: MWException.php:32
This class is a collection of static functions that serve two purposes:
Definition: Html.php:55
A class containing constants representing the names of configuration variables.
Compact stacked vertical format for forms, implemented using OOUI widgets.
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:598
static check( $name, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox.
Definition: Xml.php:330