4 * HTML form generation and submission handling.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms. in a reusable manner.
28 * In order to generate the form, the HTMLForm object takes an array
29 * structure detailing the form fields available. Each element of the
30 * array is a basic property-list, including the type of field, the
31 * label it is to be given in the form, callbacks for validation and
32 * 'filtering', and other pertinent information.
34 * Field types are implemented as subclasses of the generic HTMLFormField
35 * object, and typically implement at least getInputHTML, which generates
36 * the HTML for the input field to be placed in the table.
38 * You can find extensive documentation on the www.mediawiki.org wiki:
39 * - https://www.mediawiki.org/wiki/HTMLForm
40 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
45 * 'class' -- the subclass of HTMLFormField that will be used
46 * to create the object. *NOT* the CSS class!
47 * 'type' -- roughly translates into the <select> type attribute.
48 * if 'class' is not specified, this is used as a map
49 * through HTMLForm::$typeMappings to get the class name.
50 * 'default' -- default value when the form is displayed
51 * 'nodata' -- if set (to any value, which casts to true), the data
52 * for this field will not be loaded from the actual request. Instead,
53 * always the default data is set as the value of this field.
54 * 'id' -- HTML id attribute
55 * 'cssclass' -- CSS class
56 * 'csshelpclass' -- CSS class used to style help text
57 * 'dir' -- Direction of the element.
58 * 'options' -- associative array mapping raw text labels to values.
59 * Some field types support multi-level arrays.
60 * Overwrites 'options-message'.
61 * 'options-messages' -- associative array mapping message keys to values.
62 * Some field types support multi-level arrays.
63 * Overwrites 'options' and 'options-message'.
64 * 'options-message' -- message key or object to be parsed to extract the list of
65 * options (like 'ipbreason-dropdown').
66 * 'label-message' -- message key or object for a message to use as the label.
67 * can be an array of msg key and then parameters to
69 * 'label' -- alternatively, a raw text message. Overridden by
71 * 'help' -- message text for a message to use as a help text.
72 * 'help-message' -- message key or object for a message to use as a help text.
73 * can be an array of msg key and then parameters to
75 * Overwrites 'help-messages' and 'help'.
76 * 'help-messages' -- array of message keys/objects. As above, each item can
77 * be an array of msg key and then parameters.
79 * 'help-inline' -- Whether help text (defined using options above) will be shown
80 * inline after the input field, rather than in a popup.
81 * Defaults to true. Only used by OOUI form fields.
82 * 'required' -- passed through to the object, indicating that it
83 * is a required field.
84 * 'size' -- the length of text fields
85 * 'filter-callback' -- a function name to give you the chance to
86 * massage the inputted value before it's processed.
87 * @see HTMLFormField::filter()
88 * 'validation-callback' -- a function name to give you the chance
89 * to impose extra validation on the field input.
90 * @see HTMLFormField::validate()
91 * 'name' -- By default, the 'name' attribute of the input field
92 * is "wp{$fieldname}". If you want a different name
93 * (eg one without the "wp" prefix), specify it here and
94 * it will be used without modification.
95 * 'hide-if' -- expression given as an array stating when the field
96 * should be hidden. The first array value has to be the
97 * expression's logic operator. Supported expressions:
99 * [ 'NOT', array $expression ]
100 * To hide a field if a given expression is not true.
102 * [ '===', string $fieldName, string $value ]
103 * To hide a field if another field identified by
104 * $field has the value $value.
106 * [ '!==', string $fieldName, string $value ]
107 * Same as [ 'NOT', [ '===', $fieldName, $value ]
108 * 'OR', 'AND', 'NOR', 'NAND'
109 * [ 'XXX', array $expression1, ..., array $expressionN ]
110 * To hide a field if one or more (OR), all (AND),
111 * neither (NOR) or not all (NAND) given expressions
112 * are evaluated as true.
113 * The expressions will be given to a JavaScript frontend
114 * module which will continually update the field's
117 * Since 1.20, you can chain mutators to ease the form generation:
120 * $form = new HTMLForm( $someFields );
121 * $form->setMethod( 'get' )
122 * ->setWrapperLegendMsg( 'message-key' )
124 * ->displayForm( '' );
126 * Note that you will have prepareForm and displayForm at the end. Other
127 * methods call done after that would simply not be part of the form :(
129 * @todo Document 'section' / 'subsection' stuff
131 class HTMLForm
extends ContextSource
{
132 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
133 public static $typeMappings = [
134 'api' => HTMLApiField
::class,
135 'text' => HTMLTextField
::class,
136 'textwithbutton' => HTMLTextFieldWithButton
::class,
137 'textarea' => HTMLTextAreaField
::class,
138 'select' => HTMLSelectField
::class,
139 'combobox' => HTMLComboboxField
::class,
140 'radio' => HTMLRadioField
::class,
141 'multiselect' => HTMLMultiSelectField
::class,
142 'limitselect' => HTMLSelectLimitField
::class,
143 'check' => HTMLCheckField
::class,
144 'toggle' => HTMLCheckField
::class,
145 'int' => HTMLIntField
::class,
146 'float' => HTMLFloatField
::class,
147 'info' => HTMLInfoField
::class,
148 'selectorother' => HTMLSelectOrOtherField
::class,
149 'selectandother' => HTMLSelectAndOtherField
::class,
150 'namespaceselect' => HTMLSelectNamespace
::class,
151 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton
::class,
152 'tagfilter' => HTMLTagFilter
::class,
153 'sizefilter' => HTMLSizeFilterField
::class,
154 'submit' => HTMLSubmitField
::class,
155 'hidden' => HTMLHiddenField
::class,
156 'edittools' => HTMLEditTools
::class,
157 'checkmatrix' => HTMLCheckMatrix
::class,
158 'cloner' => HTMLFormFieldCloner
::class,
159 'autocompleteselect' => HTMLAutoCompleteSelectField
::class,
160 'language' => HTMLSelectLanguageField
::class,
161 'date' => HTMLDateTimeField
::class,
162 'time' => HTMLDateTimeField
::class,
163 'datetime' => HTMLDateTimeField
::class,
164 'expiry' => HTMLExpiryField
::class,
165 // HTMLTextField will output the correct type="" attribute automagically.
166 // There are about four zillion other HTML5 input types, like range, but
167 // we don't use those at the moment, so no point in adding all of them.
168 'email' => HTMLTextField
::class,
169 'password' => HTMLTextField
::class,
170 'url' => HTMLTextField
::class,
171 'title' => HTMLTitleTextField
::class,
172 'user' => HTMLUserTextField
::class,
173 'usersmultiselect' => HTMLUsersMultiselectField
::class,
174 'titlesmultiselect' => HTMLTitlesMultiselectField
::class,
175 'namespacesmultiselect' => HTMLNamespacesMultiselectField
::class,
180 protected $mMessagePrefix;
182 /** @var HTMLFormField[] */
183 protected $mFlatFields;
185 protected $mFieldTree;
186 protected $mShowReset = false;
187 protected $mShowSubmit = true;
188 protected $mSubmitFlags = [ 'primary', 'progressive' ];
189 protected $mShowCancel = false;
190 protected $mCancelTarget;
192 protected $mSubmitCallback;
193 protected $mValidationErrorMessage;
195 protected $mPre = '';
196 protected $mHeader = '';
197 protected $mFooter = '';
198 protected $mSectionHeaders = [];
199 protected $mSectionFooters = [];
200 protected $mPost = '';
203 protected $mTableId = '';
205 protected $mSubmitID;
206 protected $mSubmitName;
207 protected $mSubmitText;
208 protected $mSubmitTooltip;
210 protected $mFormIdentifier;
212 protected $mMethod = 'post';
213 protected $mWasSubmitted = false;
216 * Form action URL. false means we will use the URL to set Title
220 protected $mAction = false;
223 * Whether the form can be collapsed
227 protected $mCollapsible = false;
230 * Whether the form is collapsed by default
234 protected $mCollapsed = false;
237 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
241 protected $mAutocomplete = null;
243 protected $mUseMultipart = false;
244 protected $mHiddenFields = [];
245 protected $mButtons = [];
247 protected $mWrapperLegend = false;
248 protected $mWrapperAttributes = [];
251 * Salt for the edit token.
254 protected $mTokenSalt = '';
257 * If true, sections that contain both fields and subsections will
258 * render their subsections before their fields.
260 * Subclasses may set this to false to render subsections after fields
263 protected $mSubSectionBeforeFields = true;
266 * Format in which to display form. For viable options,
267 * @see $availableDisplayFormats
270 protected $displayFormat = 'table';
273 * Available formats in which to display the form
276 protected $availableDisplayFormats = [
284 * Available formats in which to display the form
287 protected $availableSubclassDisplayFormats = [
293 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
295 * @param string $displayFormat
296 * @param mixed $arguments,... Additional arguments to pass to the constructor.
299 public static function factory( $displayFormat/*, $arguments...*/ ) {
300 $arguments = func_get_args();
301 array_shift( $arguments );
303 switch ( $displayFormat ) {
305 return new VFormHTMLForm( ...$arguments );
307 return new OOUIHTMLForm( ...$arguments );
309 $form = new self( ...$arguments );
310 $form->setDisplayFormat( $displayFormat );
316 * Build a new HTMLForm from an array of field attributes
318 * @param array $descriptor Array of Field constructs, as described above
319 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
320 * Obviates the need to call $form->setTitle()
321 * @param string $messagePrefix A prefix to go in front of default messages
323 public function __construct( $descriptor, /*IContextSource*/ $context = null,
326 if ( $context instanceof IContextSource
) {
327 $this->setContext( $context );
328 $this->mTitle
= false; // We don't need them to set a title
329 $this->mMessagePrefix
= $messagePrefix;
330 } elseif ( $context === null && $messagePrefix !== '' ) {
331 $this->mMessagePrefix
= $messagePrefix;
332 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
334 // it's actually $messagePrefix
335 $this->mMessagePrefix
= $context;
338 // Evil hack for mobile :(
340 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
341 && $this->displayFormat
=== 'table'
343 $this->displayFormat
= 'div';
346 // Expand out into a tree.
347 $loadedDescriptor = [];
348 $this->mFlatFields
= [];
350 foreach ( $descriptor as $fieldname => $info ) {
351 $section = $info['section'] ??
'';
353 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
354 $this->mUseMultipart
= true;
357 $field = static::loadInputFromParameters( $fieldname, $info, $this );
359 $setSection =& $loadedDescriptor;
361 foreach ( explode( '/', $section ) as $newName ) {
362 if ( !isset( $setSection[$newName] ) ) {
363 $setSection[$newName] = [];
366 $setSection =& $setSection[$newName];
370 $setSection[$fieldname] = $field;
371 $this->mFlatFields
[$fieldname] = $field;
374 $this->mFieldTree
= $loadedDescriptor;
378 * @param string $fieldname
381 public function hasField( $fieldname ) {
382 return isset( $this->mFlatFields
[$fieldname] );
386 * @param string $fieldname
387 * @return HTMLFormField
388 * @throws DomainException on invalid field name
390 public function getField( $fieldname ) {
391 if ( !$this->hasField( $fieldname ) ) {
392 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
394 return $this->mFlatFields
[$fieldname];
398 * Set format in which to display the form
400 * @param string $format The name of the format to use, must be one of
401 * $this->availableDisplayFormats
403 * @throws MWException
405 * @return HTMLForm $this for chaining calls (since 1.20)
407 public function setDisplayFormat( $format ) {
409 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
410 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
412 throw new MWException( 'Cannot change display format after creation, ' .
413 'use HTMLForm::factory() instead' );
416 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
417 throw new MWException( 'Display format must be one of ' .
420 $this->availableDisplayFormats
,
421 $this->availableSubclassDisplayFormats
427 // Evil hack for mobile :(
428 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
432 $this->displayFormat
= $format;
438 * Getter for displayFormat
442 public function getDisplayFormat() {
443 return $this->displayFormat
;
447 * Get the HTMLFormField subclass for this descriptor.
449 * The descriptor can be passed either 'class' which is the name of
450 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
451 * This makes sure the 'class' is always set, and also is returned by
452 * this function for ease.
456 * @param string $fieldname Name of the field
457 * @param array &$descriptor Input Descriptor, as described above
459 * @throws MWException
460 * @return string Name of a HTMLFormField subclass
462 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
463 if ( isset( $descriptor['class'] ) ) {
464 $class = $descriptor['class'];
465 } elseif ( isset( $descriptor['type'] ) ) {
466 $class = static::$typeMappings[$descriptor['type']];
467 $descriptor['class'] = $class;
473 throw new MWException( "Descriptor with no class for $fieldname: "
474 . print_r( $descriptor, true ) );
481 * Initialise a new Object for the field
483 * @param string $fieldname Name of the field
484 * @param array $descriptor Input Descriptor, as described above
485 * @param HTMLForm|null $parent Parent instance of HTMLForm
487 * @throws MWException
488 * @return HTMLFormField Instance of a subclass of HTMLFormField
490 public static function loadInputFromParameters( $fieldname, $descriptor,
491 HTMLForm
$parent = null
493 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
495 $descriptor['fieldname'] = $fieldname;
497 $descriptor['parent'] = $parent;
500 # @todo This will throw a fatal error whenever someone try to use
501 # 'class' to feed a CSS class instead of 'cssclass'. Would be
502 # great to avoid the fatal error and show a nice error.
503 return new $class( $descriptor );
507 * Prepare form for submission.
509 * @warning When doing method chaining, that should be the very last
510 * method call before displayForm().
512 * @throws MWException
513 * @return HTMLForm $this for chaining calls (since 1.20)
515 public function prepareForm() {
516 # Check if we have the info we need
517 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
518 throw new MWException( 'You must call setTitle() on an HTMLForm' );
521 # Load data from the request.
523 $this->mFormIdentifier
=== null ||
524 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
528 $this->mFieldData
= [];
535 * Try submitting, with edit token check first
536 * @return Status|bool
538 public function tryAuthorizedSubmit() {
541 if ( $this->mFormIdentifier
=== null ) {
544 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
548 if ( $this->getMethod() !== 'post' ) {
549 $tokenOkay = true; // no session check needed
550 } elseif ( $this->getRequest()->wasPosted() ) {
551 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
552 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
553 // Session tokens for logged-out users have no security value.
554 // However, if the user gave one, check it in order to give a nice
555 // "session expired" error instead of "permission denied" or such.
556 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
562 if ( $tokenOkay && $identOkay ) {
563 $this->mWasSubmitted
= true;
564 $result = $this->trySubmit();
571 * The here's-one-I-made-earlier option: do the submission if
572 * posted, or display the form with or without funky validation
574 * @return bool|Status Whether submission was successful.
576 public function show() {
577 $this->prepareForm();
579 $result = $this->tryAuthorizedSubmit();
580 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
584 $this->displayForm( $result );
590 * Same as self::show with the difference, that the form will be
591 * added to the output, no matter, if the validation was good or not.
592 * @return bool|Status Whether submission was successful.
594 public function showAlways() {
595 $this->prepareForm();
597 $result = $this->tryAuthorizedSubmit();
599 $this->displayForm( $result );
605 * Validate all the fields, and call the submission callback
606 * function if everything is kosher.
607 * @throws MWException
608 * @return bool|string|array|Status
609 * - Bool true or a good Status object indicates success,
610 * - Bool false indicates no submission was attempted,
611 * - Anything else indicates failure. The value may be a fatal Status
612 * object, an HTML string, or an array of arrays (message keys and
613 * params) or strings (message keys)
615 public function trySubmit() {
617 $hoistedErrors = Status
::newGood();
618 if ( $this->mValidationErrorMessage
) {
619 foreach ( $this->mValidationErrorMessage
as $error ) {
620 $hoistedErrors->fatal( ...$error );
623 $hoistedErrors->fatal( 'htmlform-invalid-input' );
626 $this->mWasSubmitted
= true;
628 # Check for cancelled submission
629 foreach ( $this->mFlatFields
as $fieldname => $field ) {
630 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
633 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
634 $this->mWasSubmitted
= false;
639 # Check for validation
640 foreach ( $this->mFlatFields
as $fieldname => $field ) {
641 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
644 if ( $field->isHidden( $this->mFieldData
) ) {
647 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
648 if ( $res !== true ) {
650 if ( $res !== false && !$field->canDisplayErrors() ) {
651 if ( is_string( $res ) ) {
652 $hoistedErrors->fatal( 'rawmessage', $res );
654 $hoistedErrors->fatal( $res );
661 return $hoistedErrors;
664 $callback = $this->mSubmitCallback
;
665 if ( !is_callable( $callback ) ) {
666 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
667 'setSubmitCallback() to set one.' );
670 $data = $this->filterDataForSubmit( $this->mFieldData
);
672 $res = call_user_func( $callback, $data, $this );
673 if ( $res === false ) {
674 $this->mWasSubmitted
= false;
681 * Test whether the form was considered to have been submitted or not, i.e.
682 * whether the last call to tryAuthorizedSubmit or trySubmit returned
685 * This will return false until HTMLForm::tryAuthorizedSubmit or
686 * HTMLForm::trySubmit is called.
691 public function wasSubmitted() {
692 return $this->mWasSubmitted
;
696 * Set a callback to a function to do something with the form
697 * once it's been successfully validated.
699 * @param callable $cb The function will be passed the output from
700 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
701 * return as documented for HTMLForm::trySubmit
703 * @return HTMLForm $this for chaining calls (since 1.20)
705 public function setSubmitCallback( $cb ) {
706 $this->mSubmitCallback
= $cb;
712 * Set a message to display on a validation error.
714 * @param array $msg Array of valid inputs to wfMessage()
715 * (so each entry must itself be an array of arguments)
717 * @return HTMLForm $this for chaining calls (since 1.20)
719 public function setValidationErrorMessage( $msg ) {
720 $this->mValidationErrorMessage
= $msg;
726 * Set the introductory message, overwriting any existing message.
728 * @param string $msg Complete text of message to display
730 * @return HTMLForm $this for chaining calls (since 1.20)
732 public function setIntro( $msg ) {
733 $this->setPreText( $msg );
739 * Set the introductory message HTML, overwriting any existing message.
742 * @param string $msg Complete HTML of message to display
744 * @return HTMLForm $this for chaining calls (since 1.20)
746 public function setPreText( $msg ) {
753 * Add HTML to introductory message.
755 * @param string $msg Complete HTML of message to display
757 * @return HTMLForm $this for chaining calls (since 1.20)
759 public function addPreText( $msg ) {
766 * Get the introductory message HTML.
772 public function getPreText() {
777 * Add HTML to the header, inside the form.
779 * @param string $msg Additional HTML to display in header
780 * @param string|null $section The section to add the header to
782 * @return HTMLForm $this for chaining calls (since 1.20)
784 public function addHeaderText( $msg, $section = null ) {
785 if ( $section === null ) {
786 $this->mHeader
.= $msg;
788 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
789 $this->mSectionHeaders
[$section] = '';
791 $this->mSectionHeaders
[$section] .= $msg;
798 * Set header text, inside the form.
801 * @param string $msg Complete HTML of header to display
802 * @param string|null $section The section to add the header to
804 * @return HTMLForm $this for chaining calls (since 1.20)
806 public function setHeaderText( $msg, $section = null ) {
807 if ( $section === null ) {
808 $this->mHeader
= $msg;
810 $this->mSectionHeaders
[$section] = $msg;
819 * @param string|null $section The section to get the header text for
821 * @return string HTML
823 public function getHeaderText( $section = null ) {
824 if ( $section === null ) {
825 return $this->mHeader
;
827 return $this->mSectionHeaders
[$section] ??
'';
832 * Add footer text, inside the form.
834 * @param string $msg Complete text of message to display
835 * @param string|null $section The section to add the footer text to
837 * @return HTMLForm $this for chaining calls (since 1.20)
839 public function addFooterText( $msg, $section = null ) {
840 if ( $section === null ) {
841 $this->mFooter
.= $msg;
843 if ( !isset( $this->mSectionFooters
[$section] ) ) {
844 $this->mSectionFooters
[$section] = '';
846 $this->mSectionFooters
[$section] .= $msg;
853 * Set footer text, inside the form.
856 * @param string $msg Complete text of message to display
857 * @param string|null $section The section to add the footer text to
859 * @return HTMLForm $this for chaining calls (since 1.20)
861 public function setFooterText( $msg, $section = null ) {
862 if ( $section === null ) {
863 $this->mFooter
= $msg;
865 $this->mSectionFooters
[$section] = $msg;
874 * @param string|null $section The section to get the footer text for
878 public function getFooterText( $section = null ) {
879 if ( $section === null ) {
880 return $this->mFooter
;
882 return $this->mSectionFooters
[$section] ??
'';
887 * Add text to the end of the display.
889 * @param string $msg Complete text of message to display
891 * @return HTMLForm $this for chaining calls (since 1.20)
893 public function addPostText( $msg ) {
894 $this->mPost
.= $msg;
900 * Set text at the end of the display.
902 * @param string $msg Complete text of message to display
904 * @return HTMLForm $this for chaining calls (since 1.20)
906 public function setPostText( $msg ) {
913 * Add a hidden field to the output
915 * @param string $name Field name. This will be used exactly as entered
916 * @param string $value Field value
917 * @param array $attribs
919 * @return HTMLForm $this for chaining calls (since 1.20)
921 public function addHiddenField( $name, $value, array $attribs = [] ) {
922 $attribs +
= [ 'name' => $name ];
923 $this->mHiddenFields
[] = [ $value, $attribs ];
929 * Add an array of hidden fields to the output
933 * @param array $fields Associative array of fields to add;
934 * mapping names to their values
936 * @return HTMLForm $this for chaining calls
938 public function addHiddenFields( array $fields ) {
939 foreach ( $fields as $name => $value ) {
940 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
947 * Add a button to the form
949 * @since 1.27 takes an array as shown. Earlier versions accepted
950 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
952 * @note Custom labels ('label', 'label-message', 'label-raw') are not
953 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
954 * they will be served buttons using 'value' as the button label.
955 * @param array $data Data to define the button:
956 * - name: (string) Button name.
957 * - value: (string) Button value.
958 * - label-message: (string, optional) Button label message key to use
959 * instead of 'value'. Overrides 'label' and 'label-raw'.
960 * - label: (string, optional) Button label text to use instead of
961 * 'value'. Overrides 'label-raw'.
962 * - label-raw: (string, optional) Button label HTML to use instead of
964 * - id: (string, optional) DOM id for the button.
965 * - attribs: (array, optional) Additional HTML attributes.
966 * - flags: (string|string[], optional) OOUI flags.
967 * - framed: (boolean=true, optional) OOUI framed attribute.
968 * @return HTMLForm $this for chaining calls (since 1.20)
970 public function addButton( $data ) {
971 if ( !is_array( $data ) ) {
972 $args = func_get_args();
973 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
974 throw new InvalidArgumentException(
975 'Incorrect number of arguments for deprecated calling style'
981 'id' => $args[2] ??
null,
982 'attribs' => $args[3] ??
null,
985 if ( !isset( $data['name'] ) ) {
986 throw new InvalidArgumentException( 'A name is required' );
988 if ( !isset( $data['value'] ) ) {
989 throw new InvalidArgumentException( 'A value is required' );
992 $this->mButtons
[] = $data +
[
1003 * Set the salt for the edit token.
1005 * Only useful when the method is "post".
1008 * @param string|array $salt Salt to use
1009 * @return HTMLForm $this For chaining calls
1011 public function setTokenSalt( $salt ) {
1012 $this->mTokenSalt
= $salt;
1018 * Display the form (sending to the context's OutputPage object), with an
1019 * appropriate error message or stack of messages, and any validation errors, etc.
1021 * @warning You should call prepareForm() before calling this function.
1022 * Moreover, when doing method chaining this should be the very last method
1023 * call just after prepareForm().
1025 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1027 * @return void Nothing, should be last call
1029 public function displayForm( $submitResult ) {
1030 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1034 * Returns the raw HTML generated by the form
1036 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1038 * @return string HTML
1039 * @return-taint escaped
1041 public function getHTML( $submitResult ) {
1042 # For good measure (it is the default)
1043 $this->getOutput()->preventClickjacking();
1044 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1045 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1048 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1049 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1050 . $this->getHeaderText()
1052 . $this->getHiddenFields()
1053 . $this->getButtons()
1054 . $this->getFooterText();
1056 $html = $this->wrapForm( $html );
1058 return '' . $this->mPre
. $html . $this->mPost
;
1062 * Enable collapsible mode, and set whether the form is collapsed by default.
1065 * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
1066 * @return HTMLForm $this for chaining calls
1068 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1069 $this->mCollapsible
= true;
1070 $this->mCollapsed
= $collapsedByDefault;
1075 * Get HTML attributes for the `<form>` tag.
1078 protected function getFormAttributes() {
1079 # Use multipart/form-data
1080 $encType = $this->mUseMultipart
1081 ?
'multipart/form-data'
1082 : 'application/x-www-form-urlencoded';
1085 'class' => 'mw-htmlform',
1086 'action' => $this->getAction(),
1087 'method' => $this->getMethod(),
1088 'enctype' => $encType,
1091 $attribs['id'] = $this->mId
;
1093 if ( is_string( $this->mAutocomplete
) ) {
1094 $attribs['autocomplete'] = $this->mAutocomplete
;
1096 if ( $this->mName
) {
1097 $attribs['name'] = $this->mName
;
1099 if ( $this->needsJSForHtml5FormValidation() ) {
1100 $attribs['novalidate'] = true;
1106 * Wrap the form innards in an actual "<form>" element
1108 * @param string $html HTML contents to wrap.
1110 * @return string Wrapped HTML.
1112 public function wrapForm( $html ) {
1113 # Include a <fieldset> wrapper for style, if requested.
1114 if ( $this->mWrapperLegend
!== false ) {
1115 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1116 $html = Xml
::fieldset( $legend, $html, $this->mWrapperAttributes
);
1119 return Html
::rawElement(
1121 $this->getFormAttributes(),
1127 * Get the hidden fields that should go inside the form.
1128 * @return string HTML.
1130 public function getHiddenFields() {
1132 if ( $this->mFormIdentifier
!== null ) {
1133 $html .= Html
::hidden(
1135 $this->mFormIdentifier
1138 if ( $this->getMethod() === 'post' ) {
1139 $html .= Html
::hidden(
1141 $this->getUser()->getEditToken( $this->mTokenSalt
),
1142 [ 'id' => 'wpEditToken' ]
1144 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1147 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1148 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1149 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1152 foreach ( $this->mHiddenFields
as $data ) {
1153 list( $value, $attribs ) = $data;
1154 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1161 * Get the submit and (potentially) reset buttons.
1162 * @return string HTML.
1164 public function getButtons() {
1166 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1168 if ( $this->mShowSubmit
) {
1171 if ( isset( $this->mSubmitID
) ) {
1172 $attribs['id'] = $this->mSubmitID
;
1175 if ( isset( $this->mSubmitName
) ) {
1176 $attribs['name'] = $this->mSubmitName
;
1179 if ( isset( $this->mSubmitTooltip
) ) {
1180 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1183 $attribs['class'] = [ 'mw-htmlform-submit' ];
1185 if ( $useMediaWikiUIEverywhere ) {
1186 foreach ( $this->mSubmitFlags
as $flag ) {
1187 $attribs['class'][] = 'mw-ui-' . $flag;
1189 $attribs['class'][] = 'mw-ui-button';
1192 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1195 if ( $this->mShowReset
) {
1196 $buttons .= Html
::element(
1200 'value' => $this->msg( 'htmlform-reset' )->text(),
1201 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1206 if ( $this->mShowCancel
) {
1207 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1208 if ( $target instanceof Title
) {
1209 $target = $target->getLocalURL();
1211 $buttons .= Html
::element(
1214 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1217 $this->msg( 'cancel' )->text()
1221 // IE<8 has bugs with <button>, so we'll need to avoid them.
1222 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1224 foreach ( $this->mButtons
as $button ) {
1227 'name' => $button['name'],
1228 'value' => $button['value']
1231 if ( isset( $button['label-message'] ) ) {
1232 $label = $this->getMessage( $button['label-message'] )->parse();
1233 } elseif ( isset( $button['label'] ) ) {
1234 $label = htmlspecialchars( $button['label'] );
1235 } elseif ( isset( $button['label-raw'] ) ) {
1236 $label = $button['label-raw'];
1238 $label = htmlspecialchars( $button['value'] );
1241 if ( $button['attribs'] ) {
1242 $attrs +
= $button['attribs'];
1245 if ( isset( $button['id'] ) ) {
1246 $attrs['id'] = $button['id'];
1249 if ( $useMediaWikiUIEverywhere ) {
1250 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1251 $attrs['class'][] = 'mw-ui-button';
1255 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1257 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1265 return Html
::rawElement( 'span',
1266 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1270 * Get the whole body of the form.
1273 public function getBody() {
1274 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1278 * Returns a formatted list of errors or warnings from the given elements.
1280 * @param string|array|Status $elements The set of errors/warnings to process.
1281 * @param string $elementsType Should warnings or errors be returned. This is meant
1282 * for Status objects, all other valid types are always considered as errors.
1285 public function getErrorsOrWarnings( $elements, $elementsType ) {
1286 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1287 throw new DomainException( $elementsType . ' is not a valid type.' );
1289 $elementstr = false;
1290 if ( $elements instanceof Status
) {
1291 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1292 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1293 if ( $status->isGood() ) {
1296 $elementstr = $this->getOutput()->parseAsInterface(
1297 $status->getWikiText()
1300 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1301 $elementstr = $this->formatErrors( $elements );
1302 } elseif ( $elementsType === 'error' ) {
1303 $elementstr = $elements;
1307 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1312 * Format a stack of error messages into a single HTML string
1314 * @param array $errors Array of message keys/values
1316 * @return string HTML, a "<ul>" list of errors
1318 public function formatErrors( $errors ) {
1321 foreach ( $errors as $error ) {
1322 $errorstr .= Html
::rawElement(
1325 $this->getMessage( $error )->parse()
1329 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1335 * Set the text for the submit button
1337 * @param string $t Plaintext
1339 * @return HTMLForm $this for chaining calls (since 1.20)
1341 public function setSubmitText( $t ) {
1342 $this->mSubmitText
= $t;
1348 * Identify that the submit button in the form has a destructive action
1351 * @return HTMLForm $this for chaining calls (since 1.28)
1353 public function setSubmitDestructive() {
1354 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1360 * Set the text for the submit button to a message
1363 * @param string|Message $msg Message key or Message object
1365 * @return HTMLForm $this for chaining calls (since 1.20)
1367 public function setSubmitTextMsg( $msg ) {
1368 if ( !$msg instanceof Message
) {
1369 $msg = $this->msg( $msg );
1371 $this->setSubmitText( $msg->text() );
1377 * Get the text for the submit button, either customised or a default.
1380 public function getSubmitText() {
1381 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1385 * @param string $name Submit button name
1387 * @return HTMLForm $this for chaining calls (since 1.20)
1389 public function setSubmitName( $name ) {
1390 $this->mSubmitName
= $name;
1396 * @param string $name Tooltip for the submit button
1398 * @return HTMLForm $this for chaining calls (since 1.20)
1400 public function setSubmitTooltip( $name ) {
1401 $this->mSubmitTooltip
= $name;
1407 * Set the id for the submit button.
1411 * @todo FIXME: Integrity of $t is *not* validated
1412 * @return HTMLForm $this for chaining calls (since 1.20)
1414 public function setSubmitID( $t ) {
1415 $this->mSubmitID
= $t;
1421 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1422 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1425 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1426 * was submitted, and not attempt to validate the other ones.
1427 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1428 * HTMLForm to distinguish between the initial page view and a form submission with all
1429 * checkboxes or select options unchecked.
1432 * @param string $ident
1435 public function setFormIdentifier( $ident ) {
1436 $this->mFormIdentifier
= $ident;
1442 * Stop a default submit button being shown for this form. This implies that an
1443 * alternate submit method must be provided manually.
1447 * @param bool $suppressSubmit Set to false to re-enable the button again
1449 * @return HTMLForm $this for chaining calls
1451 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1452 $this->mShowSubmit
= !$suppressSubmit;
1458 * Show a cancel button (or prevent it). The button is not shown by default.
1460 * @return HTMLForm $this for chaining calls
1463 public function showCancel( $show = true ) {
1464 $this->mShowCancel
= $show;
1469 * Sets the target where the user is redirected to after clicking cancel.
1470 * @param Title|string $target Target as a Title object or an URL
1471 * @return HTMLForm $this for chaining calls
1474 public function setCancelTarget( $target ) {
1475 $this->mCancelTarget
= $target;
1480 * Set the id of the \<table\> or outermost \<div\> element.
1484 * @param string $id New value of the id attribute, or "" to remove
1486 * @return HTMLForm $this for chaining calls
1488 public function setTableId( $id ) {
1489 $this->mTableId
= $id;
1495 * @param string $id DOM id for the form
1497 * @return HTMLForm $this for chaining calls (since 1.20)
1499 public function setId( $id ) {
1506 * @param string $name 'name' attribute for the form
1507 * @return HTMLForm $this for chaining calls
1509 public function setName( $name ) {
1510 $this->mName
= $name;
1516 * Prompt the whole form to be wrapped in a "<fieldset>", with
1517 * this text as its "<legend>" element.
1519 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1520 * If true, a wrapper will be displayed, but no legend.
1521 * If a string, a wrapper will be displayed with that string as a legend.
1522 * The string will be escaped before being output (this doesn't support HTML).
1524 * @return HTMLForm $this for chaining calls (since 1.20)
1526 public function setWrapperLegend( $legend ) {
1527 $this->mWrapperLegend
= $legend;
1533 * For internal use only. Use is discouraged, and should only be used where
1534 * support for gadgets/user scripts is warranted.
1535 * @param array $attributes
1537 * @return HTMLForm $this for chaining calls
1539 public function setWrapperAttributes( $attributes ) {
1540 $this->mWrapperAttributes
= $attributes;
1546 * Prompt the whole form to be wrapped in a "<fieldset>", with
1547 * this message as its "<legend>" element.
1550 * @param string|Message $msg Message key or Message object
1552 * @return HTMLForm $this for chaining calls (since 1.20)
1554 public function setWrapperLegendMsg( $msg ) {
1555 if ( !$msg instanceof Message
) {
1556 $msg = $this->msg( $msg );
1558 $this->setWrapperLegend( $msg->text() );
1564 * Set the prefix for various default messages
1565 * @todo Currently only used for the "<fieldset>" legend on forms
1566 * with multiple sections; should be used elsewhere?
1570 * @return HTMLForm $this for chaining calls (since 1.20)
1572 public function setMessagePrefix( $p ) {
1573 $this->mMessagePrefix
= $p;
1579 * Set the title for form submission
1581 * @param Title $t Title of page the form is on/should be posted to
1583 * @return HTMLForm $this for chaining calls (since 1.20)
1585 public function setTitle( $t ) {
1595 public function getTitle() {
1596 return $this->mTitle
=== false
1597 ?
$this->getContext()->getTitle()
1602 * Set the method used to submit the form
1604 * @param string $method
1606 * @return HTMLForm $this for chaining calls (since 1.20)
1608 public function setMethod( $method = 'post' ) {
1609 $this->mMethod
= strtolower( $method );
1615 * @return string Always lowercase
1617 public function getMethod() {
1618 return $this->mMethod
;
1622 * Wraps the given $section into an user-visible fieldset.
1624 * @param string $legend Legend text for the fieldset
1625 * @param string $section The section content in plain Html
1626 * @param array $attributes Additional attributes for the fieldset
1627 * @param bool $isRoot Section is at the root of the tree
1628 * @return string The fieldset's Html
1630 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1631 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1637 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1639 * @param string $sectionName ID attribute of the "<table>" tag for this
1640 * section, ignored if empty.
1641 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1642 * each subsection, ignored if empty.
1643 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1644 * @throws LogicException When called on uninitialized field data, e.g. When
1645 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1650 public function displaySection( $fields,
1652 $fieldsetIDPrefix = '',
1653 &$hasUserVisibleFields = false
1655 if ( $this->mFieldData
=== null ) {
1656 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1657 . 'You probably called displayForm() without calling prepareForm() first.' );
1660 $displayFormat = $this->getDisplayFormat();
1663 $subsectionHtml = '';
1666 // Conveniently, PHP method names are case-insensitive.
1667 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1668 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1670 foreach ( $fields as $key => $value ) {
1671 if ( $value instanceof HTMLFormField
) {
1672 $v = array_key_exists( $key, $this->mFieldData
)
1673 ?
$this->mFieldData
[$key]
1674 : $value->getDefault();
1676 $retval = $value->$getFieldHtmlMethod( $v );
1678 // check, if the form field should be added to
1680 if ( $value->hasVisibleOutput() ) {
1683 $labelValue = trim( $value->getLabel() );
1684 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
1688 $hasUserVisibleFields = true;
1690 } elseif ( is_array( $value ) ) {
1691 $subsectionHasVisibleFields = false;
1693 $this->displaySection( $value,
1695 "$fieldsetIDPrefix$key-",
1696 $subsectionHasVisibleFields );
1699 if ( $subsectionHasVisibleFields === true ) {
1700 // Display the section with various niceties.
1701 $hasUserVisibleFields = true;
1703 $legend = $this->getLegend( $key );
1705 $section = $this->getHeaderText( $key ) .
1707 $this->getFooterText( $key );
1710 if ( $fieldsetIDPrefix ) {
1711 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1713 $subsectionHtml .= $this->wrapFieldSetSection(
1714 $legend, $section, $attributes, $fields === $this->mFieldTree
1717 // Just return the inputs, nothing fancy.
1718 $subsectionHtml .= $section;
1723 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1725 if ( $subsectionHtml ) {
1726 if ( $this->mSubSectionBeforeFields
) {
1727 return $subsectionHtml . "\n" . $html;
1729 return $html . "\n" . $subsectionHtml;
1737 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1738 * @param array $fieldsHtml
1739 * @param string $sectionName
1740 * @param bool $anyFieldHasLabel
1741 * @return string HTML
1743 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1744 if ( !$fieldsHtml ) {
1745 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1746 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1750 $displayFormat = $this->getDisplayFormat();
1751 $html = implode( '', $fieldsHtml );
1753 if ( $displayFormat === 'raw' ) {
1759 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1760 $classes[] = 'mw-htmlform-nolabel';
1764 'class' => implode( ' ', $classes ),
1767 if ( $sectionName ) {
1768 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1771 if ( $displayFormat === 'table' ) {
1772 return Html
::rawElement( 'table',
1774 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1775 } elseif ( $displayFormat === 'inline' ) {
1776 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1778 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1783 * Construct the form fields from the Descriptor array
1785 public function loadData() {
1788 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1789 $request = $this->getRequest();
1790 if ( $field->skipLoadData( $request ) ) {
1792 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1793 $fieldData[$fieldname] = $field->getDefault();
1795 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1800 foreach ( $fieldData as $name => &$value ) {
1801 $field = $this->mFlatFields
[$name];
1802 $value = $field->filter( $value, $this->mFlatFields
);
1805 $this->mFieldData
= $fieldData;
1809 * Stop a reset button being shown for this form
1811 * @param bool $suppressReset Set to false to re-enable the button again
1813 * @return HTMLForm $this for chaining calls (since 1.20)
1815 public function suppressReset( $suppressReset = true ) {
1816 $this->mShowReset
= !$suppressReset;
1822 * Overload this if you want to apply special filtration routines
1823 * to the form as a whole, after it's submitted but before it's
1826 * @param array $data
1830 public function filterDataForSubmit( $data ) {
1835 * Get a string to go in the "<legend>" of a section fieldset.
1836 * Override this if you want something more complicated.
1838 * @param string $key
1840 * @return string Plain text (not HTML-escaped)
1842 public function getLegend( $key ) {
1843 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1847 * Set the value for the action attribute of the form.
1848 * When set to false (which is the default state), the set title is used.
1852 * @param string|bool $action
1854 * @return HTMLForm $this for chaining calls (since 1.20)
1856 public function setAction( $action ) {
1857 $this->mAction
= $action;
1863 * Get the value for the action attribute of the form.
1869 public function getAction() {
1870 // If an action is alredy provided, return it
1871 if ( $this->mAction
!== false ) {
1872 return $this->mAction
;
1875 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1876 // Check whether we are in GET mode and the ArticlePath contains a "?"
1877 // meaning that getLocalURL() would return something like "index.php?title=...".
1878 // As browser remove the query string before submitting GET forms,
1879 // it means that the title would be lost. In such case use wfScript() instead
1880 // and put title in an hidden field (see getHiddenFields()).
1881 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1885 return $this->getTitle()->getLocalURL();
1889 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1890 * When set to null (which is the default state), the attribute get not set.
1894 * @param string|null $autocomplete
1896 * @return HTMLForm $this for chaining calls
1898 public function setAutocomplete( $autocomplete ) {
1899 $this->mAutocomplete
= $autocomplete;
1905 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1906 * name + parameters array) into a Message.
1907 * @param mixed $value
1910 protected function getMessage( $value ) {
1911 return Message
::newFromSpecifier( $value )->setContext( $this );
1915 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1916 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1917 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1918 * agent has JavaScript support, in htmlform.js.
1923 public function needsJSForHtml5FormValidation() {
1924 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1925 if ( $field->needsJSForHtml5FormValidation() ) {