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
24 use Wikimedia\ObjectFactory
;
27 * Object handling generic submission, CSRF protection, layout and
28 * other logic for UI forms. in a reusable manner.
30 * In order to generate the form, the HTMLForm object takes an array
31 * structure detailing the form fields available. Each element of the
32 * array is a basic property-list, including the type of field, the
33 * label it is to be given in the form, callbacks for validation and
34 * 'filtering', and other pertinent information.
36 * Field types are implemented as subclasses of the generic HTMLFormField
37 * object, and typically implement at least getInputHTML, which generates
38 * the HTML for the input field to be placed in the table.
40 * You can find extensive documentation on the www.mediawiki.org wiki:
41 * - https://www.mediawiki.org/wiki/HTMLForm
42 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
44 * The constructor input is an associative array of $fieldname => $info,
45 * where $info is an Associative Array with any of the following:
47 * 'class' -- the subclass of HTMLFormField that will be used
48 * to create the object. *NOT* the CSS class!
49 * 'type' -- roughly translates into the <select> type attribute.
50 * if 'class' is not specified, this is used as a map
51 * through HTMLForm::$typeMappings to get the class name.
52 * 'default' -- default value when the form is displayed
53 * 'nodata' -- if set (to any value, which casts to true), the data
54 * for this field will not be loaded from the actual request. Instead,
55 * always the default data is set as the value of this field.
56 * 'id' -- HTML id attribute
57 * 'cssclass' -- CSS class
58 * 'csshelpclass' -- CSS class used to style help text
59 * 'dir' -- Direction of the element.
60 * 'options' -- associative array mapping raw text labels to values.
61 * Some field types support multi-level arrays.
62 * Overwrites 'options-message'.
63 * 'options-messages' -- associative array mapping message keys to values.
64 * Some field types support multi-level arrays.
65 * Overwrites 'options' and 'options-message'.
66 * 'options-message' -- message key or object to be parsed to extract the list of
67 * options (like 'ipbreason-dropdown').
68 * 'label-message' -- message key or object for a message to use as the label.
69 * can be an array of msg key and then parameters to
71 * 'label' -- alternatively, a raw text message. Overridden by
73 * 'help' -- message text for a message to use as a help text.
74 * 'help-message' -- message key or object for a message to use as a help text.
75 * can be an array of msg key and then parameters to
77 * Overwrites 'help-messages' and 'help'.
78 * 'help-messages' -- array of message keys/objects. As above, each item can
79 * be an array of msg key and then parameters.
81 * 'help-inline' -- Whether help text (defined using options above) will be shown
82 * inline after the input field, rather than in a popup.
83 * Defaults to true. Only used by OOUI form fields.
84 * 'required' -- passed through to the object, indicating that it
85 * is a required field.
86 * 'size' -- the length of text fields
87 * 'filter-callback' -- a function name to give you the chance to
88 * massage the inputted value before it's processed.
89 * @see HTMLFormField::filter()
90 * 'validation-callback' -- a function name to give you the chance
91 * to impose extra validation on the field input.
92 * @see HTMLFormField::validate()
93 * 'name' -- By default, the 'name' attribute of the input field
94 * is "wp{$fieldname}". If you want a different name
95 * (eg one without the "wp" prefix), specify it here and
96 * it will be used without modification.
97 * 'hide-if' -- expression given as an array stating when the field
98 * should be hidden. The first array value has to be the
99 * expression's logic operator. Supported expressions:
101 * [ 'NOT', array $expression ]
102 * To hide a field if a given expression is not true.
104 * [ '===', string $fieldName, string $value ]
105 * To hide a field if another field identified by
106 * $field has the value $value.
108 * [ '!==', string $fieldName, string $value ]
109 * Same as [ 'NOT', [ '===', $fieldName, $value ]
110 * 'OR', 'AND', 'NOR', 'NAND'
111 * [ 'XXX', array $expression1, ..., array $expressionN ]
112 * To hide a field if one or more (OR), all (AND),
113 * neither (NOR) or not all (NAND) given expressions
114 * are evaluated as true.
115 * The expressions will be given to a JavaScript frontend
116 * module which will continually update the field's
119 * Since 1.20, you can chain mutators to ease the form generation:
122 * $form = new HTMLForm( $someFields );
123 * $form->setMethod( 'get' )
124 * ->setWrapperLegendMsg( 'message-key' )
126 * ->displayForm( '' );
128 * Note that you will have prepareForm and displayForm at the end. Other
129 * methods call done after that would simply not be part of the form :(
131 * @todo Document 'section' / 'subsection' stuff
133 class HTMLForm
extends ContextSource
{
134 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
135 public static $typeMappings = [
136 'api' => HTMLApiField
::class,
137 'text' => HTMLTextField
::class,
138 'textwithbutton' => HTMLTextFieldWithButton
::class,
139 'textarea' => HTMLTextAreaField
::class,
140 'select' => HTMLSelectField
::class,
141 'combobox' => HTMLComboboxField
::class,
142 'radio' => HTMLRadioField
::class,
143 'multiselect' => HTMLMultiSelectField
::class,
144 'limitselect' => HTMLSelectLimitField
::class,
145 'check' => HTMLCheckField
::class,
146 'toggle' => HTMLCheckField
::class,
147 'int' => HTMLIntField
::class,
148 'float' => HTMLFloatField
::class,
149 'info' => HTMLInfoField
::class,
150 'selectorother' => HTMLSelectOrOtherField
::class,
151 'selectandother' => HTMLSelectAndOtherField
::class,
152 'namespaceselect' => HTMLSelectNamespace
::class,
153 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton
::class,
154 'tagfilter' => HTMLTagFilter
::class,
155 'sizefilter' => HTMLSizeFilterField
::class,
156 'submit' => HTMLSubmitField
::class,
157 'hidden' => HTMLHiddenField
::class,
158 'edittools' => HTMLEditTools
::class,
159 'checkmatrix' => HTMLCheckMatrix
::class,
160 'cloner' => HTMLFormFieldCloner
::class,
161 'autocompleteselect' => HTMLAutoCompleteSelectField
::class,
162 'language' => HTMLSelectLanguageField
::class,
163 'date' => HTMLDateTimeField
::class,
164 'time' => HTMLDateTimeField
::class,
165 'datetime' => HTMLDateTimeField
::class,
166 'expiry' => HTMLExpiryField
::class,
167 // HTMLTextField will output the correct type="" attribute automagically.
168 // There are about four zillion other HTML5 input types, like range, but
169 // we don't use those at the moment, so no point in adding all of them.
170 'email' => HTMLTextField
::class,
171 'password' => HTMLTextField
::class,
172 'url' => HTMLTextField
::class,
173 'title' => HTMLTitleTextField
::class,
174 'user' => HTMLUserTextField
::class,
175 'usersmultiselect' => HTMLUsersMultiselectField
::class,
176 'titlesmultiselect' => HTMLTitlesMultiselectField
::class,
181 protected $mMessagePrefix;
183 /** @var HTMLFormField[] */
184 protected $mFlatFields;
186 protected $mFieldTree;
187 protected $mShowReset = false;
188 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 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
228 protected $mAutocomplete = null;
230 protected $mUseMultipart = false;
231 protected $mHiddenFields = [];
232 protected $mButtons = [];
234 protected $mWrapperLegend = false;
237 * Salt for the edit token.
240 protected $mTokenSalt = '';
243 * If true, sections that contain both fields and subsections will
244 * render their subsections before their fields.
246 * Subclasses may set this to false to render subsections after fields
249 protected $mSubSectionBeforeFields = true;
252 * Format in which to display form. For viable options,
253 * @see $availableDisplayFormats
256 protected $displayFormat = 'table';
259 * Available formats in which to display the form
262 protected $availableDisplayFormats = [
270 * Available formats in which to display the form
273 protected $availableSubclassDisplayFormats = [
279 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
281 * @param string $displayFormat
282 * @param mixed $arguments,... Additional arguments to pass to the constructor.
285 public static function factory( $displayFormat/*, $arguments...*/ ) {
286 $arguments = func_get_args();
287 array_shift( $arguments );
289 switch ( $displayFormat ) {
291 return ObjectFactory
::constructClassInstance( VFormHTMLForm
::class, $arguments );
293 return ObjectFactory
::constructClassInstance( OOUIHTMLForm
::class, $arguments );
295 /** @var HTMLForm $form */
296 $form = ObjectFactory
::constructClassInstance( self
::class, $arguments );
297 $form->setDisplayFormat( $displayFormat );
303 * Build a new HTMLForm from an array of field attributes
305 * @param array $descriptor Array of Field constructs, as described above
306 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
307 * Obviates the need to call $form->setTitle()
308 * @param string $messagePrefix A prefix to go in front of default messages
310 public function __construct( $descriptor, /*IContextSource*/ $context = null,
313 if ( $context instanceof IContextSource
) {
314 $this->setContext( $context );
315 $this->mTitle
= false; // We don't need them to set a title
316 $this->mMessagePrefix
= $messagePrefix;
317 } elseif ( $context === null && $messagePrefix !== '' ) {
318 $this->mMessagePrefix
= $messagePrefix;
319 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
321 // it's actually $messagePrefix
322 $this->mMessagePrefix
= $context;
325 // Evil hack for mobile :(
327 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
328 && $this->displayFormat
=== 'table'
330 $this->displayFormat
= 'div';
333 // Expand out into a tree.
334 $loadedDescriptor = [];
335 $this->mFlatFields
= [];
337 foreach ( $descriptor as $fieldname => $info ) {
338 $section = $info['section'] ??
'';
340 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
341 $this->mUseMultipart
= true;
344 $field = static::loadInputFromParameters( $fieldname, $info, $this );
346 $setSection =& $loadedDescriptor;
348 foreach ( explode( '/', $section ) as $newName ) {
349 if ( !isset( $setSection[$newName] ) ) {
350 $setSection[$newName] = [];
353 $setSection =& $setSection[$newName];
357 $setSection[$fieldname] = $field;
358 $this->mFlatFields
[$fieldname] = $field;
361 $this->mFieldTree
= $loadedDescriptor;
365 * @param string $fieldname
368 public function hasField( $fieldname ) {
369 return isset( $this->mFlatFields
[$fieldname] );
373 * @param string $fieldname
374 * @return HTMLFormField
375 * @throws DomainException on invalid field name
377 public function getField( $fieldname ) {
378 if ( !$this->hasField( $fieldname ) ) {
379 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
381 return $this->mFlatFields
[$fieldname];
385 * Set format in which to display the form
387 * @param string $format The name of the format to use, must be one of
388 * $this->availableDisplayFormats
390 * @throws MWException
392 * @return HTMLForm $this for chaining calls (since 1.20)
394 public function setDisplayFormat( $format ) {
396 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
397 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
399 throw new MWException( 'Cannot change display format after creation, ' .
400 'use HTMLForm::factory() instead' );
403 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
404 throw new MWException( 'Display format must be one of ' .
407 $this->availableDisplayFormats
,
408 $this->availableSubclassDisplayFormats
414 // Evil hack for mobile :(
415 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
419 $this->displayFormat
= $format;
425 * Getter for displayFormat
429 public function getDisplayFormat() {
430 return $this->displayFormat
;
434 * Get the HTMLFormField subclass for this descriptor.
436 * The descriptor can be passed either 'class' which is the name of
437 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
438 * This makes sure the 'class' is always set, and also is returned by
439 * this function for ease.
443 * @param string $fieldname Name of the field
444 * @param array &$descriptor Input Descriptor, as described above
446 * @throws MWException
447 * @return string Name of a HTMLFormField subclass
449 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
450 if ( isset( $descriptor['class'] ) ) {
451 $class = $descriptor['class'];
452 } elseif ( isset( $descriptor['type'] ) ) {
453 $class = static::$typeMappings[$descriptor['type']];
454 $descriptor['class'] = $class;
460 throw new MWException( "Descriptor with no class for $fieldname: "
461 . print_r( $descriptor, true ) );
468 * Initialise a new Object for the field
470 * @param string $fieldname Name of the field
471 * @param array $descriptor Input Descriptor, as described above
472 * @param HTMLForm|null $parent Parent instance of HTMLForm
474 * @throws MWException
475 * @return HTMLFormField Instance of a subclass of HTMLFormField
477 public static function loadInputFromParameters( $fieldname, $descriptor,
478 HTMLForm
$parent = null
480 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
482 $descriptor['fieldname'] = $fieldname;
484 $descriptor['parent'] = $parent;
487 # @todo This will throw a fatal error whenever someone try to use
488 # 'class' to feed a CSS class instead of 'cssclass'. Would be
489 # great to avoid the fatal error and show a nice error.
490 return new $class( $descriptor );
494 * Prepare form for submission.
496 * @warning When doing method chaining, that should be the very last
497 * method call before displayForm().
499 * @throws MWException
500 * @return HTMLForm $this for chaining calls (since 1.20)
502 public function prepareForm() {
503 # Check if we have the info we need
504 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
505 throw new MWException( 'You must call setTitle() on an HTMLForm' );
508 # Load data from the request.
510 $this->mFormIdentifier
=== null ||
511 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
515 $this->mFieldData
= [];
522 * Try submitting, with edit token check first
523 * @return Status|bool
525 public function tryAuthorizedSubmit() {
529 if ( $this->mFormIdentifier
=== null ) {
532 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
536 if ( $this->getMethod() !== 'post' ) {
537 $tokenOkay = true; // no session check needed
538 } elseif ( $this->getRequest()->wasPosted() ) {
539 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
540 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
541 // Session tokens for logged-out users have no security value.
542 // However, if the user gave one, check it in order to give a nice
543 // "session expired" error instead of "permission denied" or such.
544 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
550 if ( $tokenOkay && $identOkay ) {
551 $this->mWasSubmitted
= true;
552 $result = $this->trySubmit();
559 * The here's-one-I-made-earlier option: do the submission if
560 * posted, or display the form with or without funky validation
562 * @return bool|Status Whether submission was successful.
564 public function show() {
565 $this->prepareForm();
567 $result = $this->tryAuthorizedSubmit();
568 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
572 $this->displayForm( $result );
578 * Same as self::show with the difference, that the form will be
579 * added to the output, no matter, if the validation was good or not.
580 * @return bool|Status Whether submission was successful.
582 public function showAlways() {
583 $this->prepareForm();
585 $result = $this->tryAuthorizedSubmit();
587 $this->displayForm( $result );
593 * Validate all the fields, and call the submission callback
594 * function if everything is kosher.
595 * @throws MWException
596 * @return bool|string|array|Status
597 * - Bool true or a good Status object indicates success,
598 * - Bool false indicates no submission was attempted,
599 * - Anything else indicates failure. The value may be a fatal Status
600 * object, an HTML string, or an array of arrays (message keys and
601 * params) or strings (message keys)
603 public function trySubmit() {
605 $hoistedErrors = Status
::newGood();
606 if ( $this->mValidationErrorMessage
) {
607 foreach ( (array)$this->mValidationErrorMessage
as $error ) {
608 $hoistedErrors->fatal( ...$error );
611 $hoistedErrors->fatal( 'htmlform-invalid-input' );
614 $this->mWasSubmitted
= true;
616 # Check for cancelled submission
617 foreach ( $this->mFlatFields
as $fieldname => $field ) {
618 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
621 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
622 $this->mWasSubmitted
= false;
627 # Check for validation
628 foreach ( $this->mFlatFields
as $fieldname => $field ) {
629 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
632 if ( $field->isHidden( $this->mFieldData
) ) {
635 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
636 if ( $res !== true ) {
638 if ( $res !== false && !$field->canDisplayErrors() ) {
639 if ( is_string( $res ) ) {
640 $hoistedErrors->fatal( 'rawmessage', $res );
642 $hoistedErrors->fatal( $res );
649 return $hoistedErrors;
652 $callback = $this->mSubmitCallback
;
653 if ( !is_callable( $callback ) ) {
654 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
655 'setSubmitCallback() to set one.' );
658 $data = $this->filterDataForSubmit( $this->mFieldData
);
660 $res = call_user_func( $callback, $data, $this );
661 if ( $res === false ) {
662 $this->mWasSubmitted
= false;
669 * Test whether the form was considered to have been submitted or not, i.e.
670 * whether the last call to tryAuthorizedSubmit or trySubmit returned
673 * This will return false until HTMLForm::tryAuthorizedSubmit or
674 * HTMLForm::trySubmit is called.
679 public function wasSubmitted() {
680 return $this->mWasSubmitted
;
684 * Set a callback to a function to do something with the form
685 * once it's been successfully validated.
687 * @param callable $cb The function will be passed the output from
688 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
689 * return as documented for HTMLForm::trySubmit
691 * @return HTMLForm $this for chaining calls (since 1.20)
693 public function setSubmitCallback( $cb ) {
694 $this->mSubmitCallback
= $cb;
700 * Set a message to display on a validation error.
702 * @param string|array $msg String or Array of valid inputs to wfMessage()
703 * (so each entry can be either a String or Array)
705 * @return HTMLForm $this for chaining calls (since 1.20)
707 public function setValidationErrorMessage( $msg ) {
708 $this->mValidationErrorMessage
= $msg;
714 * Set the introductory message, overwriting any existing message.
716 * @param string $msg Complete text of message to display
718 * @return HTMLForm $this for chaining calls (since 1.20)
720 public function setIntro( $msg ) {
721 $this->setPreText( $msg );
727 * Set the introductory message HTML, overwriting any existing message.
730 * @param string $msg Complete HTML of message to display
732 * @return HTMLForm $this for chaining calls (since 1.20)
734 public function setPreText( $msg ) {
741 * Add HTML to introductory message.
743 * @param string $msg Complete HTML of message to display
745 * @return HTMLForm $this for chaining calls (since 1.20)
747 public function addPreText( $msg ) {
754 * Get the introductory message HTML.
760 public function getPreText() {
765 * Add HTML to the header, inside the form.
767 * @param string $msg Additional HTML to display in header
768 * @param string|null $section The section to add the header to
770 * @return HTMLForm $this for chaining calls (since 1.20)
772 public function addHeaderText( $msg, $section = null ) {
773 if ( $section === null ) {
774 $this->mHeader
.= $msg;
776 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
777 $this->mSectionHeaders
[$section] = '';
779 $this->mSectionHeaders
[$section] .= $msg;
786 * Set header text, inside the form.
789 * @param string $msg Complete HTML of header to display
790 * @param string|null $section The section to add the header to
792 * @return HTMLForm $this for chaining calls (since 1.20)
794 public function setHeaderText( $msg, $section = null ) {
795 if ( $section === null ) {
796 $this->mHeader
= $msg;
798 $this->mSectionHeaders
[$section] = $msg;
807 * @param string|null $section The section to get the header text for
809 * @return string HTML
811 public function getHeaderText( $section = null ) {
812 if ( $section === null ) {
813 return $this->mHeader
;
815 return $this->mSectionHeaders
[$section] ??
'';
820 * Add footer text, inside the form.
822 * @param string $msg Complete text of message to display
823 * @param string|null $section The section to add the footer text to
825 * @return HTMLForm $this for chaining calls (since 1.20)
827 public function addFooterText( $msg, $section = null ) {
828 if ( $section === null ) {
829 $this->mFooter
.= $msg;
831 if ( !isset( $this->mSectionFooters
[$section] ) ) {
832 $this->mSectionFooters
[$section] = '';
834 $this->mSectionFooters
[$section] .= $msg;
841 * Set footer text, inside the form.
844 * @param string $msg Complete text of message to display
845 * @param string|null $section The section to add the footer text to
847 * @return HTMLForm $this for chaining calls (since 1.20)
849 public function setFooterText( $msg, $section = null ) {
850 if ( $section === null ) {
851 $this->mFooter
= $msg;
853 $this->mSectionFooters
[$section] = $msg;
862 * @param string|null $section The section to get the footer text for
866 public function getFooterText( $section = null ) {
867 if ( $section === null ) {
868 return $this->mFooter
;
870 return $this->mSectionFooters
[$section] ??
'';
875 * Add text to the end of the display.
877 * @param string $msg Complete text of message to display
879 * @return HTMLForm $this for chaining calls (since 1.20)
881 public function addPostText( $msg ) {
882 $this->mPost
.= $msg;
888 * Set text at 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 setPostText( $msg ) {
901 * Add a hidden field to the output
903 * @param string $name Field name. This will be used exactly as entered
904 * @param string $value Field value
905 * @param array $attribs
907 * @return HTMLForm $this for chaining calls (since 1.20)
909 public function addHiddenField( $name, $value, array $attribs = [] ) {
910 $attribs +
= [ 'name' => $name ];
911 $this->mHiddenFields
[] = [ $value, $attribs ];
917 * Add an array of hidden fields to the output
921 * @param array $fields Associative array of fields to add;
922 * mapping names to their values
924 * @return HTMLForm $this for chaining calls
926 public function addHiddenFields( array $fields ) {
927 foreach ( $fields as $name => $value ) {
928 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
935 * Add a button to the form
937 * @since 1.27 takes an array as shown. Earlier versions accepted
938 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
940 * @note Custom labels ('label', 'label-message', 'label-raw') are not
941 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
942 * they will be served buttons using 'value' as the button label.
943 * @param array $data Data to define the button:
944 * - name: (string) Button name.
945 * - value: (string) Button value.
946 * - label-message: (string, optional) Button label message key to use
947 * instead of 'value'. Overrides 'label' and 'label-raw'.
948 * - label: (string, optional) Button label text to use instead of
949 * 'value'. Overrides 'label-raw'.
950 * - label-raw: (string, optional) Button label HTML to use instead of
952 * - id: (string, optional) DOM id for the button.
953 * - attribs: (array, optional) Additional HTML attributes.
954 * - flags: (string|string[], optional) OOUI flags.
955 * - framed: (boolean=true, optional) OOUI framed attribute.
956 * @return HTMLForm $this for chaining calls (since 1.20)
958 public function addButton( $data ) {
959 if ( !is_array( $data ) ) {
960 $args = func_get_args();
961 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
962 throw new InvalidArgumentException(
963 'Incorrect number of arguments for deprecated calling style'
969 'id' => $args[2] ??
null,
970 'attribs' => $args[3] ??
null,
973 if ( !isset( $data['name'] ) ) {
974 throw new InvalidArgumentException( 'A name is required' );
976 if ( !isset( $data['value'] ) ) {
977 throw new InvalidArgumentException( 'A value is required' );
980 $this->mButtons
[] = $data +
[
991 * Set the salt for the edit token.
993 * Only useful when the method is "post".
996 * @param string|array $salt Salt to use
997 * @return HTMLForm $this For chaining calls
999 public function setTokenSalt( $salt ) {
1000 $this->mTokenSalt
= $salt;
1006 * Display the form (sending to the context's OutputPage object), with an
1007 * appropriate error message or stack of messages, and any validation errors, etc.
1009 * @warning You should call prepareForm() before calling this function.
1010 * Moreover, when doing method chaining this should be the very last method
1011 * call just after prepareForm().
1013 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1015 * @return void Nothing, should be last call
1017 public function displayForm( $submitResult ) {
1018 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1022 * Returns the raw HTML generated by the form
1024 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1026 * @return string HTML
1027 * @return-taint escaped
1029 public function getHTML( $submitResult ) {
1030 # For good measure (it is the default)
1031 $this->getOutput()->preventClickjacking();
1032 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1033 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1036 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1037 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1038 . $this->getHeaderText()
1040 . $this->getHiddenFields()
1041 . $this->getButtons()
1042 . $this->getFooterText();
1044 $html = $this->wrapForm( $html );
1046 return '' . $this->mPre
. $html . $this->mPost
;
1050 * Get HTML attributes for the `<form>` tag.
1053 protected function getFormAttributes() {
1054 # Use multipart/form-data
1055 $encType = $this->mUseMultipart
1056 ?
'multipart/form-data'
1057 : 'application/x-www-form-urlencoded';
1060 'class' => 'mw-htmlform',
1061 'action' => $this->getAction(),
1062 'method' => $this->getMethod(),
1063 'enctype' => $encType,
1066 $attribs['id'] = $this->mId
;
1068 if ( is_string( $this->mAutocomplete
) ) {
1069 $attribs['autocomplete'] = $this->mAutocomplete
;
1071 if ( $this->mName
) {
1072 $attribs['name'] = $this->mName
;
1074 if ( $this->needsJSForHtml5FormValidation() ) {
1075 $attribs['novalidate'] = true;
1081 * Wrap the form innards in an actual "<form>" element
1083 * @param string $html HTML contents to wrap.
1085 * @return string Wrapped HTML.
1087 public function wrapForm( $html ) {
1088 # Include a <fieldset> wrapper for style, if requested.
1089 if ( $this->mWrapperLegend
!== false ) {
1090 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1091 $html = Xml
::fieldset( $legend, $html );
1094 return Html
::rawElement(
1096 $this->getFormAttributes(),
1102 * Get the hidden fields that should go inside the form.
1103 * @return string HTML.
1105 public function getHiddenFields() {
1107 if ( $this->mFormIdentifier
!== null ) {
1108 $html .= Html
::hidden(
1110 $this->mFormIdentifier
1113 if ( $this->getMethod() === 'post' ) {
1114 $html .= Html
::hidden(
1116 $this->getUser()->getEditToken( $this->mTokenSalt
),
1117 [ 'id' => 'wpEditToken' ]
1119 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1122 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1123 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1124 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1127 foreach ( $this->mHiddenFields
as $data ) {
1128 list( $value, $attribs ) = $data;
1129 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1136 * Get the submit and (potentially) reset buttons.
1137 * @return string HTML.
1139 public function getButtons() {
1141 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1143 if ( $this->mShowSubmit
) {
1146 if ( isset( $this->mSubmitID
) ) {
1147 $attribs['id'] = $this->mSubmitID
;
1150 if ( isset( $this->mSubmitName
) ) {
1151 $attribs['name'] = $this->mSubmitName
;
1154 if ( isset( $this->mSubmitTooltip
) ) {
1155 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1158 $attribs['class'] = [ 'mw-htmlform-submit' ];
1160 if ( $useMediaWikiUIEverywhere ) {
1161 foreach ( $this->mSubmitFlags
as $flag ) {
1162 $attribs['class'][] = 'mw-ui-' . $flag;
1164 $attribs['class'][] = 'mw-ui-button';
1167 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1170 if ( $this->mShowReset
) {
1171 $buttons .= Html
::element(
1175 'value' => $this->msg( 'htmlform-reset' )->text(),
1176 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1181 if ( $this->mShowCancel
) {
1182 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1183 if ( $target instanceof Title
) {
1184 $target = $target->getLocalURL();
1186 $buttons .= Html
::element(
1189 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1192 $this->msg( 'cancel' )->text()
1196 // IE<8 has bugs with <button>, so we'll need to avoid them.
1197 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1199 foreach ( $this->mButtons
as $button ) {
1202 'name' => $button['name'],
1203 'value' => $button['value']
1206 if ( isset( $button['label-message'] ) ) {
1207 $label = $this->getMessage( $button['label-message'] )->parse();
1208 } elseif ( isset( $button['label'] ) ) {
1209 $label = htmlspecialchars( $button['label'] );
1210 } elseif ( isset( $button['label-raw'] ) ) {
1211 $label = $button['label-raw'];
1213 $label = htmlspecialchars( $button['value'] );
1216 if ( $button['attribs'] ) {
1217 $attrs +
= $button['attribs'];
1220 if ( isset( $button['id'] ) ) {
1221 $attrs['id'] = $button['id'];
1224 if ( $useMediaWikiUIEverywhere ) {
1225 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1226 $attrs['class'][] = 'mw-ui-button';
1230 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1232 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1240 return Html
::rawElement( 'span',
1241 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1245 * Get the whole body of the form.
1248 public function getBody() {
1249 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1253 * Format and display an error message stack.
1255 * @param string|array|Status $errors
1257 * @deprecated since 1.28, use getErrorsOrWarnings() instead
1261 public function getErrors( $errors ) {
1262 wfDeprecated( __METHOD__
);
1263 return $this->getErrorsOrWarnings( $errors, 'error' );
1267 * Returns a formatted list of errors or warnings from the given elements.
1269 * @param string|array|Status $elements The set of errors/warnings to process.
1270 * @param string $elementsType Should warnings or errors be returned. This is meant
1271 * for Status objects, all other valid types are always considered as errors.
1274 public function getErrorsOrWarnings( $elements, $elementsType ) {
1275 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1276 throw new DomainException( $elementsType . ' is not a valid type.' );
1278 $elementstr = false;
1279 if ( $elements instanceof Status
) {
1280 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1281 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1282 if ( $status->isGood() ) {
1285 $elementstr = $this->getOutput()->parseAsInterface(
1286 $status->getWikiText()
1289 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1290 $elementstr = $this->formatErrors( $elements );
1291 } elseif ( $elementsType === 'error' ) {
1292 $elementstr = $elements;
1296 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1301 * Format a stack of error messages into a single HTML string
1303 * @param array $errors Array of message keys/values
1305 * @return string HTML, a "<ul>" list of errors
1307 public function formatErrors( $errors ) {
1310 foreach ( $errors as $error ) {
1311 $errorstr .= Html
::rawElement(
1314 $this->getMessage( $error )->parse()
1318 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1324 * Set the text for the submit button
1326 * @param string $t Plaintext
1328 * @return HTMLForm $this for chaining calls (since 1.20)
1330 public function setSubmitText( $t ) {
1331 $this->mSubmitText
= $t;
1337 * Identify that the submit button in the form has a destructive action
1340 * @return HTMLForm $this for chaining calls (since 1.28)
1342 public function setSubmitDestructive() {
1343 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1349 * Identify that the submit button in the form has a progressive action
1351 * @deprecated since 1.32, No need to call. Submit button already
1352 * has a progressive action form.
1354 * @return HTMLForm $this for chaining calls (since 1.28)
1356 public function setSubmitProgressive() {
1357 wfDeprecated( __METHOD__
, '1.32' );
1358 $this->mSubmitFlags
= [ 'progressive', 'primary' ];
1364 * Set the text for the submit button to a message
1367 * @param string|Message $msg Message key or Message object
1369 * @return HTMLForm $this for chaining calls (since 1.20)
1371 public function setSubmitTextMsg( $msg ) {
1372 if ( !$msg instanceof Message
) {
1373 $msg = $this->msg( $msg );
1375 $this->setSubmitText( $msg->text() );
1381 * Get the text for the submit button, either customised or a default.
1384 public function getSubmitText() {
1385 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1389 * @param string $name Submit button name
1391 * @return HTMLForm $this for chaining calls (since 1.20)
1393 public function setSubmitName( $name ) {
1394 $this->mSubmitName
= $name;
1400 * @param string $name Tooltip for the submit button
1402 * @return HTMLForm $this for chaining calls (since 1.20)
1404 public function setSubmitTooltip( $name ) {
1405 $this->mSubmitTooltip
= $name;
1411 * Set the id for the submit button.
1415 * @todo FIXME: Integrity of $t is *not* validated
1416 * @return HTMLForm $this for chaining calls (since 1.20)
1418 public function setSubmitID( $t ) {
1419 $this->mSubmitID
= $t;
1425 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1426 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1429 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1430 * was submitted, and not attempt to validate the other ones.
1431 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1432 * HTMLForm to distinguish between the initial page view and a form submission with all
1433 * checkboxes or select options unchecked.
1436 * @param string $ident
1439 public function setFormIdentifier( $ident ) {
1440 $this->mFormIdentifier
= $ident;
1446 * Stop a default submit button being shown for this form. This implies that an
1447 * alternate submit method must be provided manually.
1451 * @param bool $suppressSubmit Set to false to re-enable the button again
1453 * @return HTMLForm $this for chaining calls
1455 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1456 $this->mShowSubmit
= !$suppressSubmit;
1462 * Show a cancel button (or prevent it). The button is not shown by default.
1464 * @return HTMLForm $this for chaining calls
1467 public function showCancel( $show = true ) {
1468 $this->mShowCancel
= $show;
1473 * Sets the target where the user is redirected to after clicking cancel.
1474 * @param Title|string $target Target as a Title object or an URL
1475 * @return HTMLForm $this for chaining calls
1478 public function setCancelTarget( $target ) {
1479 $this->mCancelTarget
= $target;
1484 * Set the id of the \<table\> or outermost \<div\> element.
1488 * @param string $id New value of the id attribute, or "" to remove
1490 * @return HTMLForm $this for chaining calls
1492 public function setTableId( $id ) {
1493 $this->mTableId
= $id;
1499 * @param string $id DOM id for the form
1501 * @return HTMLForm $this for chaining calls (since 1.20)
1503 public function setId( $id ) {
1510 * @param string $name 'name' attribute for the form
1511 * @return HTMLForm $this for chaining calls
1513 public function setName( $name ) {
1514 $this->mName
= $name;
1520 * Prompt the whole form to be wrapped in a "<fieldset>", with
1521 * this text as its "<legend>" element.
1523 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1524 * If true, a wrapper will be displayed, but no legend.
1525 * If a string, a wrapper will be displayed with that string as a legend.
1526 * The string will be escaped before being output (this doesn't support HTML).
1528 * @return HTMLForm $this for chaining calls (since 1.20)
1530 public function setWrapperLegend( $legend ) {
1531 $this->mWrapperLegend
= $legend;
1537 * Prompt the whole form to be wrapped in a "<fieldset>", with
1538 * this message as its "<legend>" element.
1541 * @param string|Message $msg Message key or Message object
1543 * @return HTMLForm $this for chaining calls (since 1.20)
1545 public function setWrapperLegendMsg( $msg ) {
1546 if ( !$msg instanceof Message
) {
1547 $msg = $this->msg( $msg );
1549 $this->setWrapperLegend( $msg->text() );
1555 * Set the prefix for various default messages
1556 * @todo Currently only used for the "<fieldset>" legend on forms
1557 * with multiple sections; should be used elsewhere?
1561 * @return HTMLForm $this for chaining calls (since 1.20)
1563 public function setMessagePrefix( $p ) {
1564 $this->mMessagePrefix
= $p;
1570 * Set the title for form submission
1572 * @param Title $t Title of page the form is on/should be posted to
1574 * @return HTMLForm $this for chaining calls (since 1.20)
1576 public function setTitle( $t ) {
1586 public function getTitle() {
1587 return $this->mTitle
=== false
1588 ?
$this->getContext()->getTitle()
1593 * Set the method used to submit the form
1595 * @param string $method
1597 * @return HTMLForm $this for chaining calls (since 1.20)
1599 public function setMethod( $method = 'post' ) {
1600 $this->mMethod
= strtolower( $method );
1606 * @return string Always lowercase
1608 public function getMethod() {
1609 return $this->mMethod
;
1613 * Wraps the given $section into an user-visible fieldset.
1615 * @param string $legend Legend text for the fieldset
1616 * @param string $section The section content in plain Html
1617 * @param array $attributes Additional attributes for the fieldset
1618 * @param bool $isRoot Section is at the root of the tree
1619 * @return string The fieldset's Html
1621 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1622 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1628 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1630 * @param string $sectionName ID attribute of the "<table>" tag for this
1631 * section, ignored if empty.
1632 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1633 * each subsection, ignored if empty.
1634 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1635 * @throws LogicException When called on uninitialized field data, e.g. When
1636 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1641 public function displaySection( $fields,
1643 $fieldsetIDPrefix = '',
1644 &$hasUserVisibleFields = false
1646 if ( $this->mFieldData
=== null ) {
1647 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1648 . 'You probably called displayForm() without calling prepareForm() first.' );
1651 $displayFormat = $this->getDisplayFormat();
1654 $subsectionHtml = '';
1657 // Conveniently, PHP method names are case-insensitive.
1658 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1659 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1661 foreach ( $fields as $key => $value ) {
1662 if ( $value instanceof HTMLFormField
) {
1663 $v = array_key_exists( $key, $this->mFieldData
)
1664 ?
$this->mFieldData
[$key]
1665 : $value->getDefault();
1667 $retval = $value->$getFieldHtmlMethod( $v );
1669 // check, if the form field should be added to
1671 if ( $value->hasVisibleOutput() ) {
1674 $labelValue = trim( $value->getLabel() );
1675 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
1679 $hasUserVisibleFields = true;
1681 } elseif ( is_array( $value ) ) {
1682 $subsectionHasVisibleFields = false;
1684 $this->displaySection( $value,
1686 "$fieldsetIDPrefix$key-",
1687 $subsectionHasVisibleFields );
1690 if ( $subsectionHasVisibleFields === true ) {
1691 // Display the section with various niceties.
1692 $hasUserVisibleFields = true;
1694 $legend = $this->getLegend( $key );
1696 $section = $this->getHeaderText( $key ) .
1698 $this->getFooterText( $key );
1701 if ( $fieldsetIDPrefix ) {
1702 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1704 $subsectionHtml .= $this->wrapFieldSetSection(
1705 $legend, $section, $attributes, $fields === $this->mFieldTree
1708 // Just return the inputs, nothing fancy.
1709 $subsectionHtml .= $section;
1714 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1716 if ( $subsectionHtml ) {
1717 if ( $this->mSubSectionBeforeFields
) {
1718 return $subsectionHtml . "\n" . $html;
1720 return $html . "\n" . $subsectionHtml;
1728 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1729 * @param array $fieldsHtml
1730 * @param string $sectionName
1731 * @param bool $anyFieldHasLabel
1732 * @return string HTML
1734 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1735 if ( !$fieldsHtml ) {
1736 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1737 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1741 $displayFormat = $this->getDisplayFormat();
1742 $html = implode( '', $fieldsHtml );
1744 if ( $displayFormat === 'raw' ) {
1750 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1751 $classes[] = 'mw-htmlform-nolabel';
1755 'class' => implode( ' ', $classes ),
1758 if ( $sectionName ) {
1759 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1762 if ( $displayFormat === 'table' ) {
1763 return Html
::rawElement( 'table',
1765 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1766 } elseif ( $displayFormat === 'inline' ) {
1767 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1769 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1774 * Construct the form fields from the Descriptor array
1776 public function loadData() {
1779 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1780 $request = $this->getRequest();
1781 if ( $field->skipLoadData( $request ) ) {
1783 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1784 $fieldData[$fieldname] = $field->getDefault();
1786 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1791 foreach ( $fieldData as $name => &$value ) {
1792 $field = $this->mFlatFields
[$name];
1793 $value = $field->filter( $value, $this->mFlatFields
);
1796 $this->mFieldData
= $fieldData;
1800 * Stop a reset button being shown for this form
1802 * @param bool $suppressReset Set to false to re-enable the button again
1804 * @return HTMLForm $this for chaining calls (since 1.20)
1806 public function suppressReset( $suppressReset = true ) {
1807 $this->mShowReset
= !$suppressReset;
1813 * Overload this if you want to apply special filtration routines
1814 * to the form as a whole, after it's submitted but before it's
1817 * @param array $data
1821 public function filterDataForSubmit( $data ) {
1826 * Get a string to go in the "<legend>" of a section fieldset.
1827 * Override this if you want something more complicated.
1829 * @param string $key
1831 * @return string Plain text (not HTML-escaped)
1833 public function getLegend( $key ) {
1834 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1838 * Set the value for the action attribute of the form.
1839 * When set to false (which is the default state), the set title is used.
1843 * @param string|bool $action
1845 * @return HTMLForm $this for chaining calls (since 1.20)
1847 public function setAction( $action ) {
1848 $this->mAction
= $action;
1854 * Get the value for the action attribute of the form.
1860 public function getAction() {
1861 // If an action is alredy provided, return it
1862 if ( $this->mAction
!== false ) {
1863 return $this->mAction
;
1866 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1867 // Check whether we are in GET mode and the ArticlePath contains a "?"
1868 // meaning that getLocalURL() would return something like "index.php?title=...".
1869 // As browser remove the query string before submitting GET forms,
1870 // it means that the title would be lost. In such case use wfScript() instead
1871 // and put title in an hidden field (see getHiddenFields()).
1872 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1876 return $this->getTitle()->getLocalURL();
1880 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1881 * When set to null (which is the default state), the attribute get not set.
1885 * @param string|null $autocomplete
1887 * @return HTMLForm $this for chaining calls
1889 public function setAutocomplete( $autocomplete ) {
1890 $this->mAutocomplete
= $autocomplete;
1896 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1897 * name + parameters array) into a Message.
1898 * @param mixed $value
1901 protected function getMessage( $value ) {
1902 return Message
::newFromSpecifier( $value )->setContext( $this );
1906 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1907 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1908 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1909 * agent has JavaScript support, in htmlform.js.
1914 public function needsJSForHtml5FormValidation() {
1915 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1916 if ( $field->needsJSForHtml5FormValidation() ) {