4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
7 abstract class HTMLFormField
{
10 protected $mValidationCallback;
11 protected $mFilterCallback;
14 protected $mLabel; # String label, as HTML. Set on construction.
16 protected $mClass = '';
17 protected $mVFormClass = '';
18 protected $mHelpClass = false;
21 * @var array|bool|null
23 protected $mOptions = false;
24 protected $mOptionsLabelsNotFromMessage = false;
25 protected $mHideIf = null;
28 * @var bool If true will generate an empty div element with no label
31 protected $mShowEmptyLabels = true;
39 * This function must be implemented to return the HTML to generate
40 * the input object itself. It should not implement the surrounding
41 * table cells/rows, or labels/help messages.
43 * @param string $value The value to set the input to; eg a default
44 * text for a text input.
46 * @return string Valid HTML.
48 abstract public function getInputHTML( $value );
51 * Same as getInputHTML, but returns an OOUI object.
52 * Defaults to false, which getOOUI will interpret as "use the HTML version"
54 * @param string $value
55 * @return OOUI\Widget|false
57 public function getInputOOUI( $value ) {
62 * True if this field type is able to display errors; false if validation errors need to be
63 * displayed in the main HTMLForm error area.
66 public function canDisplayErrors() {
67 return $this->hasVisibleOutput();
71 * Get a translated interface message
73 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
74 * and wfMessage() otherwise.
76 * Parameters are the same as wfMessage().
80 public function msg() {
81 $args = func_get_args();
83 if ( $this->mParent
) {
84 $callback = [ $this->mParent
, 'msg' ];
86 $callback = 'wfMessage';
89 return call_user_func_array( $callback, $args );
93 * If this field has a user-visible output or not. If not,
94 * it will not be rendered
98 public function hasVisibleOutput() {
103 * Fetch a field value from $alldata for the closest field matching a given
106 * This is complex because it needs to handle array fields like the user
107 * would expect. The general algorithm is to look for $name as a sibling
108 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
109 * that $name itself might be referencing an array.
111 * @param array $alldata
112 * @param string $name
115 protected function getNearestFieldByName( $alldata, $name ) {
118 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
119 array_unshift( $thisKeys, $m[2] );
122 if ( substr( $tmp, 0, 2 ) == 'wp' &&
123 !array_key_exists( $tmp, $alldata ) &&
124 array_key_exists( substr( $tmp, 2 ), $alldata )
126 // Adjust for name mangling.
127 $tmp = substr( $tmp, 2 );
129 array_unshift( $thisKeys, $tmp );
133 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
134 array_unshift( $nameKeys, $m[2] );
137 array_unshift( $nameKeys, $tmp );
140 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
141 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
144 $key = array_shift( $keys );
145 if ( !is_array( $data ) ||
!array_key_exists( $key, $data ) ) {
150 $testValue = (string)$data;
158 * Helper function for isHidden to handle recursive data structures.
160 * @param array $alldata
161 * @param array $params
163 * @throws MWException
165 protected function isHiddenRecurse( array $alldata, array $params ) {
166 $origParams = $params;
167 $op = array_shift( $params );
172 foreach ( $params as $i => $p ) {
173 if ( !is_array( $p ) ) {
174 throw new MWException(
175 "Expected array, found " . gettype( $p ) . " at index $i"
178 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
185 foreach ( $params as $i => $p ) {
186 if ( !is_array( $p ) ) {
187 throw new MWException(
188 "Expected array, found " . gettype( $p ) . " at index $i"
191 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
198 foreach ( $params as $i => $p ) {
199 if ( !is_array( $p ) ) {
200 throw new MWException(
201 "Expected array, found " . gettype( $p ) . " at index $i"
204 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
211 foreach ( $params as $i => $p ) {
212 if ( !is_array( $p ) ) {
213 throw new MWException(
214 "Expected array, found " . gettype( $p ) . " at index $i"
217 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
224 if ( count( $params ) !== 1 ) {
225 throw new MWException( "NOT takes exactly one parameter" );
228 if ( !is_array( $p ) ) {
229 throw new MWException(
230 "Expected array, found " . gettype( $p ) . " at index 0"
233 return !$this->isHiddenRecurse( $alldata, $p );
237 if ( count( $params ) !== 2 ) {
238 throw new MWException( "$op takes exactly two parameters" );
240 list( $field, $value ) = $params;
241 if ( !is_string( $field ) ||
!is_string( $value ) ) {
242 throw new MWException( "Parameters for $op must be strings" );
244 $testValue = $this->getNearestFieldByName( $alldata, $field );
247 return ( $value === $testValue );
249 return ( $value !== $testValue );
253 throw new MWException( "Unknown operation" );
255 } catch ( Exception
$ex ) {
256 throw new MWException(
257 "Invalid hide-if specification for $this->mName: " .
258 $ex->getMessage() . " in " . var_export( $origParams, true ),
265 * Test whether this field is supposed to be hidden, based on the values of
266 * the other form fields.
269 * @param array $alldata The data collected from the form
272 public function isHidden( $alldata ) {
273 if ( !$this->mHideIf
) {
277 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
281 * Override this function if the control can somehow trigger a form
282 * submission that shouldn't actually submit the HTMLForm.
285 * @param string|array $value The value the field was submitted with
286 * @param array $alldata The data collected from the form
288 * @return bool True to cancel the submission
290 public function cancelSubmit( $value, $alldata ) {
295 * Override this function to add specific validation checks on the
296 * field input. Don't forget to call parent::validate() to ensure
297 * that the user-defined callback mValidationCallback is still run
299 * @param string|array $value The value the field was submitted with
300 * @param array $alldata The data collected from the form
302 * @return bool|string|Message True on success, or String/Message error to display, or
303 * false to fail validation without displaying an error.
305 public function validate( $value, $alldata ) {
306 if ( $this->isHidden( $alldata ) ) {
310 if ( isset( $this->mParams
['required'] )
311 && $this->mParams
['required'] !== false
314 return $this->msg( 'htmlform-required' );
317 if ( isset( $this->mValidationCallback
) ) {
318 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
324 public function filter( $value, $alldata ) {
325 if ( isset( $this->mFilterCallback
) ) {
326 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
333 * Should this field have a label, or is there no input element with the
334 * appropriate id for the label to point to?
336 * @return bool True to output a label, false to suppress
338 protected function needsLabel() {
343 * Tell the field whether to generate a separate label element if its label
348 * @param bool $show Set to false to not generate a label.
351 public function setShowEmptyLabel( $show ) {
352 $this->mShowEmptyLabels
= $show;
356 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
357 * just view it? This can't normally be distinguished for e.g. checkboxes.
359 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
360 * (wpFormIdentifier).
362 * @param WebRequest $request
365 protected function isSubmitAttempt( WebRequest
$request ) {
366 return $request->getCheck( 'wpEditToken' ) ||
$request->getCheck( 'wpFormIdentifier' );
370 * Get the value that this input has been set to from a posted form,
371 * or the input's default value if it has not been set.
373 * @param WebRequest $request
374 * @return string The value
376 public function loadDataFromRequest( $request ) {
377 if ( $request->getCheck( $this->mName
) ) {
378 return $request->getText( $this->mName
);
380 return $this->getDefault();
385 * Initialise the object
387 * @param array $params Associative Array. See HTMLForm doc for syntax.
389 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
390 * @throws MWException
392 public function __construct( $params ) {
393 $this->mParams
= $params;
395 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
396 $this->mParent
= $params['parent'];
399 # Generate the label from a message, if possible
400 if ( isset( $params['label-message'] ) ) {
401 $this->mLabel
= $this->getMessage( $params['label-message'] )->parse();
402 } elseif ( isset( $params['label'] ) ) {
403 if ( $params['label'] === ' ' ) {
404 // Apparently some things set   directly and in an odd format
405 $this->mLabel
= ' ';
407 $this->mLabel
= htmlspecialchars( $params['label'] );
409 } elseif ( isset( $params['label-raw'] ) ) {
410 $this->mLabel
= $params['label-raw'];
413 $this->mName
= "wp{$params['fieldname']}";
414 if ( isset( $params['name'] ) ) {
415 $this->mName
= $params['name'];
418 if ( isset( $params['dir'] ) ) {
419 $this->mDir
= $params['dir'];
422 $validName = urlencode( $this->mName
);
423 $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
424 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
425 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
428 $this->mID
= "mw-input-{$this->mName}";
430 if ( isset( $params['default'] ) ) {
431 $this->mDefault
= $params['default'];
434 if ( isset( $params['id'] ) ) {
436 $validId = urlencode( $id );
438 if ( $id != $validId ) {
439 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
445 if ( isset( $params['cssclass'] ) ) {
446 $this->mClass
= $params['cssclass'];
449 if ( isset( $params['csshelpclass'] ) ) {
450 $this->mHelpClass
= $params['csshelpclass'];
453 if ( isset( $params['validation-callback'] ) ) {
454 $this->mValidationCallback
= $params['validation-callback'];
457 if ( isset( $params['filter-callback'] ) ) {
458 $this->mFilterCallback
= $params['filter-callback'];
461 if ( isset( $params['hidelabel'] ) ) {
462 $this->mShowEmptyLabels
= false;
465 if ( isset( $params['hide-if'] ) ) {
466 $this->mHideIf
= $params['hide-if'];
471 * Get the complete table row for the input, including help text,
472 * labels, and whatever.
474 * @param string $value The value to set the input to.
476 * @return string Complete HTML table row.
478 public function getTableRow( $value ) {
479 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
480 $inputHtml = $this->getInputHTML( $value );
481 $fieldType = static::class;
482 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
483 $cellAttributes = [];
487 if ( !empty( $this->mParams
['vertical-label'] ) ) {
488 $cellAttributes['colspan'] = 2;
489 $verticalLabel = true;
491 $verticalLabel = false;
494 $label = $this->getLabelHtml( $cellAttributes );
496 $field = Html
::rawElement(
498 [ 'class' => 'mw-input' ] +
$cellAttributes,
499 $inputHtml . "\n$errors"
502 if ( $this->mHideIf
) {
503 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
504 $rowClasses .= ' mw-htmlform-hide-if';
507 if ( $verticalLabel ) {
508 $html = Html
::rawElement( 'tr',
509 $rowAttributes +
[ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
510 $html .= Html
::rawElement( 'tr',
512 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
517 Html
::rawElement( 'tr',
519 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
524 return $html . $helptext;
528 * Get the complete div for the input, including help text,
529 * labels, and whatever.
532 * @param string $value The value to set the input to.
534 * @return string Complete HTML table row.
536 public function getDiv( $value ) {
537 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
538 $inputHtml = $this->getInputHTML( $value );
539 $fieldType = static::class;
540 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
541 $cellAttributes = [];
542 $label = $this->getLabelHtml( $cellAttributes );
546 'mw-htmlform-nolabel' => ( $label === '' )
549 $horizontalLabel = isset( $this->mParams
['horizontal-label'] )
550 ?
$this->mParams
['horizontal-label'] : false;
552 if ( $horizontalLabel ) {
553 $field = ' ' . $inputHtml . "\n$errors";
555 $field = Html
::rawElement(
557 [ 'class' => $outerDivClass ] +
$cellAttributes,
558 $inputHtml . "\n$errors"
561 $divCssClasses = [ "mw-htmlform-field-$fieldType",
562 $this->mClass
, $this->mVFormClass
, $errorClass ];
564 $wrapperAttributes = [
565 'class' => $divCssClasses,
567 if ( $this->mHideIf
) {
568 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
569 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
571 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
578 * Get the OOUI version of the div. Falls back to getDiv by default.
581 * @param string $value The value to set the input to.
583 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
585 public function getOOUI( $value ) {
586 $inputField = $this->getInputOOUI( $value );
588 if ( !$inputField ) {
589 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
590 // generate the whole field, label and errors and all, then wrap it in a Widget.
591 // It might look weird, but it'll work OK.
592 return $this->getFieldLayoutOOUI(
593 new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $this->getDiv( $value ) ) ] ),
594 [ 'infusable' => false, 'align' => 'top' ]
599 if ( is_string( $inputField ) ) {
600 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
601 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
602 // JavaScript doesn't know how to rebuilt the contents.
603 $inputField = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $inputField ) ] );
607 $fieldType = static::class;
608 $help = $this->getHelpText();
609 $errors = $this->getErrorsRaw( $value );
610 foreach ( $errors as &$error ) {
611 $error = new OOUI\
HtmlSnippet( $error );
614 $notices = $this->getNotices();
615 foreach ( $notices as &$notice ) {
616 $notice = new OOUI\
HtmlSnippet( $notice );
620 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass
],
621 'align' => $this->getLabelAlignOOUI(),
622 'help' => ( $help !== null && $help !== '' ) ?
new OOUI\
HtmlSnippet( $help ) : null,
624 'notices' => $notices,
625 'infusable' => $infusable,
628 $preloadModules = false;
630 if ( $infusable && $this->shouldInfuseOOUI() ) {
631 $preloadModules = true;
632 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
635 // the element could specify, that the label doesn't need to be added
636 $label = $this->getLabel();
637 if ( $label && $label !== ' ' ) {
638 $config['label'] = new OOUI\
HtmlSnippet( $label );
641 if ( $this->mHideIf
) {
642 $preloadModules = true;
643 $config['hideIf'] = $this->mHideIf
;
646 $config['modules'] = $this->getOOUIModules();
648 if ( $preloadModules ) {
649 $this->mParent
->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
650 $this->mParent
->getOutput()->addModules( $this->getOOUIModules() );
653 return $this->getFieldLayoutOOUI( $inputField, $config );
657 * Get label alignment when generating field for OOUI.
658 * @return string 'left', 'right', 'top' or 'inline'
660 protected function getLabelAlignOOUI() {
665 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
666 * @param string $inputField
667 * @param array $config
668 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
670 protected function getFieldLayoutOOUI( $inputField, $config ) {
671 if ( isset( $this->mClassWithButton
) ) {
672 $buttonWidget = $this->mClassWithButton
->getInputOOUI( '' );
673 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
675 return new HTMLFormFieldLayout( $inputField, $config );
679 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
680 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
681 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
685 protected function shouldInfuseOOUI() {
686 // Always infuse fields with help text, since the interface for it is nicer with JS
687 return $this->getHelpText() !== null;
691 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
692 * possible to infuse this field's OOUI widget.
696 protected function getOOUIModules() {
701 * Get the complete raw fields for the input, including help text,
702 * labels, and whatever.
705 * @param string $value The value to set the input to.
707 * @return string Complete HTML table row.
709 public function getRaw( $value ) {
710 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
711 $inputHtml = $this->getInputHTML( $value );
712 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
713 $cellAttributes = [];
714 $label = $this->getLabelHtml( $cellAttributes );
725 * Get the complete field for the input, including help text,
726 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
729 * @param string $value The value to set the input to.
730 * @return string Complete HTML field.
732 public function getVForm( $value ) {
734 $this->mVFormClass
= ' mw-ui-vform-field';
735 return $this->getDiv( $value );
739 * Get the complete field as an inline element.
741 * @param string $value The value to set the input to.
742 * @return string Complete HTML inline element
744 public function getInline( $value ) {
745 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
746 $inputHtml = $this->getInputHTML( $value );
747 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
748 $cellAttributes = [];
749 $label = $this->getLabelHtml( $cellAttributes );
751 $html = "\n" . $errors .
760 * Generate help text HTML in table format
763 * @param string|null $helptext
766 public function getHelpTextHtmlTable( $helptext ) {
767 if ( is_null( $helptext ) ) {
772 if ( $this->mHideIf
) {
773 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
774 $rowAttributes['class'] = 'mw-htmlform-hide-if';
777 $tdClasses = [ 'htmlform-tip' ];
778 if ( $this->mHelpClass
!== false ) {
779 $tdClasses[] = $this->mHelpClass
;
781 $row = Html
::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
782 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
788 * Generate help text HTML in div format
791 * @param string|null $helptext
795 public function getHelpTextHtmlDiv( $helptext ) {
796 if ( is_null( $helptext ) ) {
800 $wrapperAttributes = [
801 'class' => 'htmlform-tip',
803 if ( $this->mHelpClass
!== false ) {
804 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
806 if ( $this->mHideIf
) {
807 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
808 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
810 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
816 * Generate help text HTML formatted for raw output
819 * @param string|null $helptext
822 public function getHelpTextHtmlRaw( $helptext ) {
823 return $this->getHelpTextHtmlDiv( $helptext );
827 * Determine the help text to display
829 * @return string|null HTML
831 public function getHelpText() {
834 if ( isset( $this->mParams
['help-message'] ) ) {
835 $this->mParams
['help-messages'] = [ $this->mParams
['help-message'] ];
838 if ( isset( $this->mParams
['help-messages'] ) ) {
839 foreach ( $this->mParams
['help-messages'] as $msg ) {
840 $msg = $this->getMessage( $msg );
842 if ( $msg->exists() ) {
843 if ( is_null( $helptext ) ) {
846 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
848 $helptext .= $msg->parse(); // Append message
851 } elseif ( isset( $this->mParams
['help'] ) ) {
852 $helptext = $this->mParams
['help'];
859 * Determine form errors to display and their classes
862 * @param string $value The value of the input
863 * @return array array( $errors, $errorClass )
865 public function getErrorsAndErrorClass( $value ) {
866 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
868 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
872 $errors = self
::formatErrors( $errors );
873 $errorClass = 'mw-htmlform-invalid-input';
876 return [ $errors, $errorClass ];
880 * Determine form errors to display, returning them in an array.
883 * @param string $value The value of the input
884 * @return string[] Array of error HTML strings
886 public function getErrorsRaw( $value ) {
887 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
889 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
893 if ( !is_array( $errors ) ) {
894 $errors = [ $errors ];
896 foreach ( $errors as &$error ) {
897 if ( $error instanceof Message
) {
898 $error = $error->parse();
906 * Determine notices to display for the field.
911 public function getNotices() {
914 if ( isset( $this->mParams
['notice-message'] ) ) {
915 $notices[] = $this->getMessage( $this->mParams
['notice-message'] )->parse();
918 if ( isset( $this->mParams
['notice-messages'] ) ) {
919 foreach ( $this->mParams
['notice-messages'] as $msg ) {
920 $notices[] = $this->getMessage( $msg )->parse();
922 } elseif ( isset( $this->mParams
['notice'] ) ) {
923 $notices[] = $this->mParams
['notice'];
930 * @return string HTML
932 public function getLabel() {
933 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
936 public function getLabelHtml( $cellAttributes = [] ) {
937 # Don't output a for= attribute for labels with no associated input.
938 # Kind of hacky here, possibly we don't want these to be <label>s at all.
941 if ( $this->needsLabel() ) {
942 $for['for'] = $this->mID
;
945 $labelValue = trim( $this->getLabel() );
947 if ( $labelValue !== ' ' && $labelValue !== '' ) {
951 $displayFormat = $this->mParent
->getDisplayFormat();
953 $horizontalLabel = isset( $this->mParams
['horizontal-label'] )
954 ?
$this->mParams
['horizontal-label'] : false;
956 if ( $displayFormat === 'table' ) {
958 Html
::rawElement( 'td',
959 [ 'class' => 'mw-label' ] +
$cellAttributes,
960 Html
::rawElement( 'label', $for, $labelValue ) );
961 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
962 if ( $displayFormat === 'div' && !$horizontalLabel ) {
964 Html
::rawElement( 'div',
965 [ 'class' => 'mw-label' ] +
$cellAttributes,
966 Html
::rawElement( 'label', $for, $labelValue ) );
968 $html = Html
::rawElement( 'label', $for, $labelValue );
975 public function getDefault() {
976 if ( isset( $this->mDefault
) ) {
977 return $this->mDefault
;
984 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
986 * @return array Attributes
988 public function getTooltipAndAccessKey() {
989 if ( empty( $this->mParams
['tooltip'] ) ) {
993 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
997 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
999 * @return array Attributes
1001 public function getTooltipAndAccessKeyOOUI() {
1002 if ( empty( $this->mParams
['tooltip'] ) ) {
1007 'title' => Linker
::titleAttrib( $this->mParams
['tooltip'] ),
1008 'accessKey' => Linker
::accesskey( $this->mParams
['tooltip'] ),
1013 * Returns the given attributes from the parameters
1015 * @param array $list List of attributes to get
1016 * @return array Attributes
1018 public function getAttributes( array $list ) {
1019 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1022 foreach ( $list as $key ) {
1023 if ( in_array( $key, $boolAttribs ) ) {
1024 if ( !empty( $this->mParams
[$key] ) ) {
1027 } elseif ( isset( $this->mParams
[$key] ) ) {
1028 $ret[$key] = $this->mParams
[$key];
1036 * Given an array of msg-key => value mappings, returns an array with keys
1037 * being the message texts. It also forces values to strings.
1039 * @param array $options
1042 private function lookupOptionsKeys( $options ) {
1044 foreach ( $options as $key => $value ) {
1045 $key = $this->msg( $key )->plain();
1046 $ret[$key] = is_array( $value )
1047 ?
$this->lookupOptionsKeys( $value )
1054 * Recursively forces values in an array to strings, because issues arise
1055 * with integer 0 as a value.
1057 * @param array $array
1058 * @return array|string
1060 public static function forceToStringRecursive( $array ) {
1061 if ( is_array( $array ) ) {
1062 return array_map( [ __CLASS__
, 'forceToStringRecursive' ], $array );
1064 return strval( $array );
1069 * Fetch the array of options from the field's parameters. In order, this
1070 * checks 'options-messages', 'options', then 'options-message'.
1072 * @return array|null Options array
1074 public function getOptions() {
1075 if ( $this->mOptions
=== false ) {
1076 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
1077 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
1078 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
1079 $this->mOptionsLabelsNotFromMessage
= true;
1080 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
1081 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
1082 $message = $this->getMessage( $this->mParams
['options-message'] )->inContentLanguage()->plain();
1083 $this->mOptions
= Xml
::listDropDownOptions( $message );
1085 $this->mOptions
= null;
1089 return $this->mOptions
;
1093 * Get options and make them into arrays suitable for OOUI.
1094 * @return array Options for inclusion in a select or whatever.
1096 public function getOptionsOOUI() {
1097 $oldoptions = $this->getOptions();
1099 if ( $oldoptions === null ) {
1103 return Xml
::listDropDownOptionsOoui( $oldoptions );
1107 * flatten an array of options to a single array, for instance,
1108 * a set of "<options>" inside "<optgroups>".
1110 * @param array $options Associative Array with values either Strings or Arrays
1111 * @return array Flattened input
1113 public static function flattenOptions( $options ) {
1116 foreach ( $options as $value ) {
1117 if ( is_array( $value ) ) {
1118 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1120 $flatOpts[] = $value;
1128 * Formats one or more errors as accepted by field validation-callback.
1130 * @param string|Message|array $errors Array of strings or Message instances
1131 * @return string HTML
1134 protected static function formatErrors( $errors ) {
1135 // Note: If you change the logic in this method, change
1136 // htmlform.Checker.js to match.
1138 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1139 $errors = array_shift( $errors );
1142 if ( is_array( $errors ) ) {
1144 foreach ( $errors as $error ) {
1145 if ( $error instanceof Message
) {
1146 $lines[] = Html
::rawElement( 'li', [], $error->parse() );
1148 $lines[] = Html
::rawElement( 'li', [], $error );
1152 return Html
::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1154 if ( $errors instanceof Message
) {
1155 $errors = $errors->parse();
1158 return Html
::rawElement( 'span', [ 'class' => 'error' ], $errors );
1163 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1164 * name + parameters array) into a Message.
1165 * @param mixed $value
1168 protected function getMessage( $value ) {
1169 $message = Message
::newFromSpecifier( $value );
1171 if ( $this->mParent
) {
1172 $message->setContext( $this->mParent
);
1179 * Skip this field when collecting data.
1180 * @param WebRequest $request
1184 public function skipLoadData( $request ) {
1185 return !empty( $this->mParams
['nodata'] );
1189 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1190 * form validation to work correctly.
1195 public function needsJSForHtml5FormValidation() {
1196 if ( $this->mHideIf
) {
1197 // This is probably more restrictive than it needs to be, but better safe than sorry