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 = [];
184 protected $mFieldTree = [];
185 protected $mShowReset = false;
186 protected $mShowSubmit = true;
188 protected $mSubmitFlags = [ 'primary', 'progressive' ];
189 protected $mShowCancel = false;
190 protected $mCancelTarget;
192 protected $mSubmitCallback;
193 protected $mValidationErrorMessage;
195 protected $mPre = '';
196 protected $mHeader = '';
197 protected $mFooter = '';
198 protected $mSectionHeaders = [];
199 protected $mSectionFooters = [];
200 protected $mPost = '';
203 protected $mTableId = '';
205 protected $mSubmitID;
206 protected $mSubmitName;
207 protected $mSubmitText;
208 protected $mSubmitTooltip;
210 protected $mFormIdentifier;
212 protected $mMethod = 'post';
213 protected $mWasSubmitted = false;
216 * Form action URL. false means we will use the URL to set Title
220 protected $mAction = false;
223 * Whether the form can be collapsed
227 protected $mCollapsible = false;
230 * Whether the form is collapsed by default
234 protected $mCollapsed = false;
237 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
241 protected $mAutocomplete = null;
243 protected $mUseMultipart = false;
244 protected $mHiddenFields = [];
245 protected $mButtons = [];
247 protected $mWrapperLegend = false;
248 protected $mWrapperAttributes = [];
251 * Salt for the edit token.
254 protected $mTokenSalt = '';
257 * If true, sections that contain both fields and subsections will
258 * render their subsections before their fields.
260 * Subclasses may set this to false to render subsections after fields
263 protected $mSubSectionBeforeFields = true;
266 * Format in which to display form. For viable options,
267 * @see $availableDisplayFormats
270 protected $displayFormat = 'table';
273 * Available formats in which to display the form
276 protected $availableDisplayFormats = [
284 * Available formats in which to display the form
287 protected $availableSubclassDisplayFormats = [
293 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
295 * @param string $displayFormat
296 * @param mixed $arguments,... Additional arguments to pass to the constructor.
299 public static function factory( $displayFormat/*, $arguments...*/ ) {
300 $arguments = func_get_args();
301 array_shift( $arguments );
303 switch ( $displayFormat ) {
305 return new VFormHTMLForm( ...$arguments );
307 return new OOUIHTMLForm( ...$arguments );
309 $form = new self( ...$arguments );
310 $form->setDisplayFormat( $displayFormat );
316 * Build a new HTMLForm from an array of field attributes
318 * @param array $descriptor Array of Field constructs, as described
319 * in the class documentation
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 $this->addFields( $descriptor );
351 * Add fields to the form
355 * @param array $descriptor Array of Field constructs, as described
356 * in the class documentation
359 public function addFields( $descriptor ) {
360 $loadedDescriptor = [];
362 foreach ( $descriptor as $fieldname => $info ) {
364 $section = $info['section'] ??
'';
366 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
367 $this->mUseMultipart
= true;
370 $field = static::loadInputFromParameters( $fieldname, $info, $this );
372 $setSection =& $loadedDescriptor;
374 foreach ( explode( '/', $section ) as $newName ) {
375 if ( !isset( $setSection[$newName] ) ) {
376 $setSection[$newName] = [];
379 $setSection =& $setSection[$newName];
383 $setSection[$fieldname] = $field;
384 $this->mFlatFields
[$fieldname] = $field;
387 $this->mFieldTree
= array_merge( $this->mFieldTree
, $loadedDescriptor );
393 * @param string $fieldname
396 public function hasField( $fieldname ) {
397 return isset( $this->mFlatFields
[$fieldname] );
401 * @param string $fieldname
402 * @return HTMLFormField
403 * @throws DomainException on invalid field name
405 public function getField( $fieldname ) {
406 if ( !$this->hasField( $fieldname ) ) {
407 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
409 return $this->mFlatFields
[$fieldname];
413 * Set format in which to display the form
415 * @param string $format The name of the format to use, must be one of
416 * $this->availableDisplayFormats
418 * @throws MWException
420 * @return HTMLForm $this for chaining calls (since 1.20)
422 public function setDisplayFormat( $format ) {
424 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
425 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
427 throw new MWException( 'Cannot change display format after creation, ' .
428 'use HTMLForm::factory() instead' );
431 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
432 throw new MWException( 'Display format must be one of ' .
435 $this->availableDisplayFormats
,
436 $this->availableSubclassDisplayFormats
442 // Evil hack for mobile :(
443 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
447 $this->displayFormat
= $format;
453 * Getter for displayFormat
457 public function getDisplayFormat() {
458 return $this->displayFormat
;
462 * Get the HTMLFormField subclass for this descriptor.
464 * The descriptor can be passed either 'class' which is the name of
465 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
466 * This makes sure the 'class' is always set, and also is returned by
467 * this function for ease.
471 * @param string $fieldname Name of the field
472 * @param array &$descriptor Input Descriptor, as described
473 * in the class documentation
475 * @throws MWException
476 * @return string Name of a HTMLFormField subclass
478 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
479 if ( isset( $descriptor['class'] ) ) {
480 $class = $descriptor['class'];
481 } elseif ( isset( $descriptor['type'] ) ) {
482 $class = static::$typeMappings[$descriptor['type']];
483 $descriptor['class'] = $class;
489 throw new MWException( "Descriptor with no class for $fieldname: "
490 . print_r( $descriptor, true ) );
497 * Initialise a new Object for the field
499 * @param string $fieldname Name of the field
500 * @param array $descriptor Input Descriptor, as described
501 * in the class documentation
502 * @param HTMLForm|null $parent Parent instance of HTMLForm
504 * @throws MWException
505 * @return HTMLFormField Instance of a subclass of HTMLFormField
507 public static function loadInputFromParameters( $fieldname, $descriptor,
508 HTMLForm
$parent = null
510 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
512 $descriptor['fieldname'] = $fieldname;
514 $descriptor['parent'] = $parent;
517 # @todo This will throw a fatal error whenever someone try to use
518 # 'class' to feed a CSS class instead of 'cssclass'. Would be
519 # great to avoid the fatal error and show a nice error.
520 return new $class( $descriptor );
524 * Prepare form for submission.
526 * @warning When doing method chaining, that should be the very last
527 * method call before displayForm().
529 * @throws MWException
530 * @return HTMLForm $this for chaining calls (since 1.20)
532 public function prepareForm() {
533 # Check if we have the info we need
534 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
535 throw new MWException( 'You must call setTitle() on an HTMLForm' );
538 # Load data from the request.
540 $this->mFormIdentifier
=== null ||
541 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
545 $this->mFieldData
= [];
552 * Try submitting, with edit token check first
553 * @return Status|bool
555 public function tryAuthorizedSubmit() {
558 if ( $this->mFormIdentifier
=== null ) {
561 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
565 if ( $this->getMethod() !== 'post' ) {
566 $tokenOkay = true; // no session check needed
567 } elseif ( $this->getRequest()->wasPosted() ) {
568 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
569 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
570 // Session tokens for logged-out users have no security value.
571 // However, if the user gave one, check it in order to give a nice
572 // "session expired" error instead of "permission denied" or such.
573 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
579 if ( $tokenOkay && $identOkay ) {
580 $this->mWasSubmitted
= true;
581 $result = $this->trySubmit();
588 * The here's-one-I-made-earlier option: do the submission if
589 * posted, or display the form with or without funky validation
591 * @return bool|Status Whether submission was successful.
593 public function show() {
594 $this->prepareForm();
596 $result = $this->tryAuthorizedSubmit();
597 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
601 $this->displayForm( $result );
607 * Same as self::show with the difference, that the form will be
608 * added to the output, no matter, if the validation was good or not.
609 * @return bool|Status Whether submission was successful.
611 public function showAlways() {
612 $this->prepareForm();
614 $result = $this->tryAuthorizedSubmit();
616 $this->displayForm( $result );
622 * Validate all the fields, and call the submission callback
623 * function if everything is kosher.
624 * @throws MWException
625 * @return bool|string|array|Status
626 * - Bool true or a good Status object indicates success,
627 * - Bool false indicates no submission was attempted,
628 * - Anything else indicates failure. The value may be a fatal Status
629 * object, an HTML string, or an array of arrays (message keys and
630 * params) or strings (message keys)
632 public function trySubmit() {
634 $hoistedErrors = Status
::newGood();
635 if ( $this->mValidationErrorMessage
) {
636 foreach ( $this->mValidationErrorMessage
as $error ) {
637 $hoistedErrors->fatal( ...$error );
640 $hoistedErrors->fatal( 'htmlform-invalid-input' );
643 $this->mWasSubmitted
= true;
645 # Check for cancelled submission
646 foreach ( $this->mFlatFields
as $fieldname => $field ) {
647 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
650 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
651 $this->mWasSubmitted
= false;
656 # Check for validation
657 foreach ( $this->mFlatFields
as $fieldname => $field ) {
658 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
661 if ( $field->isHidden( $this->mFieldData
) ) {
664 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
665 if ( $res !== true ) {
667 if ( $res !== false && !$field->canDisplayErrors() ) {
668 if ( is_string( $res ) ) {
669 $hoistedErrors->fatal( 'rawmessage', $res );
671 $hoistedErrors->fatal( $res );
678 return $hoistedErrors;
681 $callback = $this->mSubmitCallback
;
682 if ( !is_callable( $callback ) ) {
683 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
684 'setSubmitCallback() to set one.' );
687 $data = $this->filterDataForSubmit( $this->mFieldData
);
689 $res = call_user_func( $callback, $data, $this );
690 if ( $res === false ) {
691 $this->mWasSubmitted
= false;
698 * Test whether the form was considered to have been submitted or not, i.e.
699 * whether the last call to tryAuthorizedSubmit or trySubmit returned
702 * This will return false until HTMLForm::tryAuthorizedSubmit or
703 * HTMLForm::trySubmit is called.
708 public function wasSubmitted() {
709 return $this->mWasSubmitted
;
713 * Set a callback to a function to do something with the form
714 * once it's been successfully validated.
716 * @param callable $cb The function will be passed the output from
717 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
718 * return as documented for HTMLForm::trySubmit
720 * @return HTMLForm $this for chaining calls (since 1.20)
722 public function setSubmitCallback( $cb ) {
723 $this->mSubmitCallback
= $cb;
729 * Set a message to display on a validation error.
731 * @param array $msg Array of valid inputs to wfMessage()
732 * (so each entry must itself be an array of arguments)
734 * @return HTMLForm $this for chaining calls (since 1.20)
736 public function setValidationErrorMessage( $msg ) {
737 $this->mValidationErrorMessage
= $msg;
743 * Set the introductory message, overwriting any existing message.
745 * @param string $msg Complete text of message to display
747 * @return HTMLForm $this for chaining calls (since 1.20)
749 public function setIntro( $msg ) {
750 $this->setPreText( $msg );
756 * Set the introductory message HTML, overwriting any existing message.
759 * @param string $msg Complete HTML of message to display
761 * @return HTMLForm $this for chaining calls (since 1.20)
763 public function setPreText( $msg ) {
770 * Add HTML to introductory message.
772 * @param string $msg Complete HTML of message to display
774 * @return HTMLForm $this for chaining calls (since 1.20)
776 public function addPreText( $msg ) {
783 * Get the introductory message HTML.
789 public function getPreText() {
794 * Add HTML to the header, inside the form.
796 * @param string $msg Additional HTML to display in header
797 * @param string|null $section The section to add the header to
799 * @return HTMLForm $this for chaining calls (since 1.20)
801 public function addHeaderText( $msg, $section = null ) {
802 if ( $section === null ) {
803 $this->mHeader
.= $msg;
805 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
806 $this->mSectionHeaders
[$section] = '';
808 $this->mSectionHeaders
[$section] .= $msg;
815 * Set header text, inside the form.
818 * @param string $msg Complete HTML of header to display
819 * @param string|null $section The section to add the header to
821 * @return HTMLForm $this for chaining calls (since 1.20)
823 public function setHeaderText( $msg, $section = null ) {
824 if ( $section === null ) {
825 $this->mHeader
= $msg;
827 $this->mSectionHeaders
[$section] = $msg;
836 * @param string|null $section The section to get the header text for
838 * @return string HTML
840 public function getHeaderText( $section = null ) {
841 if ( $section === null ) {
842 return $this->mHeader
;
844 return $this->mSectionHeaders
[$section] ??
'';
849 * Add footer text, inside the form.
851 * @param string $msg Complete text of message to display
852 * @param string|null $section The section to add the footer text to
854 * @return HTMLForm $this for chaining calls (since 1.20)
856 public function addFooterText( $msg, $section = null ) {
857 if ( $section === null ) {
858 $this->mFooter
.= $msg;
860 if ( !isset( $this->mSectionFooters
[$section] ) ) {
861 $this->mSectionFooters
[$section] = '';
863 $this->mSectionFooters
[$section] .= $msg;
870 * Set footer text, inside the form.
873 * @param string $msg Complete text of message to display
874 * @param string|null $section The section to add the footer text to
876 * @return HTMLForm $this for chaining calls (since 1.20)
878 public function setFooterText( $msg, $section = null ) {
879 if ( $section === null ) {
880 $this->mFooter
= $msg;
882 $this->mSectionFooters
[$section] = $msg;
891 * @param string|null $section The section to get the footer text for
895 public function getFooterText( $section = null ) {
896 if ( $section === null ) {
897 return $this->mFooter
;
899 return $this->mSectionFooters
[$section] ??
'';
904 * Add text to the end of the display.
906 * @param string $msg Complete text of message to display
908 * @return HTMLForm $this for chaining calls (since 1.20)
910 public function addPostText( $msg ) {
911 $this->mPost
.= $msg;
917 * Set text at the end of the display.
919 * @param string $msg Complete text of message to display
921 * @return HTMLForm $this for chaining calls (since 1.20)
923 public function setPostText( $msg ) {
930 * Add a hidden field to the output
932 * @param string $name Field name. This will be used exactly as entered
933 * @param string $value Field value
934 * @param array $attribs
936 * @return HTMLForm $this for chaining calls (since 1.20)
938 public function addHiddenField( $name, $value, array $attribs = [] ) {
939 $attribs +
= [ 'name' => $name ];
940 $this->mHiddenFields
[] = [ $value, $attribs ];
946 * Add an array of hidden fields to the output
950 * @param array $fields Associative array of fields to add;
951 * mapping names to their values
953 * @return HTMLForm $this for chaining calls
955 public function addHiddenFields( array $fields ) {
956 foreach ( $fields as $name => $value ) {
957 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
964 * Add a button to the form
966 * @since 1.27 takes an array as shown. Earlier versions accepted
967 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
969 * @note Custom labels ('label', 'label-message', 'label-raw') are not
970 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
971 * they will be served buttons using 'value' as the button label.
972 * @param array $data Data to define the button:
973 * - name: (string) Button name.
974 * - value: (string) Button value.
975 * - label-message: (string, optional) Button label message key to use
976 * instead of 'value'. Overrides 'label' and 'label-raw'.
977 * - label: (string, optional) Button label text to use instead of
978 * 'value'. Overrides 'label-raw'.
979 * - label-raw: (string, optional) Button label HTML to use instead of
981 * - id: (string, optional) DOM id for the button.
982 * - attribs: (array, optional) Additional HTML attributes.
983 * - flags: (string|string[], optional) OOUI flags.
984 * - framed: (boolean=true, optional) OOUI framed attribute.
985 * @return HTMLForm $this for chaining calls (since 1.20)
987 public function addButton( $data ) {
988 if ( !is_array( $data ) ) {
989 $args = func_get_args();
990 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
991 throw new InvalidArgumentException(
992 'Incorrect number of arguments for deprecated calling style'
998 'id' => $args[2] ??
null,
999 'attribs' => $args[3] ??
null,
1002 if ( !isset( $data['name'] ) ) {
1003 throw new InvalidArgumentException( 'A name is required' );
1005 if ( !isset( $data['value'] ) ) {
1006 throw new InvalidArgumentException( 'A value is required' );
1009 $this->mButtons
[] = $data +
[
1020 * Set the salt for the edit token.
1022 * Only useful when the method is "post".
1025 * @param string|array $salt Salt to use
1026 * @return HTMLForm $this For chaining calls
1028 public function setTokenSalt( $salt ) {
1029 $this->mTokenSalt
= $salt;
1035 * Display the form (sending to the context's OutputPage object), with an
1036 * appropriate error message or stack of messages, and any validation errors, etc.
1038 * @warning You should call prepareForm() before calling this function.
1039 * Moreover, when doing method chaining this should be the very last method
1040 * call just after prepareForm().
1042 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1044 * @return void Nothing, should be last call
1046 public function displayForm( $submitResult ) {
1047 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1051 * Returns the raw HTML generated by the form
1053 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1055 * @return string HTML
1056 * @return-taint escaped
1058 public function getHTML( $submitResult ) {
1059 # For good measure (it is the default)
1060 $this->getOutput()->preventClickjacking();
1061 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1062 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1065 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1066 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1067 . $this->getHeaderText()
1069 . $this->getHiddenFields()
1070 . $this->getButtons()
1071 . $this->getFooterText();
1073 $html = $this->wrapForm( $html );
1075 return '' . $this->mPre
. $html . $this->mPost
;
1079 * Enable collapsible mode, and set whether the form is collapsed by default.
1082 * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
1083 * @return HTMLForm $this for chaining calls
1085 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1086 $this->mCollapsible
= true;
1087 $this->mCollapsed
= $collapsedByDefault;
1092 * Get HTML attributes for the `<form>` tag.
1095 protected function getFormAttributes() {
1096 # Use multipart/form-data
1097 $encType = $this->mUseMultipart
1098 ?
'multipart/form-data'
1099 : 'application/x-www-form-urlencoded';
1102 'class' => 'mw-htmlform',
1103 'action' => $this->getAction(),
1104 'method' => $this->getMethod(),
1105 'enctype' => $encType,
1108 $attribs['id'] = $this->mId
;
1110 if ( is_string( $this->mAutocomplete
) ) {
1111 $attribs['autocomplete'] = $this->mAutocomplete
;
1113 if ( $this->mName
) {
1114 $attribs['name'] = $this->mName
;
1116 if ( $this->needsJSForHtml5FormValidation() ) {
1117 $attribs['novalidate'] = true;
1123 * Wrap the form innards in an actual "<form>" element
1125 * @param string $html HTML contents to wrap.
1127 * @return string Wrapped HTML.
1129 public function wrapForm( $html ) {
1130 # Include a <fieldset> wrapper for style, if requested.
1131 if ( $this->mWrapperLegend
!== false ) {
1132 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1133 $html = Xml
::fieldset( $legend, $html, $this->mWrapperAttributes
);
1136 return Html
::rawElement(
1138 $this->getFormAttributes(),
1144 * Get the hidden fields that should go inside the form.
1145 * @return string HTML.
1147 public function getHiddenFields() {
1149 if ( $this->mFormIdentifier
!== null ) {
1150 $html .= Html
::hidden(
1152 $this->mFormIdentifier
1155 if ( $this->getMethod() === 'post' ) {
1156 $html .= Html
::hidden(
1158 $this->getUser()->getEditToken( $this->mTokenSalt
),
1159 [ 'id' => 'wpEditToken' ]
1161 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1164 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1165 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1166 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1169 foreach ( $this->mHiddenFields
as $data ) {
1170 list( $value, $attribs ) = $data;
1171 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1178 * Get the submit and (potentially) reset buttons.
1179 * @return string HTML.
1181 public function getButtons() {
1183 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1185 if ( $this->mShowSubmit
) {
1188 if ( isset( $this->mSubmitID
) ) {
1189 $attribs['id'] = $this->mSubmitID
;
1192 if ( isset( $this->mSubmitName
) ) {
1193 $attribs['name'] = $this->mSubmitName
;
1196 if ( isset( $this->mSubmitTooltip
) ) {
1197 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1200 $attribs['class'] = [ 'mw-htmlform-submit' ];
1202 if ( $useMediaWikiUIEverywhere ) {
1203 foreach ( $this->mSubmitFlags
as $flag ) {
1204 $attribs['class'][] = 'mw-ui-' . $flag;
1206 $attribs['class'][] = 'mw-ui-button';
1209 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1212 if ( $this->mShowReset
) {
1213 $buttons .= Html
::element(
1217 'value' => $this->msg( 'htmlform-reset' )->text(),
1218 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1223 if ( $this->mShowCancel
) {
1224 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1225 if ( $target instanceof Title
) {
1226 $target = $target->getLocalURL();
1228 $buttons .= Html
::element(
1231 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1234 $this->msg( 'cancel' )->text()
1238 // IE<8 has bugs with <button>, so we'll need to avoid them.
1239 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1241 foreach ( $this->mButtons
as $button ) {
1244 'name' => $button['name'],
1245 'value' => $button['value']
1248 if ( isset( $button['label-message'] ) ) {
1249 $label = $this->getMessage( $button['label-message'] )->parse();
1250 } elseif ( isset( $button['label'] ) ) {
1251 $label = htmlspecialchars( $button['label'] );
1252 } elseif ( isset( $button['label-raw'] ) ) {
1253 $label = $button['label-raw'];
1255 $label = htmlspecialchars( $button['value'] );
1258 if ( $button['attribs'] ) {
1259 $attrs +
= $button['attribs'];
1262 if ( isset( $button['id'] ) ) {
1263 $attrs['id'] = $button['id'];
1266 if ( $useMediaWikiUIEverywhere ) {
1267 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1268 $attrs['class'][] = 'mw-ui-button';
1272 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1274 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1282 return Html
::rawElement( 'span',
1283 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1287 * Get the whole body of the form.
1290 public function getBody() {
1291 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1295 * Returns a formatted list of errors or warnings from the given elements.
1297 * @param string|array|Status $elements The set of errors/warnings to process.
1298 * @param string $elementsType Should warnings or errors be returned. This is meant
1299 * for Status objects, all other valid types are always considered as errors.
1302 public function getErrorsOrWarnings( $elements, $elementsType ) {
1303 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1304 throw new DomainException( $elementsType . ' is not a valid type.' );
1306 $elementstr = false;
1307 if ( $elements instanceof Status
) {
1308 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1309 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1310 if ( $status->isGood() ) {
1313 $elementstr = $this->getOutput()->parseAsInterface(
1314 $status->getWikiText()
1317 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1318 $elementstr = $this->formatErrors( $elements );
1319 } elseif ( $elementsType === 'error' ) {
1320 $elementstr = $elements;
1324 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1329 * Format a stack of error messages into a single HTML string
1331 * @param array $errors Array of message keys/values
1333 * @return string HTML, a "<ul>" list of errors
1335 public function formatErrors( $errors ) {
1338 foreach ( $errors as $error ) {
1339 $errorstr .= Html
::rawElement(
1342 $this->getMessage( $error )->parse()
1346 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1352 * Set the text for the submit button
1354 * @param string $t Plaintext
1356 * @return HTMLForm $this for chaining calls (since 1.20)
1358 public function setSubmitText( $t ) {
1359 $this->mSubmitText
= $t;
1365 * Identify that the submit button in the form has a destructive action
1368 * @return HTMLForm $this for chaining calls (since 1.28)
1370 public function setSubmitDestructive() {
1371 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1377 * Set the text for the submit button to a message
1380 * @param string|Message $msg Message key or Message object
1382 * @return HTMLForm $this for chaining calls (since 1.20)
1384 public function setSubmitTextMsg( $msg ) {
1385 if ( !$msg instanceof Message
) {
1386 $msg = $this->msg( $msg );
1388 $this->setSubmitText( $msg->text() );
1394 * Get the text for the submit button, either customised or a default.
1397 public function getSubmitText() {
1398 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1402 * @param string $name Submit button name
1404 * @return HTMLForm $this for chaining calls (since 1.20)
1406 public function setSubmitName( $name ) {
1407 $this->mSubmitName
= $name;
1413 * @param string $name Tooltip for the submit button
1415 * @return HTMLForm $this for chaining calls (since 1.20)
1417 public function setSubmitTooltip( $name ) {
1418 $this->mSubmitTooltip
= $name;
1424 * Set the id for the submit button.
1428 * @todo FIXME: Integrity of $t is *not* validated
1429 * @return HTMLForm $this for chaining calls (since 1.20)
1431 public function setSubmitID( $t ) {
1432 $this->mSubmitID
= $t;
1438 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1439 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1442 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1443 * was submitted, and not attempt to validate the other ones.
1444 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1445 * HTMLForm to distinguish between the initial page view and a form submission with all
1446 * checkboxes or select options unchecked.
1449 * @param string $ident
1452 public function setFormIdentifier( $ident ) {
1453 $this->mFormIdentifier
= $ident;
1459 * Stop a default submit button being shown for this form. This implies that an
1460 * alternate submit method must be provided manually.
1464 * @param bool $suppressSubmit Set to false to re-enable the button again
1466 * @return HTMLForm $this for chaining calls
1468 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1469 $this->mShowSubmit
= !$suppressSubmit;
1475 * Show a cancel button (or prevent it). The button is not shown by default.
1477 * @return HTMLForm $this for chaining calls
1480 public function showCancel( $show = true ) {
1481 $this->mShowCancel
= $show;
1486 * Sets the target where the user is redirected to after clicking cancel.
1487 * @param Title|string $target Target as a Title object or an URL
1488 * @return HTMLForm $this for chaining calls
1491 public function setCancelTarget( $target ) {
1492 $this->mCancelTarget
= $target;
1497 * Set the id of the \<table\> or outermost \<div\> element.
1501 * @param string $id New value of the id attribute, or "" to remove
1503 * @return HTMLForm $this for chaining calls
1505 public function setTableId( $id ) {
1506 $this->mTableId
= $id;
1512 * @param string $id DOM id for the form
1514 * @return HTMLForm $this for chaining calls (since 1.20)
1516 public function setId( $id ) {
1523 * @param string $name 'name' attribute for the form
1524 * @return HTMLForm $this for chaining calls
1526 public function setName( $name ) {
1527 $this->mName
= $name;
1533 * Prompt the whole form to be wrapped in a "<fieldset>", with
1534 * this text as its "<legend>" element.
1536 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1537 * If true, a wrapper will be displayed, but no legend.
1538 * If a string, a wrapper will be displayed with that string as a legend.
1539 * The string will be escaped before being output (this doesn't support HTML).
1541 * @return HTMLForm $this for chaining calls (since 1.20)
1543 public function setWrapperLegend( $legend ) {
1544 $this->mWrapperLegend
= $legend;
1550 * For internal use only. Use is discouraged, and should only be used where
1551 * support for gadgets/user scripts is warranted.
1552 * @param array $attributes
1554 * @return HTMLForm $this for chaining calls
1556 public function setWrapperAttributes( $attributes ) {
1557 $this->mWrapperAttributes
= $attributes;
1563 * Prompt the whole form to be wrapped in a "<fieldset>", with
1564 * this message as its "<legend>" element.
1567 * @param string|Message $msg Message key or Message object
1569 * @return HTMLForm $this for chaining calls (since 1.20)
1571 public function setWrapperLegendMsg( $msg ) {
1572 if ( !$msg instanceof Message
) {
1573 $msg = $this->msg( $msg );
1575 $this->setWrapperLegend( $msg->text() );
1581 * Set the prefix for various default messages
1582 * @todo Currently only used for the "<fieldset>" legend on forms
1583 * with multiple sections; should be used elsewhere?
1587 * @return HTMLForm $this for chaining calls (since 1.20)
1589 public function setMessagePrefix( $p ) {
1590 $this->mMessagePrefix
= $p;
1596 * Set the title for form submission
1598 * @param Title $t Title of page the form is on/should be posted to
1600 * @return HTMLForm $this for chaining calls (since 1.20)
1602 public function setTitle( $t ) {
1612 public function getTitle() {
1613 return $this->mTitle
=== false
1614 ?
$this->getContext()->getTitle()
1619 * Set the method used to submit the form
1621 * @param string $method
1623 * @return HTMLForm $this for chaining calls (since 1.20)
1625 public function setMethod( $method = 'post' ) {
1626 $this->mMethod
= strtolower( $method );
1632 * @return string Always lowercase
1634 public function getMethod() {
1635 return $this->mMethod
;
1639 * Wraps the given $section into an user-visible fieldset.
1641 * @param string $legend Legend text for the fieldset
1642 * @param string $section The section content in plain Html
1643 * @param array $attributes Additional attributes for the fieldset
1644 * @param bool $isRoot Section is at the root of the tree
1645 * @return string The fieldset's Html
1647 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1648 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1654 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1656 * @param string $sectionName ID attribute of the "<table>" tag for this
1657 * section, ignored if empty.
1658 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1659 * each subsection, ignored if empty.
1660 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1661 * @throws LogicException When called on uninitialized field data, e.g. When
1662 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1667 public function displaySection( $fields,
1669 $fieldsetIDPrefix = '',
1670 &$hasUserVisibleFields = false
1672 if ( $this->mFieldData
=== null ) {
1673 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1674 . 'You probably called displayForm() without calling prepareForm() first.' );
1677 $displayFormat = $this->getDisplayFormat();
1680 $subsectionHtml = '';
1683 // Conveniently, PHP method names are case-insensitive.
1684 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1685 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1687 foreach ( $fields as $key => $value ) {
1688 if ( $value instanceof HTMLFormField
) {
1689 $v = array_key_exists( $key, $this->mFieldData
)
1690 ?
$this->mFieldData
[$key]
1691 : $value->getDefault();
1693 $retval = $value->$getFieldHtmlMethod( $v );
1695 // check, if the form field should be added to
1697 if ( $value->hasVisibleOutput() ) {
1700 $labelValue = trim( $value->getLabel() );
1701 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
1705 $hasUserVisibleFields = true;
1707 } elseif ( is_array( $value ) ) {
1708 $subsectionHasVisibleFields = false;
1710 $this->displaySection( $value,
1712 "$fieldsetIDPrefix$key-",
1713 $subsectionHasVisibleFields );
1716 if ( $subsectionHasVisibleFields === true ) {
1717 // Display the section with various niceties.
1718 $hasUserVisibleFields = true;
1720 $legend = $this->getLegend( $key );
1722 $section = $this->getHeaderText( $key ) .
1724 $this->getFooterText( $key );
1727 if ( $fieldsetIDPrefix ) {
1728 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1730 $subsectionHtml .= $this->wrapFieldSetSection(
1731 $legend, $section, $attributes, $fields === $this->mFieldTree
1734 // Just return the inputs, nothing fancy.
1735 $subsectionHtml .= $section;
1740 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1742 if ( $subsectionHtml ) {
1743 if ( $this->mSubSectionBeforeFields
) {
1744 return $subsectionHtml . "\n" . $html;
1746 return $html . "\n" . $subsectionHtml;
1754 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1755 * @param array $fieldsHtml
1756 * @param string $sectionName
1757 * @param bool $anyFieldHasLabel
1758 * @return string HTML
1760 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1761 if ( !$fieldsHtml ) {
1762 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1763 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1767 $displayFormat = $this->getDisplayFormat();
1768 $html = implode( '', $fieldsHtml );
1770 if ( $displayFormat === 'raw' ) {
1776 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1777 $classes[] = 'mw-htmlform-nolabel';
1781 'class' => implode( ' ', $classes ),
1784 if ( $sectionName ) {
1785 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1788 if ( $displayFormat === 'table' ) {
1789 return Html
::rawElement( 'table',
1791 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1792 } elseif ( $displayFormat === 'inline' ) {
1793 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1795 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1800 * Construct the form fields from the Descriptor array
1802 public function loadData() {
1805 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1806 $request = $this->getRequest();
1807 if ( $field->skipLoadData( $request ) ) {
1809 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1810 $fieldData[$fieldname] = $field->getDefault();
1812 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1817 foreach ( $fieldData as $name => &$value ) {
1818 $field = $this->mFlatFields
[$name];
1819 $value = $field->filter( $value, $this->mFlatFields
);
1822 $this->mFieldData
= $fieldData;
1826 * Stop a reset button being shown for this form
1828 * @param bool $suppressReset Set to false to re-enable the button again
1830 * @return HTMLForm $this for chaining calls (since 1.20)
1832 public function suppressReset( $suppressReset = true ) {
1833 $this->mShowReset
= !$suppressReset;
1839 * Overload this if you want to apply special filtration routines
1840 * to the form as a whole, after it's submitted but before it's
1843 * @param array $data
1847 public function filterDataForSubmit( $data ) {
1852 * Get a string to go in the "<legend>" of a section fieldset.
1853 * Override this if you want something more complicated.
1855 * @param string $key
1857 * @return string Plain text (not HTML-escaped)
1859 public function getLegend( $key ) {
1860 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1864 * Set the value for the action attribute of the form.
1865 * When set to false (which is the default state), the set title is used.
1869 * @param string|bool $action
1871 * @return HTMLForm $this for chaining calls (since 1.20)
1873 public function setAction( $action ) {
1874 $this->mAction
= $action;
1880 * Get the value for the action attribute of the form.
1886 public function getAction() {
1887 // If an action is alredy provided, return it
1888 if ( $this->mAction
!== false ) {
1889 return $this->mAction
;
1892 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1893 // Check whether we are in GET mode and the ArticlePath contains a "?"
1894 // meaning that getLocalURL() would return something like "index.php?title=...".
1895 // As browser remove the query string before submitting GET forms,
1896 // it means that the title would be lost. In such case use wfScript() instead
1897 // and put title in an hidden field (see getHiddenFields()).
1898 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1902 return $this->getTitle()->getLocalURL();
1906 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1907 * When set to null (which is the default state), the attribute get not set.
1911 * @param string|null $autocomplete
1913 * @return HTMLForm $this for chaining calls
1915 public function setAutocomplete( $autocomplete ) {
1916 $this->mAutocomplete
= $autocomplete;
1922 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1923 * name + parameters array) into a Message.
1924 * @param mixed $value
1927 protected function getMessage( $value ) {
1928 return Message
::newFromSpecifier( $value )->setContext( $this );
1932 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1933 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1934 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1935 * agent has JavaScript support, in htmlform.js.
1940 public function needsJSForHtml5FormValidation() {
1941 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1942 if ( $field->needsJSForHtml5FormValidation() ) {