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;
189 protected $mSubmitFlags = [ 'primary', 'progressive' ];
190 protected $mShowCancel = false;
191 protected $mCancelTarget;
193 protected $mSubmitCallback;
194 protected $mValidationErrorMessage;
196 protected $mPre = '';
197 protected $mHeader = '';
198 protected $mFooter = '';
199 protected $mSectionHeaders = [];
200 protected $mSectionFooters = [];
201 protected $mPost = '';
204 protected $mTableId = '';
206 protected $mSubmitID;
207 protected $mSubmitName;
208 protected $mSubmitText;
209 protected $mSubmitTooltip;
211 protected $mFormIdentifier;
213 protected $mMethod = 'post';
214 protected $mWasSubmitted = false;
217 * Form action URL. false means we will use the URL to set Title
221 protected $mAction = false;
224 * Whether the form can be collapsed
228 protected $mCollapsible = false;
231 * Whether the form is collapsed by default
235 protected $mCollapsed = false;
238 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
242 protected $mAutocomplete = null;
244 protected $mUseMultipart = false;
245 protected $mHiddenFields = [];
246 protected $mButtons = [];
248 protected $mWrapperLegend = false;
249 protected $mWrapperAttributes = [];
252 * Salt for the edit token.
255 protected $mTokenSalt = '';
258 * If true, sections that contain both fields and subsections will
259 * render their subsections before their fields.
261 * Subclasses may set this to false to render subsections after fields
264 protected $mSubSectionBeforeFields = true;
267 * Format in which to display form. For viable options,
268 * @see $availableDisplayFormats
271 protected $displayFormat = 'table';
274 * Available formats in which to display the form
277 protected $availableDisplayFormats = [
285 * Available formats in which to display the form
288 protected $availableSubclassDisplayFormats = [
294 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
296 * @param string $displayFormat
297 * @param mixed $arguments,... Additional arguments to pass to the constructor.
300 public static function factory( $displayFormat/*, $arguments...*/ ) {
301 $arguments = func_get_args();
302 array_shift( $arguments );
304 switch ( $displayFormat ) {
306 return new VFormHTMLForm( ...$arguments );
308 return new OOUIHTMLForm( ...$arguments );
310 $form = new self( ...$arguments );
311 $form->setDisplayFormat( $displayFormat );
317 * Build a new HTMLForm from an array of field attributes
319 * @param array $descriptor Array of Field constructs, as described above
320 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
321 * Obviates the need to call $form->setTitle()
322 * @param string $messagePrefix A prefix to go in front of default messages
324 public function __construct( $descriptor, /*IContextSource*/ $context = null,
327 if ( $context instanceof IContextSource
) {
328 $this->setContext( $context );
329 $this->mTitle
= false; // We don't need them to set a title
330 $this->mMessagePrefix
= $messagePrefix;
331 } elseif ( $context === null && $messagePrefix !== '' ) {
332 $this->mMessagePrefix
= $messagePrefix;
333 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
335 // it's actually $messagePrefix
336 $this->mMessagePrefix
= $context;
339 // Evil hack for mobile :(
341 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
342 && $this->displayFormat
=== 'table'
344 $this->displayFormat
= 'div';
347 // Expand out into a tree.
348 $loadedDescriptor = [];
349 $this->mFlatFields
= [];
351 foreach ( $descriptor as $fieldname => $info ) {
352 $section = $info['section'] ??
'';
354 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
355 $this->mUseMultipart
= true;
358 $field = static::loadInputFromParameters( $fieldname, $info, $this );
360 $setSection =& $loadedDescriptor;
362 foreach ( explode( '/', $section ) as $newName ) {
363 if ( !isset( $setSection[$newName] ) ) {
364 $setSection[$newName] = [];
367 $setSection =& $setSection[$newName];
371 $setSection[$fieldname] = $field;
372 $this->mFlatFields
[$fieldname] = $field;
375 $this->mFieldTree
= $loadedDescriptor;
379 * @param string $fieldname
382 public function hasField( $fieldname ) {
383 return isset( $this->mFlatFields
[$fieldname] );
387 * @param string $fieldname
388 * @return HTMLFormField
389 * @throws DomainException on invalid field name
391 public function getField( $fieldname ) {
392 if ( !$this->hasField( $fieldname ) ) {
393 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
395 return $this->mFlatFields
[$fieldname];
399 * Set format in which to display the form
401 * @param string $format The name of the format to use, must be one of
402 * $this->availableDisplayFormats
404 * @throws MWException
406 * @return HTMLForm $this for chaining calls (since 1.20)
408 public function setDisplayFormat( $format ) {
410 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
411 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
413 throw new MWException( 'Cannot change display format after creation, ' .
414 'use HTMLForm::factory() instead' );
417 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
418 throw new MWException( 'Display format must be one of ' .
421 $this->availableDisplayFormats
,
422 $this->availableSubclassDisplayFormats
428 // Evil hack for mobile :(
429 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
433 $this->displayFormat
= $format;
439 * Getter for displayFormat
443 public function getDisplayFormat() {
444 return $this->displayFormat
;
448 * Get the HTMLFormField subclass for this descriptor.
450 * The descriptor can be passed either 'class' which is the name of
451 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
452 * This makes sure the 'class' is always set, and also is returned by
453 * this function for ease.
457 * @param string $fieldname Name of the field
458 * @param array &$descriptor Input Descriptor, as described above
460 * @throws MWException
461 * @return string Name of a HTMLFormField subclass
463 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
464 if ( isset( $descriptor['class'] ) ) {
465 $class = $descriptor['class'];
466 } elseif ( isset( $descriptor['type'] ) ) {
467 $class = static::$typeMappings[$descriptor['type']];
468 $descriptor['class'] = $class;
474 throw new MWException( "Descriptor with no class for $fieldname: "
475 . print_r( $descriptor, true ) );
482 * Initialise a new Object for the field
484 * @param string $fieldname Name of the field
485 * @param array $descriptor Input Descriptor, as described above
486 * @param HTMLForm|null $parent Parent instance of HTMLForm
488 * @throws MWException
489 * @return HTMLFormField Instance of a subclass of HTMLFormField
491 public static function loadInputFromParameters( $fieldname, $descriptor,
492 HTMLForm
$parent = null
494 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
496 $descriptor['fieldname'] = $fieldname;
498 $descriptor['parent'] = $parent;
501 # @todo This will throw a fatal error whenever someone try to use
502 # 'class' to feed a CSS class instead of 'cssclass'. Would be
503 # great to avoid the fatal error and show a nice error.
504 return new $class( $descriptor );
508 * Prepare form for submission.
510 * @warning When doing method chaining, that should be the very last
511 * method call before displayForm().
513 * @throws MWException
514 * @return HTMLForm $this for chaining calls (since 1.20)
516 public function prepareForm() {
517 # Check if we have the info we need
518 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
519 throw new MWException( 'You must call setTitle() on an HTMLForm' );
522 # Load data from the request.
524 $this->mFormIdentifier
=== null ||
525 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
529 $this->mFieldData
= [];
536 * Try submitting, with edit token check first
537 * @return Status|bool
539 public function tryAuthorizedSubmit() {
542 if ( $this->mFormIdentifier
=== null ) {
545 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
549 if ( $this->getMethod() !== 'post' ) {
550 $tokenOkay = true; // no session check needed
551 } elseif ( $this->getRequest()->wasPosted() ) {
552 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
553 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
554 // Session tokens for logged-out users have no security value.
555 // However, if the user gave one, check it in order to give a nice
556 // "session expired" error instead of "permission denied" or such.
557 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
563 if ( $tokenOkay && $identOkay ) {
564 $this->mWasSubmitted
= true;
565 $result = $this->trySubmit();
572 * The here's-one-I-made-earlier option: do the submission if
573 * posted, or display the form with or without funky validation
575 * @return bool|Status Whether submission was successful.
577 public function show() {
578 $this->prepareForm();
580 $result = $this->tryAuthorizedSubmit();
581 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
585 $this->displayForm( $result );
591 * Same as self::show with the difference, that the form will be
592 * added to the output, no matter, if the validation was good or not.
593 * @return bool|Status Whether submission was successful.
595 public function showAlways() {
596 $this->prepareForm();
598 $result = $this->tryAuthorizedSubmit();
600 $this->displayForm( $result );
606 * Validate all the fields, and call the submission callback
607 * function if everything is kosher.
608 * @throws MWException
609 * @return bool|string|array|Status
610 * - Bool true or a good Status object indicates success,
611 * - Bool false indicates no submission was attempted,
612 * - Anything else indicates failure. The value may be a fatal Status
613 * object, an HTML string, or an array of arrays (message keys and
614 * params) or strings (message keys)
616 public function trySubmit() {
618 $hoistedErrors = Status
::newGood();
619 if ( $this->mValidationErrorMessage
) {
620 foreach ( $this->mValidationErrorMessage
as $error ) {
621 $hoistedErrors->fatal( ...$error );
624 $hoistedErrors->fatal( 'htmlform-invalid-input' );
627 $this->mWasSubmitted
= true;
629 # Check for cancelled submission
630 foreach ( $this->mFlatFields
as $fieldname => $field ) {
631 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
634 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
635 $this->mWasSubmitted
= false;
640 # Check for validation
641 foreach ( $this->mFlatFields
as $fieldname => $field ) {
642 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
645 if ( $field->isHidden( $this->mFieldData
) ) {
648 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
649 if ( $res !== true ) {
651 if ( $res !== false && !$field->canDisplayErrors() ) {
652 if ( is_string( $res ) ) {
653 $hoistedErrors->fatal( 'rawmessage', $res );
655 $hoistedErrors->fatal( $res );
662 return $hoistedErrors;
665 $callback = $this->mSubmitCallback
;
666 if ( !is_callable( $callback ) ) {
667 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
668 'setSubmitCallback() to set one.' );
671 $data = $this->filterDataForSubmit( $this->mFieldData
);
673 $res = call_user_func( $callback, $data, $this );
674 if ( $res === false ) {
675 $this->mWasSubmitted
= false;
682 * Test whether the form was considered to have been submitted or not, i.e.
683 * whether the last call to tryAuthorizedSubmit or trySubmit returned
686 * This will return false until HTMLForm::tryAuthorizedSubmit or
687 * HTMLForm::trySubmit is called.
692 public function wasSubmitted() {
693 return $this->mWasSubmitted
;
697 * Set a callback to a function to do something with the form
698 * once it's been successfully validated.
700 * @param callable $cb The function will be passed the output from
701 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
702 * return as documented for HTMLForm::trySubmit
704 * @return HTMLForm $this for chaining calls (since 1.20)
706 public function setSubmitCallback( $cb ) {
707 $this->mSubmitCallback
= $cb;
713 * Set a message to display on a validation error.
715 * @param array $msg Array of valid inputs to wfMessage()
716 * (so each entry must itself be an array of arguments)
718 * @return HTMLForm $this for chaining calls (since 1.20)
720 public function setValidationErrorMessage( $msg ) {
721 $this->mValidationErrorMessage
= $msg;
727 * Set the introductory message, overwriting any existing message.
729 * @param string $msg Complete text of message to display
731 * @return HTMLForm $this for chaining calls (since 1.20)
733 public function setIntro( $msg ) {
734 $this->setPreText( $msg );
740 * Set the introductory message HTML, overwriting any existing message.
743 * @param string $msg Complete HTML of message to display
745 * @return HTMLForm $this for chaining calls (since 1.20)
747 public function setPreText( $msg ) {
754 * Add HTML to introductory message.
756 * @param string $msg Complete HTML of message to display
758 * @return HTMLForm $this for chaining calls (since 1.20)
760 public function addPreText( $msg ) {
767 * Get the introductory message HTML.
773 public function getPreText() {
778 * Add HTML to the header, inside the form.
780 * @param string $msg Additional HTML to display in header
781 * @param string|null $section The section to add the header to
783 * @return HTMLForm $this for chaining calls (since 1.20)
785 public function addHeaderText( $msg, $section = null ) {
786 if ( $section === null ) {
787 $this->mHeader
.= $msg;
789 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
790 $this->mSectionHeaders
[$section] = '';
792 $this->mSectionHeaders
[$section] .= $msg;
799 * Set header text, inside the form.
802 * @param string $msg Complete HTML of header to display
803 * @param string|null $section The section to add the header to
805 * @return HTMLForm $this for chaining calls (since 1.20)
807 public function setHeaderText( $msg, $section = null ) {
808 if ( $section === null ) {
809 $this->mHeader
= $msg;
811 $this->mSectionHeaders
[$section] = $msg;
820 * @param string|null $section The section to get the header text for
822 * @return string HTML
824 public function getHeaderText( $section = null ) {
825 if ( $section === null ) {
826 return $this->mHeader
;
828 return $this->mSectionHeaders
[$section] ??
'';
833 * Add footer text, inside the form.
835 * @param string $msg Complete text of message to display
836 * @param string|null $section The section to add the footer text to
838 * @return HTMLForm $this for chaining calls (since 1.20)
840 public function addFooterText( $msg, $section = null ) {
841 if ( $section === null ) {
842 $this->mFooter
.= $msg;
844 if ( !isset( $this->mSectionFooters
[$section] ) ) {
845 $this->mSectionFooters
[$section] = '';
847 $this->mSectionFooters
[$section] .= $msg;
854 * Set footer text, inside the form.
857 * @param string $msg Complete text of message to display
858 * @param string|null $section The section to add the footer text to
860 * @return HTMLForm $this for chaining calls (since 1.20)
862 public function setFooterText( $msg, $section = null ) {
863 if ( $section === null ) {
864 $this->mFooter
= $msg;
866 $this->mSectionFooters
[$section] = $msg;
875 * @param string|null $section The section to get the footer text for
879 public function getFooterText( $section = null ) {
880 if ( $section === null ) {
881 return $this->mFooter
;
883 return $this->mSectionFooters
[$section] ??
'';
888 * Add text to the end of the display.
890 * @param string $msg Complete text of message to display
892 * @return HTMLForm $this for chaining calls (since 1.20)
894 public function addPostText( $msg ) {
895 $this->mPost
.= $msg;
901 * Set text at the end of the display.
903 * @param string $msg Complete text of message to display
905 * @return HTMLForm $this for chaining calls (since 1.20)
907 public function setPostText( $msg ) {
914 * Add a hidden field to the output
916 * @param string $name Field name. This will be used exactly as entered
917 * @param string $value Field value
918 * @param array $attribs
920 * @return HTMLForm $this for chaining calls (since 1.20)
922 public function addHiddenField( $name, $value, array $attribs = [] ) {
923 $attribs +
= [ 'name' => $name ];
924 $this->mHiddenFields
[] = [ $value, $attribs ];
930 * Add an array of hidden fields to the output
934 * @param array $fields Associative array of fields to add;
935 * mapping names to their values
937 * @return HTMLForm $this for chaining calls
939 public function addHiddenFields( array $fields ) {
940 foreach ( $fields as $name => $value ) {
941 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
948 * Add a button to the form
950 * @since 1.27 takes an array as shown. Earlier versions accepted
951 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
953 * @note Custom labels ('label', 'label-message', 'label-raw') are not
954 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
955 * they will be served buttons using 'value' as the button label.
956 * @param array $data Data to define the button:
957 * - name: (string) Button name.
958 * - value: (string) Button value.
959 * - label-message: (string, optional) Button label message key to use
960 * instead of 'value'. Overrides 'label' and 'label-raw'.
961 * - label: (string, optional) Button label text to use instead of
962 * 'value'. Overrides 'label-raw'.
963 * - label-raw: (string, optional) Button label HTML to use instead of
965 * - id: (string, optional) DOM id for the button.
966 * - attribs: (array, optional) Additional HTML attributes.
967 * - flags: (string|string[], optional) OOUI flags.
968 * - framed: (boolean=true, optional) OOUI framed attribute.
969 * @return HTMLForm $this for chaining calls (since 1.20)
971 public function addButton( $data ) {
972 if ( !is_array( $data ) ) {
973 $args = func_get_args();
974 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
975 throw new InvalidArgumentException(
976 'Incorrect number of arguments for deprecated calling style'
982 'id' => $args[2] ??
null,
983 'attribs' => $args[3] ??
null,
986 if ( !isset( $data['name'] ) ) {
987 throw new InvalidArgumentException( 'A name is required' );
989 if ( !isset( $data['value'] ) ) {
990 throw new InvalidArgumentException( 'A value is required' );
993 $this->mButtons
[] = $data +
[
1004 * Set the salt for the edit token.
1006 * Only useful when the method is "post".
1009 * @param string|array $salt Salt to use
1010 * @return HTMLForm $this For chaining calls
1012 public function setTokenSalt( $salt ) {
1013 $this->mTokenSalt
= $salt;
1019 * Display the form (sending to the context's OutputPage object), with an
1020 * appropriate error message or stack of messages, and any validation errors, etc.
1022 * @warning You should call prepareForm() before calling this function.
1023 * Moreover, when doing method chaining this should be the very last method
1024 * call just after prepareForm().
1026 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1028 * @return void Nothing, should be last call
1030 public function displayForm( $submitResult ) {
1031 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1035 * Returns the raw HTML generated by the form
1037 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1039 * @return string HTML
1040 * @return-taint escaped
1042 public function getHTML( $submitResult ) {
1043 # For good measure (it is the default)
1044 $this->getOutput()->preventClickjacking();
1045 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1046 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1049 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1050 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1051 . $this->getHeaderText()
1053 . $this->getHiddenFields()
1054 . $this->getButtons()
1055 . $this->getFooterText();
1057 $html = $this->wrapForm( $html );
1059 return '' . $this->mPre
. $html . $this->mPost
;
1063 * Enable collapsible mode, and set whether the form is collapsed by default.
1066 * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
1067 * @return HTMLForm $this for chaining calls
1069 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1070 $this->mCollapsible
= true;
1071 $this->mCollapsed
= $collapsedByDefault;
1076 * Get HTML attributes for the `<form>` tag.
1079 protected function getFormAttributes() {
1080 # Use multipart/form-data
1081 $encType = $this->mUseMultipart
1082 ?
'multipart/form-data'
1083 : 'application/x-www-form-urlencoded';
1086 'class' => 'mw-htmlform',
1087 'action' => $this->getAction(),
1088 'method' => $this->getMethod(),
1089 'enctype' => $encType,
1092 $attribs['id'] = $this->mId
;
1094 if ( is_string( $this->mAutocomplete
) ) {
1095 $attribs['autocomplete'] = $this->mAutocomplete
;
1097 if ( $this->mName
) {
1098 $attribs['name'] = $this->mName
;
1100 if ( $this->needsJSForHtml5FormValidation() ) {
1101 $attribs['novalidate'] = true;
1107 * Wrap the form innards in an actual "<form>" element
1109 * @param string $html HTML contents to wrap.
1111 * @return string Wrapped HTML.
1113 public function wrapForm( $html ) {
1114 # Include a <fieldset> wrapper for style, if requested.
1115 if ( $this->mWrapperLegend
!== false ) {
1116 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1117 $html = Xml
::fieldset( $legend, $html, $this->mWrapperAttributes
);
1120 return Html
::rawElement(
1122 $this->getFormAttributes(),
1128 * Get the hidden fields that should go inside the form.
1129 * @return string HTML.
1131 public function getHiddenFields() {
1133 if ( $this->mFormIdentifier
!== null ) {
1134 $html .= Html
::hidden(
1136 $this->mFormIdentifier
1139 if ( $this->getMethod() === 'post' ) {
1140 $html .= Html
::hidden(
1142 $this->getUser()->getEditToken( $this->mTokenSalt
),
1143 [ 'id' => 'wpEditToken' ]
1145 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1148 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1149 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1150 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1153 foreach ( $this->mHiddenFields
as $data ) {
1154 list( $value, $attribs ) = $data;
1155 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1162 * Get the submit and (potentially) reset buttons.
1163 * @return string HTML.
1165 public function getButtons() {
1167 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1169 if ( $this->mShowSubmit
) {
1172 if ( isset( $this->mSubmitID
) ) {
1173 $attribs['id'] = $this->mSubmitID
;
1176 if ( isset( $this->mSubmitName
) ) {
1177 $attribs['name'] = $this->mSubmitName
;
1180 if ( isset( $this->mSubmitTooltip
) ) {
1181 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1184 $attribs['class'] = [ 'mw-htmlform-submit' ];
1186 if ( $useMediaWikiUIEverywhere ) {
1187 foreach ( $this->mSubmitFlags
as $flag ) {
1188 $attribs['class'][] = 'mw-ui-' . $flag;
1190 $attribs['class'][] = 'mw-ui-button';
1193 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1196 if ( $this->mShowReset
) {
1197 $buttons .= Html
::element(
1201 'value' => $this->msg( 'htmlform-reset' )->text(),
1202 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1207 if ( $this->mShowCancel
) {
1208 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1209 if ( $target instanceof Title
) {
1210 $target = $target->getLocalURL();
1212 $buttons .= Html
::element(
1215 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1218 $this->msg( 'cancel' )->text()
1222 // IE<8 has bugs with <button>, so we'll need to avoid them.
1223 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1225 foreach ( $this->mButtons
as $button ) {
1228 'name' => $button['name'],
1229 'value' => $button['value']
1232 if ( isset( $button['label-message'] ) ) {
1233 $label = $this->getMessage( $button['label-message'] )->parse();
1234 } elseif ( isset( $button['label'] ) ) {
1235 $label = htmlspecialchars( $button['label'] );
1236 } elseif ( isset( $button['label-raw'] ) ) {
1237 $label = $button['label-raw'];
1239 $label = htmlspecialchars( $button['value'] );
1242 if ( $button['attribs'] ) {
1243 $attrs +
= $button['attribs'];
1246 if ( isset( $button['id'] ) ) {
1247 $attrs['id'] = $button['id'];
1250 if ( $useMediaWikiUIEverywhere ) {
1251 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1252 $attrs['class'][] = 'mw-ui-button';
1256 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1258 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1266 return Html
::rawElement( 'span',
1267 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1271 * Get the whole body of the form.
1274 public function getBody() {
1275 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1279 * Returns a formatted list of errors or warnings from the given elements.
1281 * @param string|array|Status $elements The set of errors/warnings to process.
1282 * @param string $elementsType Should warnings or errors be returned. This is meant
1283 * for Status objects, all other valid types are always considered as errors.
1286 public function getErrorsOrWarnings( $elements, $elementsType ) {
1287 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1288 throw new DomainException( $elementsType . ' is not a valid type.' );
1290 $elementstr = false;
1291 if ( $elements instanceof Status
) {
1292 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1293 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1294 if ( $status->isGood() ) {
1297 $elementstr = $this->getOutput()->parseAsInterface(
1298 $status->getWikiText()
1301 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1302 $elementstr = $this->formatErrors( $elements );
1303 } elseif ( $elementsType === 'error' ) {
1304 $elementstr = $elements;
1308 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1313 * Format a stack of error messages into a single HTML string
1315 * @param array $errors Array of message keys/values
1317 * @return string HTML, a "<ul>" list of errors
1319 public function formatErrors( $errors ) {
1322 foreach ( $errors as $error ) {
1323 $errorstr .= Html
::rawElement(
1326 $this->getMessage( $error )->parse()
1330 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1336 * Set the text for the submit button
1338 * @param string $t Plaintext
1340 * @return HTMLForm $this for chaining calls (since 1.20)
1342 public function setSubmitText( $t ) {
1343 $this->mSubmitText
= $t;
1349 * Identify that the submit button in the form has a destructive action
1352 * @return HTMLForm $this for chaining calls (since 1.28)
1354 public function setSubmitDestructive() {
1355 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1361 * Set the text for the submit button to a message
1364 * @param string|Message $msg Message key or Message object
1366 * @return HTMLForm $this for chaining calls (since 1.20)
1368 public function setSubmitTextMsg( $msg ) {
1369 if ( !$msg instanceof Message
) {
1370 $msg = $this->msg( $msg );
1372 $this->setSubmitText( $msg->text() );
1378 * Get the text for the submit button, either customised or a default.
1381 public function getSubmitText() {
1382 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1386 * @param string $name Submit button name
1388 * @return HTMLForm $this for chaining calls (since 1.20)
1390 public function setSubmitName( $name ) {
1391 $this->mSubmitName
= $name;
1397 * @param string $name Tooltip for the submit button
1399 * @return HTMLForm $this for chaining calls (since 1.20)
1401 public function setSubmitTooltip( $name ) {
1402 $this->mSubmitTooltip
= $name;
1408 * Set the id for the submit button.
1412 * @todo FIXME: Integrity of $t is *not* validated
1413 * @return HTMLForm $this for chaining calls (since 1.20)
1415 public function setSubmitID( $t ) {
1416 $this->mSubmitID
= $t;
1422 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1423 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1426 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1427 * was submitted, and not attempt to validate the other ones.
1428 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1429 * HTMLForm to distinguish between the initial page view and a form submission with all
1430 * checkboxes or select options unchecked.
1433 * @param string $ident
1436 public function setFormIdentifier( $ident ) {
1437 $this->mFormIdentifier
= $ident;
1443 * Stop a default submit button being shown for this form. This implies that an
1444 * alternate submit method must be provided manually.
1448 * @param bool $suppressSubmit Set to false to re-enable the button again
1450 * @return HTMLForm $this for chaining calls
1452 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1453 $this->mShowSubmit
= !$suppressSubmit;
1459 * Show a cancel button (or prevent it). The button is not shown by default.
1461 * @return HTMLForm $this for chaining calls
1464 public function showCancel( $show = true ) {
1465 $this->mShowCancel
= $show;
1470 * Sets the target where the user is redirected to after clicking cancel.
1471 * @param Title|string $target Target as a Title object or an URL
1472 * @return HTMLForm $this for chaining calls
1475 public function setCancelTarget( $target ) {
1476 $this->mCancelTarget
= $target;
1481 * Set the id of the \<table\> or outermost \<div\> element.
1485 * @param string $id New value of the id attribute, or "" to remove
1487 * @return HTMLForm $this for chaining calls
1489 public function setTableId( $id ) {
1490 $this->mTableId
= $id;
1496 * @param string $id DOM id for the form
1498 * @return HTMLForm $this for chaining calls (since 1.20)
1500 public function setId( $id ) {
1507 * @param string $name 'name' attribute for the form
1508 * @return HTMLForm $this for chaining calls
1510 public function setName( $name ) {
1511 $this->mName
= $name;
1517 * Prompt the whole form to be wrapped in a "<fieldset>", with
1518 * this text as its "<legend>" element.
1520 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1521 * If true, a wrapper will be displayed, but no legend.
1522 * If a string, a wrapper will be displayed with that string as a legend.
1523 * The string will be escaped before being output (this doesn't support HTML).
1525 * @return HTMLForm $this for chaining calls (since 1.20)
1527 public function setWrapperLegend( $legend ) {
1528 $this->mWrapperLegend
= $legend;
1534 * For internal use only. Use is discouraged, and should only be used where
1535 * support for gadgets/user scripts is warranted.
1536 * @param array $attributes
1538 * @return HTMLForm $this for chaining calls
1540 public function setWrapperAttributes( $attributes ) {
1541 $this->mWrapperAttributes
= $attributes;
1547 * Prompt the whole form to be wrapped in a "<fieldset>", with
1548 * this message as its "<legend>" element.
1551 * @param string|Message $msg Message key or Message object
1553 * @return HTMLForm $this for chaining calls (since 1.20)
1555 public function setWrapperLegendMsg( $msg ) {
1556 if ( !$msg instanceof Message
) {
1557 $msg = $this->msg( $msg );
1559 $this->setWrapperLegend( $msg->text() );
1565 * Set the prefix for various default messages
1566 * @todo Currently only used for the "<fieldset>" legend on forms
1567 * with multiple sections; should be used elsewhere?
1571 * @return HTMLForm $this for chaining calls (since 1.20)
1573 public function setMessagePrefix( $p ) {
1574 $this->mMessagePrefix
= $p;
1580 * Set the title for form submission
1582 * @param Title $t Title of page the form is on/should be posted to
1584 * @return HTMLForm $this for chaining calls (since 1.20)
1586 public function setTitle( $t ) {
1596 public function getTitle() {
1597 return $this->mTitle
=== false
1598 ?
$this->getContext()->getTitle()
1603 * Set the method used to submit the form
1605 * @param string $method
1607 * @return HTMLForm $this for chaining calls (since 1.20)
1609 public function setMethod( $method = 'post' ) {
1610 $this->mMethod
= strtolower( $method );
1616 * @return string Always lowercase
1618 public function getMethod() {
1619 return $this->mMethod
;
1623 * Wraps the given $section into an user-visible fieldset.
1625 * @param string $legend Legend text for the fieldset
1626 * @param string $section The section content in plain Html
1627 * @param array $attributes Additional attributes for the fieldset
1628 * @param bool $isRoot Section is at the root of the tree
1629 * @return string The fieldset's Html
1631 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1632 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1638 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1640 * @param string $sectionName ID attribute of the "<table>" tag for this
1641 * section, ignored if empty.
1642 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1643 * each subsection, ignored if empty.
1644 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1645 * @throws LogicException When called on uninitialized field data, e.g. When
1646 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1651 public function displaySection( $fields,
1653 $fieldsetIDPrefix = '',
1654 &$hasUserVisibleFields = false
1656 if ( $this->mFieldData
=== null ) {
1657 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1658 . 'You probably called displayForm() without calling prepareForm() first.' );
1661 $displayFormat = $this->getDisplayFormat();
1664 $subsectionHtml = '';
1667 // Conveniently, PHP method names are case-insensitive.
1668 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1669 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1671 foreach ( $fields as $key => $value ) {
1672 if ( $value instanceof HTMLFormField
) {
1673 $v = array_key_exists( $key, $this->mFieldData
)
1674 ?
$this->mFieldData
[$key]
1675 : $value->getDefault();
1677 $retval = $value->$getFieldHtmlMethod( $v );
1679 // check, if the form field should be added to
1681 if ( $value->hasVisibleOutput() ) {
1684 $labelValue = trim( $value->getLabel() );
1685 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
1689 $hasUserVisibleFields = true;
1691 } elseif ( is_array( $value ) ) {
1692 $subsectionHasVisibleFields = false;
1694 $this->displaySection( $value,
1696 "$fieldsetIDPrefix$key-",
1697 $subsectionHasVisibleFields );
1700 if ( $subsectionHasVisibleFields === true ) {
1701 // Display the section with various niceties.
1702 $hasUserVisibleFields = true;
1704 $legend = $this->getLegend( $key );
1706 $section = $this->getHeaderText( $key ) .
1708 $this->getFooterText( $key );
1711 if ( $fieldsetIDPrefix ) {
1712 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1714 $subsectionHtml .= $this->wrapFieldSetSection(
1715 $legend, $section, $attributes, $fields === $this->mFieldTree
1718 // Just return the inputs, nothing fancy.
1719 $subsectionHtml .= $section;
1724 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1726 if ( $subsectionHtml ) {
1727 if ( $this->mSubSectionBeforeFields
) {
1728 return $subsectionHtml . "\n" . $html;
1730 return $html . "\n" . $subsectionHtml;
1738 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1739 * @param array $fieldsHtml
1740 * @param string $sectionName
1741 * @param bool $anyFieldHasLabel
1742 * @return string HTML
1744 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1745 if ( !$fieldsHtml ) {
1746 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1747 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1751 $displayFormat = $this->getDisplayFormat();
1752 $html = implode( '', $fieldsHtml );
1754 if ( $displayFormat === 'raw' ) {
1760 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1761 $classes[] = 'mw-htmlform-nolabel';
1765 'class' => implode( ' ', $classes ),
1768 if ( $sectionName ) {
1769 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1772 if ( $displayFormat === 'table' ) {
1773 return Html
::rawElement( 'table',
1775 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1776 } elseif ( $displayFormat === 'inline' ) {
1777 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1779 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1784 * Construct the form fields from the Descriptor array
1786 public function loadData() {
1789 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1790 $request = $this->getRequest();
1791 if ( $field->skipLoadData( $request ) ) {
1793 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1794 $fieldData[$fieldname] = $field->getDefault();
1796 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1801 foreach ( $fieldData as $name => &$value ) {
1802 $field = $this->mFlatFields
[$name];
1803 $value = $field->filter( $value, $this->mFlatFields
);
1806 $this->mFieldData
= $fieldData;
1810 * Stop a reset button being shown for this form
1812 * @param bool $suppressReset Set to false to re-enable the button again
1814 * @return HTMLForm $this for chaining calls (since 1.20)
1816 public function suppressReset( $suppressReset = true ) {
1817 $this->mShowReset
= !$suppressReset;
1823 * Overload this if you want to apply special filtration routines
1824 * to the form as a whole, after it's submitted but before it's
1827 * @param array $data
1831 public function filterDataForSubmit( $data ) {
1836 * Get a string to go in the "<legend>" of a section fieldset.
1837 * Override this if you want something more complicated.
1839 * @param string $key
1841 * @return string Plain text (not HTML-escaped)
1843 public function getLegend( $key ) {
1844 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1848 * Set the value for the action attribute of the form.
1849 * When set to false (which is the default state), the set title is used.
1853 * @param string|bool $action
1855 * @return HTMLForm $this for chaining calls (since 1.20)
1857 public function setAction( $action ) {
1858 $this->mAction
= $action;
1864 * Get the value for the action attribute of the form.
1870 public function getAction() {
1871 // If an action is alredy provided, return it
1872 if ( $this->mAction
!== false ) {
1873 return $this->mAction
;
1876 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1877 // Check whether we are in GET mode and the ArticlePath contains a "?"
1878 // meaning that getLocalURL() would return something like "index.php?title=...".
1879 // As browser remove the query string before submitting GET forms,
1880 // it means that the title would be lost. In such case use wfScript() instead
1881 // and put title in an hidden field (see getHiddenFields()).
1882 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1886 return $this->getTitle()->getLocalURL();
1890 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1891 * When set to null (which is the default state), the attribute get not set.
1895 * @param string|null $autocomplete
1897 * @return HTMLForm $this for chaining calls
1899 public function setAutocomplete( $autocomplete ) {
1900 $this->mAutocomplete
= $autocomplete;
1906 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1907 * name + parameters array) into a Message.
1908 * @param mixed $value
1911 protected function getMessage( $value ) {
1912 return Message
::newFromSpecifier( $value )->setContext( $this );
1916 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1917 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1918 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1919 * agent has JavaScript support, in htmlform.js.
1924 public function needsJSForHtml5FormValidation() {
1925 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1926 if ( $field->needsJSForHtml5FormValidation() ) {