MediaWiki  master
HTMLCheckMatrix.php
Go to the documentation of this file.
1 <?php
2 
4 
30  private static $requiredParams = [
31  // Required by underlying HTMLFormField
32  'fieldname',
33  // Required by HTMLCheckMatrix
34  'rows',
35  'columns'
36  ];
37 
42  public function __construct( $params ) {
43  $missing = array_diff( self::$requiredParams, array_keys( $params ) );
44  if ( $missing ) {
45  throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
46  }
47  parent::__construct( $params );
48  }
49 
50  public function validate( $value, $alldata ) {
51  $rows = $this->mParams['rows'];
52  $columns = $this->mParams['columns'];
53 
54  // Make sure user-defined validation callback is run
55  $p = parent::validate( $value, $alldata );
56  if ( $p !== true ) {
57  return $p;
58  }
59 
60  // Make sure submitted value is an array
61  if ( !is_array( $value ) ) {
62  return false;
63  }
64 
65  // If all options are valid, array_intersect of the valid options
66  // and the provided options will return the provided options.
67  $validOptions = [];
68  foreach ( $rows as $rowTag ) {
69  foreach ( $columns as $columnTag ) {
70  $validOptions[] = $columnTag . '-' . $rowTag;
71  }
72  }
73  $validValues = array_intersect( $value, $validOptions );
74  if ( count( $validValues ) == count( $value ) ) {
75  return true;
76  } else {
77  return $this->msg( 'htmlform-select-badoption' );
78  }
79  }
80 
91  public function getInputHTML( $value ) {
92  $html = '';
93  $tableContents = '';
94  $rows = $this->mParams['rows'];
95  $columns = $this->mParams['columns'];
96 
97  $attribs = $this->getAttributes( [ 'disabled', 'tabindex' ] );
98 
99  // Build the column headers
100  $headerContents = Html::rawElement( 'td', [], "\u{00A0}" );
101  foreach ( $columns as $columnLabel => $columnTag ) {
102  // @phan-suppress-next-line PhanTypeMismatchArgument False positive, labels are documented as string
103  $headerContents .= Html::rawElement( 'th', [], $columnLabel );
104  }
105  $thead = Html::rawElement( 'tr', [], "\n$headerContents\n" );
106  $tableContents .= Html::rawElement( 'thead', [], "\n$thead\n" );
107 
108  $tooltipClass = 'mw-icon-question';
109  if ( isset( $this->mParams['tooltip-class'] ) ) {
110  $tooltipClass = $this->mParams['tooltip-class'];
111  }
112 
113  // Build the options matrix
114  foreach ( $rows as $rowLabel => $rowTag ) {
115  // Append tooltip if configured
116  if ( isset( $this->mParams['tooltips'][$rowLabel] ) ) {
117  $tooltipAttribs = [
118  'class' => "mw-htmlform-tooltip $tooltipClass",
119  'title' => $this->mParams['tooltips'][$rowLabel],
120  'aria-label' => $this->mParams['tooltips'][$rowLabel]
121  ];
122  $rowLabel .= ' ' . Html::element( 'span', $tooltipAttribs, '' );
123  }
124  $rowContents = Html::rawElement( 'td', [], $rowLabel );
125  foreach ( $columns as $columnTag ) {
126  $thisTag = "$columnTag-$rowTag";
127  // Construct the checkbox
128  $thisAttribs = [
129  'id' => "{$this->mID}-$thisTag",
130  'value' => $thisTag,
131  ];
132  $checked = in_array( $thisTag, (array)$value, true );
133  if ( $this->isTagForcedOff( $thisTag ) ) {
134  $checked = false;
135  $thisAttribs['disabled'] = 1;
136  $thisAttribs['class'] = 'checkmatrix-forced checkmatrix-forced-off';
137  } elseif ( $this->isTagForcedOn( $thisTag ) ) {
138  $checked = true;
139  $thisAttribs['disabled'] = 1;
140  $thisAttribs['class'] = 'checkmatrix-forced checkmatrix-forced-on';
141  }
142 
143  $checkbox = $this->getOneCheckboxHTML( $checked, $attribs + $thisAttribs );
144 
145  $rowContents .= Html::rawElement(
146  'td',
147  [],
148  $checkbox
149  );
150  }
151  $tableContents .= Html::rawElement( 'tr', [], "\n$rowContents\n" );
152  }
153 
154  // Put it all in a table
155  $html .= Html::rawElement( 'table',
156  [ 'class' => 'mw-htmlform-matrix' ],
157  Html::rawElement( 'tbody', [], "\n$tableContents\n" ) ) . "\n";
158 
159  return $html;
160  }
161 
162  public function getInputOOUI( $value ) {
163  $attribs = $this->getAttributes( [ 'disabled', 'tabindex' ] );
164 
166  [
167  'name' => $this->mName,
168  'infusable' => true,
169  'id' => $this->mID,
170  'rows' => $this->mParams['rows'],
171  'columns' => $this->mParams['columns'],
172  'tooltips' => $this->mParams['tooltips'] ?? [],
173  'forcedOff' => $this->mParams['force-options-off'] ?? [],
174  'forcedOn' => $this->mParams['force-options-on'] ?? [],
175  'values' => $value,
176  ] + OOUI\Element::configFromHtmlAttributes( $attribs )
177  );
178  }
179 
180  protected function getOneCheckboxHTML( $checked, $attribs ) {
181  $checkbox = Xml::check( "{$this->mName}[]", $checked, $attribs );
182  if ( $this->mParent->getConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere ) ) {
183  $checkbox = Html::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
184  $checkbox .
185  Html::element( 'label', [ 'for' => $attribs['id'] ] ) .
186  Html::closeElement( 'div' );
187  }
188  return $checkbox;
189  }
190 
191  protected function isTagForcedOff( $tag ) {
192  return isset( $this->mParams['force-options-off'] )
193  && in_array( $tag, $this->mParams['force-options-off'] );
194  }
195 
196  protected function isTagForcedOn( $tag ) {
197  return isset( $this->mParams['force-options-on'] )
198  && in_array( $tag, $this->mParams['force-options-on'] );
199  }
200 
212  public function getTableRow( $value ) {
213  list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
214  $inputHtml = $this->getInputHTML( $value );
215  $fieldType = $this->getClassName();
216  $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
217  $cellAttributes = [ 'colspan' => 2 ];
218 
219  $moreClass = '';
220  $moreAttributes = [];
221  if ( $this->mCondState ) {
222  $moreAttributes['data-cond-state'] = FormatJson::encode( $this->mCondState );
223  $moreClass = implode( ' ', $this->mCondStateClass );
224  }
225 
226  $label = $this->getLabelHtml( $cellAttributes );
227 
228  $field = Html::rawElement(
229  'td',
230  [ 'class' => 'mw-input' ] + $cellAttributes,
231  $inputHtml . "\n$errors"
232  );
233 
234  $html = Html::rawElement( 'tr',
235  [ 'class' => "mw-htmlform-vertical-label $moreClass" ] + $moreAttributes,
236  $label );
237  $html .= Html::rawElement( 'tr',
238  [ 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $moreClass" ] +
239  $moreAttributes,
240  $field );
241 
242  return $html . $helptext;
243  }
244 
250  public function loadDataFromRequest( $request ) {
251  if ( $this->isSubmitAttempt( $request ) ) {
252  // Checkboxes are just not added to the request arrays if they're not checked,
253  // so it's perfectly possible for there not to be an entry at all
254  return $request->getArray( $this->mName, [] );
255  } else {
256  // That's ok, the user has not yet submitted the form, so show the defaults
257  return $this->getDefault();
258  }
259  }
260 
261  public function getDefault() {
262  return $this->mDefault ?? [];
263  }
264 
265  public function filterDataForSubmit( $data ) {
266  $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
267  $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
268  $res = [];
269  foreach ( $columns as $column ) {
270  foreach ( $rows as $row ) {
271  // Make sure option hasn't been forced
272  $thisTag = "$column-$row";
273  if ( $this->isTagForcedOff( $thisTag ) ) {
274  $res[$thisTag] = false;
275  } elseif ( $this->isTagForcedOn( $thisTag ) ) {
276  $res[$thisTag] = true;
277  } else {
278  $res[$thisTag] = in_array( $thisTag, $data );
279  }
280  }
281  }
282 
283  return $res;
284  }
285 
286  protected function getOOUIModules() {
287  return [ 'mediawiki.widgets.CheckMatrixWidget' ];
288  }
289 
290  protected function shouldInfuseOOUI() {
291  return true;
292  }
293 }
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:96
A checkbox matrix Operates similarly to HTMLMultiSelectField, but instead of using an array of option...
validate( $value, $alldata)
Override this function to add specific validation checks on the field input.
getOneCheckboxHTML( $checked, $attribs)
shouldInfuseOOUI()
Whether the field should be automatically infused.
__construct( $params)
getInputHTML( $value)
Build a table containing a matrix of checkbox options.
getTableRow( $value)
Get the complete table row for the input, including help text, labels, and whatever.
getOOUIModules()
Get the list of extra ResourceLoader modules which must be loaded client-side before it's possible to...
loadDataFromRequest( $request)
getInputOOUI( $value)
Same as getInputHTML, but returns an OOUI object.
filterDataForSubmit( $data)
Support for separating multi-option preferences into multiple preferences Due to lack of array suppor...
The parent class to generate form fields.
getClassName()
Gets the non namespaced class name.
getErrorsAndErrorClass( $value)
Determine form errors to display and their classes.
getHelpTextHtmlTable( $helptext)
Generate help text HTML in table format.
static flattenOptions( $options)
flatten an array of options to a single array, for instance, a set of "<options>" inside "<optgroups>...
getHelpText()
Determine the help text to display.
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.
getLabelHtml( $cellAttributes=[])
getAttributes(array $list)
Returns the given attributes from the parameters.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:236
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:214
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:256
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:320
A class containing constants representing the names of configuration variables.
static check( $name, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox.
Definition: Xml.php:332