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 = $this->mParams
['horizontal-label'] ??
false;
551 if ( $horizontalLabel ) {
552 $field = ' ' . $inputHtml . "\n$errors";
554 $field = Html
::rawElement(
556 [ 'class' => $outerDivClass ] +
$cellAttributes,
557 $inputHtml . "\n$errors"
560 $divCssClasses = [ "mw-htmlform-field-$fieldType",
561 $this->mClass
, $this->mVFormClass
, $errorClass ];
563 $wrapperAttributes = [
564 'class' => $divCssClasses,
566 if ( $this->mHideIf
) {
567 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
568 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
570 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
577 * Get the OOUI version of the div. Falls back to getDiv by default.
580 * @param string $value The value to set the input to.
582 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
584 public function getOOUI( $value ) {
585 $inputField = $this->getInputOOUI( $value );
587 if ( !$inputField ) {
588 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
589 // generate the whole field, label and errors and all, then wrap it in a Widget.
590 // It might look weird, but it'll work OK.
591 return $this->getFieldLayoutOOUI(
592 new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $this->getDiv( $value ) ) ] ),
593 [ 'infusable' => false, 'align' => 'top' ]
598 if ( is_string( $inputField ) ) {
599 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
600 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
601 // JavaScript doesn't know how to rebuilt the contents.
602 $inputField = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $inputField ) ] );
606 $fieldType = static::class;
607 $help = $this->getHelpText();
608 $errors = $this->getErrorsRaw( $value );
609 foreach ( $errors as &$error ) {
610 $error = new OOUI\
HtmlSnippet( $error );
613 $notices = $this->getNotices();
614 foreach ( $notices as &$notice ) {
615 $notice = new OOUI\
HtmlSnippet( $notice );
619 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass
],
620 'align' => $this->getLabelAlignOOUI(),
621 'help' => ( $help !== null && $help !== '' ) ?
new OOUI\
HtmlSnippet( $help ) : null,
623 'notices' => $notices,
624 'infusable' => $infusable,
627 $preloadModules = false;
629 if ( $infusable && $this->shouldInfuseOOUI() ) {
630 $preloadModules = true;
631 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
634 // the element could specify, that the label doesn't need to be added
635 $label = $this->getLabel();
636 if ( $label && $label !== ' ' ) {
637 $config['label'] = new OOUI\
HtmlSnippet( $label );
640 if ( $this->mHideIf
) {
641 $preloadModules = true;
642 $config['hideIf'] = $this->mHideIf
;
645 $config['modules'] = $this->getOOUIModules();
647 if ( $preloadModules ) {
648 $this->mParent
->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
649 $this->mParent
->getOutput()->addModules( $this->getOOUIModules() );
652 return $this->getFieldLayoutOOUI( $inputField, $config );
656 * Get label alignment when generating field for OOUI.
657 * @return string 'left', 'right', 'top' or 'inline'
659 protected function getLabelAlignOOUI() {
664 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
665 * @param string $inputField
666 * @param array $config
667 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
669 protected function getFieldLayoutOOUI( $inputField, $config ) {
670 if ( isset( $this->mClassWithButton
) ) {
671 $buttonWidget = $this->mClassWithButton
->getInputOOUI( '' );
672 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
674 return new HTMLFormFieldLayout( $inputField, $config );
678 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
679 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
680 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
684 protected function shouldInfuseOOUI() {
685 // Always infuse fields with help text, since the interface for it is nicer with JS
686 return $this->getHelpText() !== null;
690 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
691 * possible to infuse this field's OOUI widget.
695 protected function getOOUIModules() {
700 * Get the complete raw fields for the input, including help text,
701 * labels, and whatever.
704 * @param string $value The value to set the input to.
706 * @return string Complete HTML table row.
708 public function getRaw( $value ) {
709 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
710 $inputHtml = $this->getInputHTML( $value );
711 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
712 $cellAttributes = [];
713 $label = $this->getLabelHtml( $cellAttributes );
724 * Get the complete field for the input, including help text,
725 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
728 * @param string $value The value to set the input to.
729 * @return string Complete HTML field.
731 public function getVForm( $value ) {
733 $this->mVFormClass
= ' mw-ui-vform-field';
734 return $this->getDiv( $value );
738 * Get the complete field as an inline element.
740 * @param string $value The value to set the input to.
741 * @return string Complete HTML inline element
743 public function getInline( $value ) {
744 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
745 $inputHtml = $this->getInputHTML( $value );
746 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
747 $cellAttributes = [];
748 $label = $this->getLabelHtml( $cellAttributes );
750 $html = "\n" . $errors .
759 * Generate help text HTML in table format
762 * @param string|null $helptext
765 public function getHelpTextHtmlTable( $helptext ) {
766 if ( is_null( $helptext ) ) {
771 if ( $this->mHideIf
) {
772 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
773 $rowAttributes['class'] = 'mw-htmlform-hide-if';
776 $tdClasses = [ 'htmlform-tip' ];
777 if ( $this->mHelpClass
!== false ) {
778 $tdClasses[] = $this->mHelpClass
;
780 $row = Html
::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
781 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
787 * Generate help text HTML in div format
790 * @param string|null $helptext
794 public function getHelpTextHtmlDiv( $helptext ) {
795 if ( is_null( $helptext ) ) {
799 $wrapperAttributes = [
800 'class' => 'htmlform-tip',
802 if ( $this->mHelpClass
!== false ) {
803 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
805 if ( $this->mHideIf
) {
806 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
807 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
809 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
815 * Generate help text HTML formatted for raw output
818 * @param string|null $helptext
821 public function getHelpTextHtmlRaw( $helptext ) {
822 return $this->getHelpTextHtmlDiv( $helptext );
826 * Determine the help text to display
828 * @return string|null HTML
830 public function getHelpText() {
833 if ( isset( $this->mParams
['help-message'] ) ) {
834 $this->mParams
['help-messages'] = [ $this->mParams
['help-message'] ];
837 if ( isset( $this->mParams
['help-messages'] ) ) {
838 foreach ( $this->mParams
['help-messages'] as $msg ) {
839 $msg = $this->getMessage( $msg );
841 if ( $msg->exists() ) {
842 if ( is_null( $helptext ) ) {
845 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
847 $helptext .= $msg->parse(); // Append message
850 } elseif ( isset( $this->mParams
['help'] ) ) {
851 $helptext = $this->mParams
['help'];
858 * Determine form errors to display and their classes
861 * @param string $value The value of the input
862 * @return array array( $errors, $errorClass )
864 public function getErrorsAndErrorClass( $value ) {
865 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
867 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
871 $errors = self
::formatErrors( $errors );
872 $errorClass = 'mw-htmlform-invalid-input';
875 return [ $errors, $errorClass ];
879 * Determine form errors to display, returning them in an array.
882 * @param string $value The value of the input
883 * @return string[] Array of error HTML strings
885 public function getErrorsRaw( $value ) {
886 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
888 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
892 if ( !is_array( $errors ) ) {
893 $errors = [ $errors ];
895 foreach ( $errors as &$error ) {
896 if ( $error instanceof Message
) {
897 $error = $error->parse();
905 * Determine notices to display for the field.
910 public function getNotices() {
913 if ( isset( $this->mParams
['notice-message'] ) ) {
914 $notices[] = $this->getMessage( $this->mParams
['notice-message'] )->parse();
917 if ( isset( $this->mParams
['notice-messages'] ) ) {
918 foreach ( $this->mParams
['notice-messages'] as $msg ) {
919 $notices[] = $this->getMessage( $msg )->parse();
921 } elseif ( isset( $this->mParams
['notice'] ) ) {
922 $notices[] = $this->mParams
['notice'];
929 * @return string HTML
931 public function getLabel() {
932 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
935 public function getLabelHtml( $cellAttributes = [] ) {
936 # Don't output a for= attribute for labels with no associated input.
937 # Kind of hacky here, possibly we don't want these to be <label>s at all.
940 if ( $this->needsLabel() ) {
941 $for['for'] = $this->mID
;
944 $labelValue = trim( $this->getLabel() );
946 if ( $labelValue !== ' ' && $labelValue !== '' ) {
950 $displayFormat = $this->mParent
->getDisplayFormat();
952 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
954 if ( $displayFormat === 'table' ) {
956 Html
::rawElement( 'td',
957 [ 'class' => 'mw-label' ] +
$cellAttributes,
958 Html
::rawElement( 'label', $for, $labelValue ) );
959 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
960 if ( $displayFormat === 'div' && !$horizontalLabel ) {
962 Html
::rawElement( 'div',
963 [ 'class' => 'mw-label' ] +
$cellAttributes,
964 Html
::rawElement( 'label', $for, $labelValue ) );
966 $html = Html
::rawElement( 'label', $for, $labelValue );
973 public function getDefault() {
974 if ( isset( $this->mDefault
) ) {
975 return $this->mDefault
;
982 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
984 * @return array Attributes
986 public function getTooltipAndAccessKey() {
987 if ( empty( $this->mParams
['tooltip'] ) ) {
991 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
995 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
997 * @return array Attributes
999 public function getTooltipAndAccessKeyOOUI() {
1000 if ( empty( $this->mParams
['tooltip'] ) ) {
1005 'title' => Linker
::titleAttrib( $this->mParams
['tooltip'] ),
1006 'accessKey' => Linker
::accesskey( $this->mParams
['tooltip'] ),
1011 * Returns the given attributes from the parameters
1013 * @param array $list List of attributes to get
1014 * @return array Attributes
1016 public function getAttributes( array $list ) {
1017 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1020 foreach ( $list as $key ) {
1021 if ( in_array( $key, $boolAttribs ) ) {
1022 if ( !empty( $this->mParams
[$key] ) ) {
1025 } elseif ( isset( $this->mParams
[$key] ) ) {
1026 $ret[$key] = $this->mParams
[$key];
1034 * Given an array of msg-key => value mappings, returns an array with keys
1035 * being the message texts. It also forces values to strings.
1037 * @param array $options
1040 private function lookupOptionsKeys( $options ) {
1042 foreach ( $options as $key => $value ) {
1043 $key = $this->msg( $key )->plain();
1044 $ret[$key] = is_array( $value )
1045 ?
$this->lookupOptionsKeys( $value )
1052 * Recursively forces values in an array to strings, because issues arise
1053 * with integer 0 as a value.
1055 * @param array $array
1056 * @return array|string
1058 public static function forceToStringRecursive( $array ) {
1059 if ( is_array( $array ) ) {
1060 return array_map( [ __CLASS__
, 'forceToStringRecursive' ], $array );
1062 return strval( $array );
1067 * Fetch the array of options from the field's parameters. In order, this
1068 * checks 'options-messages', 'options', then 'options-message'.
1070 * @return array|null Options array
1072 public function getOptions() {
1073 if ( $this->mOptions
=== false ) {
1074 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
1075 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
1076 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
1077 $this->mOptionsLabelsNotFromMessage
= true;
1078 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
1079 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
1080 $message = $this->getMessage( $this->mParams
['options-message'] )->inContentLanguage()->plain();
1081 $this->mOptions
= Xml
::listDropDownOptions( $message );
1083 $this->mOptions
= null;
1087 return $this->mOptions
;
1091 * Get options and make them into arrays suitable for OOUI.
1092 * @return array Options for inclusion in a select or whatever.
1094 public function getOptionsOOUI() {
1095 $oldoptions = $this->getOptions();
1097 if ( $oldoptions === null ) {
1101 return Xml
::listDropDownOptionsOoui( $oldoptions );
1105 * flatten an array of options to a single array, for instance,
1106 * a set of "<options>" inside "<optgroups>".
1108 * @param array $options Associative Array with values either Strings or Arrays
1109 * @return array Flattened input
1111 public static function flattenOptions( $options ) {
1114 foreach ( $options as $value ) {
1115 if ( is_array( $value ) ) {
1116 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1118 $flatOpts[] = $value;
1126 * Formats one or more errors as accepted by field validation-callback.
1128 * @param string|Message|array $errors Array of strings or Message instances
1129 * @return string HTML
1132 protected static function formatErrors( $errors ) {
1133 // Note: If you change the logic in this method, change
1134 // htmlform.Checker.js to match.
1136 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1137 $errors = array_shift( $errors );
1140 if ( is_array( $errors ) ) {
1142 foreach ( $errors as $error ) {
1143 if ( $error instanceof Message
) {
1144 $lines[] = Html
::rawElement( 'li', [], $error->parse() );
1146 $lines[] = Html
::rawElement( 'li', [], $error );
1150 return Html
::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1152 if ( $errors instanceof Message
) {
1153 $errors = $errors->parse();
1156 return Html
::rawElement( 'span', [ 'class' => 'error' ], $errors );
1161 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1162 * name + parameters array) into a Message.
1163 * @param mixed $value
1166 protected function getMessage( $value ) {
1167 $message = Message
::newFromSpecifier( $value );
1169 if ( $this->mParent
) {
1170 $message->setContext( $this->mParent
);
1177 * Skip this field when collecting data.
1178 * @param WebRequest $request
1182 public function skipLoadData( $request ) {
1183 return !empty( $this->mParams
['nodata'] );
1187 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1188 * form validation to work correctly.
1193 public function needsJSForHtml5FormValidation() {
1194 if ( $this->mHideIf
) {
1195 // This is probably more restrictive than it needs to be, but better safe than sorry