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;
187 protected $mSubmitFlags = [ 'primary', 'progressive' ];
188 protected $mShowCancel = false;
189 protected $mCancelTarget;
191 protected $mSubmitCallback;
192 protected $mValidationErrorMessage;
194 protected $mPre = '';
195 protected $mHeader = '';
196 protected $mFooter = '';
197 protected $mSectionHeaders = [];
198 protected $mSectionFooters = [];
199 protected $mPost = '';
202 protected $mTableId = '';
204 protected $mSubmitID;
205 protected $mSubmitName;
206 protected $mSubmitText;
207 protected $mSubmitTooltip;
209 protected $mFormIdentifier;
211 protected $mMethod = 'post';
212 protected $mWasSubmitted = false;
215 * Form action URL. false means we will use the URL to set Title
219 protected $mAction = false;
222 * Whether the form can be collapsed
226 protected $mCollapsible = false;
229 * Whether the form is collapsed by default
233 protected $mCollapsed = false;
236 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
240 protected $mAutocomplete = null;
242 protected $mUseMultipart = false;
243 protected $mHiddenFields = [];
244 protected $mButtons = [];
246 protected $mWrapperLegend = false;
247 protected $mWrapperAttributes = [];
250 * Salt for the edit token.
253 protected $mTokenSalt = '';
256 * If true, sections that contain both fields and subsections will
257 * render their subsections before their fields.
259 * Subclasses may set this to false to render subsections after fields
262 protected $mSubSectionBeforeFields = true;
265 * Format in which to display form. For viable options,
266 * @see $availableDisplayFormats
269 protected $displayFormat = 'table';
272 * Available formats in which to display the form
275 protected $availableDisplayFormats = [
283 * Available formats in which to display the form
286 protected $availableSubclassDisplayFormats = [
292 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
294 * @param string $displayFormat
295 * @param mixed $arguments,... Additional arguments to pass to the constructor.
298 public static function factory( $displayFormat/*, $arguments...*/ ) {
299 $arguments = func_get_args();
300 array_shift( $arguments );
302 switch ( $displayFormat ) {
304 return new VFormHTMLForm( ...$arguments );
306 return new OOUIHTMLForm( ...$arguments );
308 $form = new self( ...$arguments );
309 $form->setDisplayFormat( $displayFormat );
315 * Build a new HTMLForm from an array of field attributes
317 * @param array $descriptor Array of Field constructs, as described
318 * in the class documentation
319 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
320 * Obviates the need to call $form->setTitle()
321 * @param string $messagePrefix A prefix to go in front of default messages
323 public function __construct( $descriptor, /*IContextSource*/ $context = null,
326 if ( $context instanceof IContextSource
) {
327 $this->setContext( $context );
328 $this->mTitle
= false; // We don't need them to set a title
329 $this->mMessagePrefix
= $messagePrefix;
330 } elseif ( $context === null && $messagePrefix !== '' ) {
331 $this->mMessagePrefix
= $messagePrefix;
332 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
334 // it's actually $messagePrefix
335 $this->mMessagePrefix
= $context;
338 // Evil hack for mobile :(
340 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
341 && $this->displayFormat
=== 'table'
343 $this->displayFormat
= 'div';
346 $this->addFields( $descriptor );
350 * Add fields to the form
354 * @param array $descriptor Array of Field constructs, as described
355 * in the class documentation
358 public function addFields( $descriptor ) {
359 $loadedDescriptor = [];
361 foreach ( $descriptor as $fieldname => $info ) {
363 $section = $info['section'] ??
'';
365 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
366 $this->mUseMultipart
= true;
369 $field = static::loadInputFromParameters( $fieldname, $info, $this );
371 $setSection =& $loadedDescriptor;
373 foreach ( explode( '/', $section ) as $newName ) {
374 if ( !isset( $setSection[$newName] ) ) {
375 $setSection[$newName] = [];
378 $setSection =& $setSection[$newName];
382 $setSection[$fieldname] = $field;
383 $this->mFlatFields
[$fieldname] = $field;
386 $this->mFieldTree
= array_merge( $this->mFieldTree
, $loadedDescriptor );
392 * @param string $fieldname
395 public function hasField( $fieldname ) {
396 return isset( $this->mFlatFields
[$fieldname] );
400 * @param string $fieldname
401 * @return HTMLFormField
402 * @throws DomainException on invalid field name
404 public function getField( $fieldname ) {
405 if ( !$this->hasField( $fieldname ) ) {
406 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
408 return $this->mFlatFields
[$fieldname];
412 * Set format in which to display the form
414 * @param string $format The name of the format to use, must be one of
415 * $this->availableDisplayFormats
417 * @throws MWException
419 * @return HTMLForm $this for chaining calls (since 1.20)
421 public function setDisplayFormat( $format ) {
423 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
424 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
426 throw new MWException( 'Cannot change display format after creation, ' .
427 'use HTMLForm::factory() instead' );
430 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
431 throw new MWException( 'Display format must be one of ' .
434 $this->availableDisplayFormats
,
435 $this->availableSubclassDisplayFormats
441 // Evil hack for mobile :(
442 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
446 $this->displayFormat
= $format;
452 * Getter for displayFormat
456 public function getDisplayFormat() {
457 return $this->displayFormat
;
461 * Get the HTMLFormField subclass for this descriptor.
463 * The descriptor can be passed either 'class' which is the name of
464 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
465 * This makes sure the 'class' is always set, and also is returned by
466 * this function for ease.
470 * @param string $fieldname Name of the field
471 * @param array &$descriptor Input Descriptor, as described
472 * in the class documentation
474 * @throws MWException
475 * @return string Name of a HTMLFormField subclass
477 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
478 if ( isset( $descriptor['class'] ) ) {
479 $class = $descriptor['class'];
480 } elseif ( isset( $descriptor['type'] ) ) {
481 $class = static::$typeMappings[$descriptor['type']];
482 $descriptor['class'] = $class;
488 throw new MWException( "Descriptor with no class for $fieldname: "
489 . print_r( $descriptor, true ) );
496 * Initialise a new Object for the field
498 * @param string $fieldname Name of the field
499 * @param array $descriptor Input Descriptor, as described
500 * in the class documentation
501 * @param HTMLForm|null $parent Parent instance of HTMLForm
503 * @throws MWException
504 * @return HTMLFormField Instance of a subclass of HTMLFormField
506 public static function loadInputFromParameters( $fieldname, $descriptor,
507 HTMLForm
$parent = null
509 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
511 $descriptor['fieldname'] = $fieldname;
513 $descriptor['parent'] = $parent;
516 # @todo This will throw a fatal error whenever someone try to use
517 # 'class' to feed a CSS class instead of 'cssclass'. Would be
518 # great to avoid the fatal error and show a nice error.
519 return new $class( $descriptor );
523 * Prepare form for submission.
525 * @warning When doing method chaining, that should be the very last
526 * method call before displayForm().
528 * @throws MWException
529 * @return HTMLForm $this for chaining calls (since 1.20)
531 public function prepareForm() {
532 # Check if we have the info we need
533 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
534 throw new MWException( 'You must call setTitle() on an HTMLForm' );
537 # Load data from the request.
539 $this->mFormIdentifier
=== null ||
540 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
544 $this->mFieldData
= [];
551 * Try submitting, with edit token check first
552 * @return Status|bool
554 public function tryAuthorizedSubmit() {
557 if ( $this->mFormIdentifier
=== null ) {
560 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
564 if ( $this->getMethod() !== 'post' ) {
565 $tokenOkay = true; // no session check needed
566 } elseif ( $this->getRequest()->wasPosted() ) {
567 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
568 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
569 // Session tokens for logged-out users have no security value.
570 // However, if the user gave one, check it in order to give a nice
571 // "session expired" error instead of "permission denied" or such.
572 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
578 if ( $tokenOkay && $identOkay ) {
579 $this->mWasSubmitted
= true;
580 $result = $this->trySubmit();
587 * The here's-one-I-made-earlier option: do the submission if
588 * posted, or display the form with or without funky validation
590 * @return bool|Status Whether submission was successful.
592 public function show() {
593 $this->prepareForm();
595 $result = $this->tryAuthorizedSubmit();
596 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
600 $this->displayForm( $result );
606 * Same as self::show with the difference, that the form will be
607 * added to the output, no matter, if the validation was good or not.
608 * @return bool|Status Whether submission was successful.
610 public function showAlways() {
611 $this->prepareForm();
613 $result = $this->tryAuthorizedSubmit();
615 $this->displayForm( $result );
621 * Validate all the fields, and call the submission callback
622 * function if everything is kosher.
623 * @throws MWException
624 * @return bool|string|array|Status
625 * - Bool true or a good Status object indicates success,
626 * - Bool false indicates no submission was attempted,
627 * - Anything else indicates failure. The value may be a fatal Status
628 * object, an HTML string, or an array of arrays (message keys and
629 * params) or strings (message keys)
631 public function trySubmit() {
633 $hoistedErrors = Status
::newGood();
634 if ( $this->mValidationErrorMessage
) {
635 foreach ( $this->mValidationErrorMessage
as $error ) {
636 $hoistedErrors->fatal( ...$error );
639 $hoistedErrors->fatal( 'htmlform-invalid-input' );
642 $this->mWasSubmitted
= true;
644 # Check for cancelled submission
645 foreach ( $this->mFlatFields
as $fieldname => $field ) {
646 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
649 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
650 $this->mWasSubmitted
= false;
655 # Check for validation
656 foreach ( $this->mFlatFields
as $fieldname => $field ) {
657 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
660 if ( $field->isHidden( $this->mFieldData
) ) {
663 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
664 if ( $res !== true ) {
666 if ( $res !== false && !$field->canDisplayErrors() ) {
667 if ( is_string( $res ) ) {
668 $hoistedErrors->fatal( 'rawmessage', $res );
670 $hoistedErrors->fatal( $res );
677 return $hoistedErrors;
680 $callback = $this->mSubmitCallback
;
681 if ( !is_callable( $callback ) ) {
682 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
683 'setSubmitCallback() to set one.' );
686 $data = $this->filterDataForSubmit( $this->mFieldData
);
688 $res = call_user_func( $callback, $data, $this );
689 if ( $res === false ) {
690 $this->mWasSubmitted
= false;
697 * Test whether the form was considered to have been submitted or not, i.e.
698 * whether the last call to tryAuthorizedSubmit or trySubmit returned
701 * This will return false until HTMLForm::tryAuthorizedSubmit or
702 * HTMLForm::trySubmit is called.
707 public function wasSubmitted() {
708 return $this->mWasSubmitted
;
712 * Set a callback to a function to do something with the form
713 * once it's been successfully validated.
715 * @param callable $cb The function will be passed the output from
716 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
717 * return as documented for HTMLForm::trySubmit
719 * @return HTMLForm $this for chaining calls (since 1.20)
721 public function setSubmitCallback( $cb ) {
722 $this->mSubmitCallback
= $cb;
728 * Set a message to display on a validation error.
730 * @param array $msg Array of valid inputs to wfMessage()
731 * (so each entry must itself be an array of arguments)
733 * @return HTMLForm $this for chaining calls (since 1.20)
735 public function setValidationErrorMessage( $msg ) {
736 $this->mValidationErrorMessage
= $msg;
742 * Set the introductory message, overwriting any existing message.
744 * @param string $msg Complete text of message to display
746 * @return HTMLForm $this for chaining calls (since 1.20)
748 public function setIntro( $msg ) {
749 $this->setPreText( $msg );
755 * Set the introductory message HTML, overwriting any existing message.
758 * @param string $msg Complete HTML of message to display
760 * @return HTMLForm $this for chaining calls (since 1.20)
762 public function setPreText( $msg ) {
769 * Add HTML to introductory message.
771 * @param string $msg Complete HTML of message to display
773 * @return HTMLForm $this for chaining calls (since 1.20)
775 public function addPreText( $msg ) {
782 * Get the introductory message HTML.
788 public function getPreText() {
793 * Add HTML to the header, inside the form.
795 * @param string $msg Additional HTML to display in header
796 * @param string|null $section The section to add the header to
798 * @return HTMLForm $this for chaining calls (since 1.20)
800 public function addHeaderText( $msg, $section = null ) {
801 if ( $section === null ) {
802 $this->mHeader
.= $msg;
804 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
805 $this->mSectionHeaders
[$section] = '';
807 $this->mSectionHeaders
[$section] .= $msg;
814 * Set header text, inside the form.
817 * @param string $msg Complete HTML of header to display
818 * @param string|null $section The section to add the header to
820 * @return HTMLForm $this for chaining calls (since 1.20)
822 public function setHeaderText( $msg, $section = null ) {
823 if ( $section === null ) {
824 $this->mHeader
= $msg;
826 $this->mSectionHeaders
[$section] = $msg;
835 * @param string|null $section The section to get the header text for
837 * @return string HTML
839 public function getHeaderText( $section = null ) {
840 if ( $section === null ) {
841 return $this->mHeader
;
843 return $this->mSectionHeaders
[$section] ??
'';
848 * Add footer text, inside the form.
850 * @param string $msg Complete text of message to display
851 * @param string|null $section The section to add the footer text to
853 * @return HTMLForm $this for chaining calls (since 1.20)
855 public function addFooterText( $msg, $section = null ) {
856 if ( $section === null ) {
857 $this->mFooter
.= $msg;
859 if ( !isset( $this->mSectionFooters
[$section] ) ) {
860 $this->mSectionFooters
[$section] = '';
862 $this->mSectionFooters
[$section] .= $msg;
869 * Set footer text, inside the form.
872 * @param string $msg Complete text of message to display
873 * @param string|null $section The section to add the footer text to
875 * @return HTMLForm $this for chaining calls (since 1.20)
877 public function setFooterText( $msg, $section = null ) {
878 if ( $section === null ) {
879 $this->mFooter
= $msg;
881 $this->mSectionFooters
[$section] = $msg;
890 * @param string|null $section The section to get the footer text for
894 public function getFooterText( $section = null ) {
895 if ( $section === null ) {
896 return $this->mFooter
;
898 return $this->mSectionFooters
[$section] ??
'';
903 * Add text to the end of the display.
905 * @param string $msg Complete text of message to display
907 * @return HTMLForm $this for chaining calls (since 1.20)
909 public function addPostText( $msg ) {
910 $this->mPost
.= $msg;
916 * Set text at the end of the display.
918 * @param string $msg Complete text of message to display
920 * @return HTMLForm $this for chaining calls (since 1.20)
922 public function setPostText( $msg ) {
929 * Add a hidden field to the output
931 * @param string $name Field name. This will be used exactly as entered
932 * @param string $value Field value
933 * @param array $attribs
935 * @return HTMLForm $this for chaining calls (since 1.20)
937 public function addHiddenField( $name, $value, array $attribs = [] ) {
938 $attribs +
= [ 'name' => $name ];
939 $this->mHiddenFields
[] = [ $value, $attribs ];
945 * Add an array of hidden fields to the output
949 * @param array $fields Associative array of fields to add;
950 * mapping names to their values
952 * @return HTMLForm $this for chaining calls
954 public function addHiddenFields( array $fields ) {
955 foreach ( $fields as $name => $value ) {
956 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
963 * Add a button to the form
965 * @since 1.27 takes an array as shown. Earlier versions accepted
966 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
968 * @note Custom labels ('label', 'label-message', 'label-raw') are not
969 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
970 * they will be served buttons using 'value' as the button label.
971 * @param array $data Data to define the button:
972 * - name: (string) Button name.
973 * - value: (string) Button value.
974 * - label-message: (string, optional) Button label message key to use
975 * instead of 'value'. Overrides 'label' and 'label-raw'.
976 * - label: (string, optional) Button label text to use instead of
977 * 'value'. Overrides 'label-raw'.
978 * - label-raw: (string, optional) Button label HTML to use instead of
980 * - id: (string, optional) DOM id for the button.
981 * - attribs: (array, optional) Additional HTML attributes.
982 * - flags: (string|string[], optional) OOUI flags.
983 * - framed: (boolean=true, optional) OOUI framed attribute.
984 * @return HTMLForm $this for chaining calls (since 1.20)
986 public function addButton( $data ) {
987 if ( !is_array( $data ) ) {
988 $args = func_get_args();
989 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
990 throw new InvalidArgumentException(
991 'Incorrect number of arguments for deprecated calling style'
997 'id' => $args[2] ??
null,
998 'attribs' => $args[3] ??
null,
1001 if ( !isset( $data['name'] ) ) {
1002 throw new InvalidArgumentException( 'A name is required' );
1004 if ( !isset( $data['value'] ) ) {
1005 throw new InvalidArgumentException( 'A value is required' );
1008 $this->mButtons
[] = $data +
[
1019 * Set the salt for the edit token.
1021 * Only useful when the method is "post".
1024 * @param string|array $salt Salt to use
1025 * @return HTMLForm $this For chaining calls
1027 public function setTokenSalt( $salt ) {
1028 $this->mTokenSalt
= $salt;
1034 * Display the form (sending to the context's OutputPage object), with an
1035 * appropriate error message or stack of messages, and any validation errors, etc.
1037 * @warning You should call prepareForm() before calling this function.
1038 * Moreover, when doing method chaining this should be the very last method
1039 * call just after prepareForm().
1041 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1043 * @return void Nothing, should be last call
1045 public function displayForm( $submitResult ) {
1046 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1050 * Returns the raw HTML generated by the form
1052 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1054 * @return string HTML
1055 * @return-taint escaped
1057 public function getHTML( $submitResult ) {
1058 # For good measure (it is the default)
1059 $this->getOutput()->preventClickjacking();
1060 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1061 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1064 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1065 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1066 . $this->getHeaderText()
1068 . $this->getHiddenFields()
1069 . $this->getButtons()
1070 . $this->getFooterText();
1072 $html = $this->wrapForm( $html );
1074 return '' . $this->mPre
. $html . $this->mPost
;
1078 * Enable collapsible mode, and set whether the form is collapsed by default.
1081 * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
1082 * @return HTMLForm $this for chaining calls
1084 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1085 $this->mCollapsible
= true;
1086 $this->mCollapsed
= $collapsedByDefault;
1091 * Get HTML attributes for the `<form>` tag.
1094 protected function getFormAttributes() {
1095 # Use multipart/form-data
1096 $encType = $this->mUseMultipart
1097 ?
'multipart/form-data'
1098 : 'application/x-www-form-urlencoded';
1101 'class' => 'mw-htmlform',
1102 'action' => $this->getAction(),
1103 'method' => $this->getMethod(),
1104 'enctype' => $encType,
1107 $attribs['id'] = $this->mId
;
1109 if ( is_string( $this->mAutocomplete
) ) {
1110 $attribs['autocomplete'] = $this->mAutocomplete
;
1112 if ( $this->mName
) {
1113 $attribs['name'] = $this->mName
;
1115 if ( $this->needsJSForHtml5FormValidation() ) {
1116 $attribs['novalidate'] = true;
1122 * Wrap the form innards in an actual "<form>" element
1124 * @param string $html HTML contents to wrap.
1126 * @return string Wrapped HTML.
1128 public function wrapForm( $html ) {
1129 # Include a <fieldset> wrapper for style, if requested.
1130 if ( $this->mWrapperLegend
!== false ) {
1131 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1132 $html = Xml
::fieldset( $legend, $html, $this->mWrapperAttributes
);
1135 return Html
::rawElement(
1137 $this->getFormAttributes(),
1143 * Get the hidden fields that should go inside the form.
1144 * @return string HTML.
1146 public function getHiddenFields() {
1148 if ( $this->mFormIdentifier
!== null ) {
1149 $html .= Html
::hidden(
1151 $this->mFormIdentifier
1154 if ( $this->getMethod() === 'post' ) {
1155 $html .= Html
::hidden(
1157 $this->getUser()->getEditToken( $this->mTokenSalt
),
1158 [ 'id' => 'wpEditToken' ]
1160 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1163 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1164 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1165 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1168 foreach ( $this->mHiddenFields
as $data ) {
1169 list( $value, $attribs ) = $data;
1170 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1177 * Get the submit and (potentially) reset buttons.
1178 * @return string HTML.
1180 public function getButtons() {
1182 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1184 if ( $this->mShowSubmit
) {
1187 if ( isset( $this->mSubmitID
) ) {
1188 $attribs['id'] = $this->mSubmitID
;
1191 if ( isset( $this->mSubmitName
) ) {
1192 $attribs['name'] = $this->mSubmitName
;
1195 if ( isset( $this->mSubmitTooltip
) ) {
1196 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1199 $attribs['class'] = [ 'mw-htmlform-submit' ];
1201 if ( $useMediaWikiUIEverywhere ) {
1202 foreach ( $this->mSubmitFlags
as $flag ) {
1203 $attribs['class'][] = 'mw-ui-' . $flag;
1205 $attribs['class'][] = 'mw-ui-button';
1208 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1211 if ( $this->mShowReset
) {
1212 $buttons .= Html
::element(
1216 'value' => $this->msg( 'htmlform-reset' )->text(),
1217 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1222 if ( $this->mShowCancel
) {
1223 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1224 if ( $target instanceof Title
) {
1225 $target = $target->getLocalURL();
1227 $buttons .= Html
::element(
1230 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1233 $this->msg( 'cancel' )->text()
1237 // IE<8 has bugs with <button>, so we'll need to avoid them.
1238 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1240 foreach ( $this->mButtons
as $button ) {
1243 'name' => $button['name'],
1244 'value' => $button['value']
1247 if ( isset( $button['label-message'] ) ) {
1248 $label = $this->getMessage( $button['label-message'] )->parse();
1249 } elseif ( isset( $button['label'] ) ) {
1250 $label = htmlspecialchars( $button['label'] );
1251 } elseif ( isset( $button['label-raw'] ) ) {
1252 $label = $button['label-raw'];
1254 $label = htmlspecialchars( $button['value'] );
1257 if ( $button['attribs'] ) {
1258 $attrs +
= $button['attribs'];
1261 if ( isset( $button['id'] ) ) {
1262 $attrs['id'] = $button['id'];
1265 if ( $useMediaWikiUIEverywhere ) {
1266 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1267 $attrs['class'][] = 'mw-ui-button';
1271 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1273 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1281 return Html
::rawElement( 'span',
1282 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1286 * Get the whole body of the form.
1289 public function getBody() {
1290 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1294 * Returns a formatted list of errors or warnings from the given elements.
1296 * @param string|array|Status $elements The set of errors/warnings to process.
1297 * @param string $elementsType Should warnings or errors be returned. This is meant
1298 * for Status objects, all other valid types are always considered as errors.
1301 public function getErrorsOrWarnings( $elements, $elementsType ) {
1302 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1303 throw new DomainException( $elementsType . ' is not a valid type.' );
1305 $elementstr = false;
1306 if ( $elements instanceof Status
) {
1307 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1308 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1309 if ( $status->isGood() ) {
1312 $elementstr = $this->getOutput()->parseAsInterface(
1313 $status->getWikiText()
1316 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1317 $elementstr = $this->formatErrors( $elements );
1318 } elseif ( $elementsType === 'error' ) {
1319 $elementstr = $elements;
1323 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1328 * Format a stack of error messages into a single HTML string
1330 * @param array $errors Array of message keys/values
1332 * @return string HTML, a "<ul>" list of errors
1334 public function formatErrors( $errors ) {
1337 foreach ( $errors as $error ) {
1338 $errorstr .= Html
::rawElement(
1341 $this->getMessage( $error )->parse()
1345 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1351 * Set the text for the submit button
1353 * @param string $t Plaintext
1355 * @return HTMLForm $this for chaining calls (since 1.20)
1357 public function setSubmitText( $t ) {
1358 $this->mSubmitText
= $t;
1364 * Identify that the submit button in the form has a destructive action
1367 * @return HTMLForm $this for chaining calls (since 1.28)
1369 public function setSubmitDestructive() {
1370 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1376 * Set the text for the submit button to a message
1379 * @param string|Message $msg Message key or Message object
1381 * @return HTMLForm $this for chaining calls (since 1.20)
1383 public function setSubmitTextMsg( $msg ) {
1384 if ( !$msg instanceof Message
) {
1385 $msg = $this->msg( $msg );
1387 $this->setSubmitText( $msg->text() );
1393 * Get the text for the submit button, either customised or a default.
1396 public function getSubmitText() {
1397 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1401 * @param string $name Submit button name
1403 * @return HTMLForm $this for chaining calls (since 1.20)
1405 public function setSubmitName( $name ) {
1406 $this->mSubmitName
= $name;
1412 * @param string $name Tooltip for the submit button
1414 * @return HTMLForm $this for chaining calls (since 1.20)
1416 public function setSubmitTooltip( $name ) {
1417 $this->mSubmitTooltip
= $name;
1423 * Set the id for the submit button.
1427 * @todo FIXME: Integrity of $t is *not* validated
1428 * @return HTMLForm $this for chaining calls (since 1.20)
1430 public function setSubmitID( $t ) {
1431 $this->mSubmitID
= $t;
1437 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1438 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1441 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1442 * was submitted, and not attempt to validate the other ones.
1443 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1444 * HTMLForm to distinguish between the initial page view and a form submission with all
1445 * checkboxes or select options unchecked.
1448 * @param string $ident
1451 public function setFormIdentifier( $ident ) {
1452 $this->mFormIdentifier
= $ident;
1458 * Stop a default submit button being shown for this form. This implies that an
1459 * alternate submit method must be provided manually.
1463 * @param bool $suppressSubmit Set to false to re-enable the button again
1465 * @return HTMLForm $this for chaining calls
1467 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1468 $this->mShowSubmit
= !$suppressSubmit;
1474 * Show a cancel button (or prevent it). The button is not shown by default.
1476 * @return HTMLForm $this for chaining calls
1479 public function showCancel( $show = true ) {
1480 $this->mShowCancel
= $show;
1485 * Sets the target where the user is redirected to after clicking cancel.
1486 * @param Title|string $target Target as a Title object or an URL
1487 * @return HTMLForm $this for chaining calls
1490 public function setCancelTarget( $target ) {
1491 $this->mCancelTarget
= $target;
1496 * Set the id of the \<table\> or outermost \<div\> element.
1500 * @param string $id New value of the id attribute, or "" to remove
1502 * @return HTMLForm $this for chaining calls
1504 public function setTableId( $id ) {
1505 $this->mTableId
= $id;
1511 * @param string $id DOM id for the form
1513 * @return HTMLForm $this for chaining calls (since 1.20)
1515 public function setId( $id ) {
1522 * @param string $name 'name' attribute for the form
1523 * @return HTMLForm $this for chaining calls
1525 public function setName( $name ) {
1526 $this->mName
= $name;
1532 * Prompt the whole form to be wrapped in a "<fieldset>", with
1533 * this text as its "<legend>" element.
1535 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1536 * If true, a wrapper will be displayed, but no legend.
1537 * If a string, a wrapper will be displayed with that string as a legend.
1538 * The string will be escaped before being output (this doesn't support HTML).
1540 * @return HTMLForm $this for chaining calls (since 1.20)
1542 public function setWrapperLegend( $legend ) {
1543 $this->mWrapperLegend
= $legend;
1549 * For internal use only. Use is discouraged, and should only be used where
1550 * support for gadgets/user scripts is warranted.
1551 * @param array $attributes
1553 * @return HTMLForm $this for chaining calls
1555 public function setWrapperAttributes( $attributes ) {
1556 $this->mWrapperAttributes
= $attributes;
1562 * Prompt the whole form to be wrapped in a "<fieldset>", with
1563 * this message as its "<legend>" element.
1566 * @param string|Message $msg Message key or Message object
1568 * @return HTMLForm $this for chaining calls (since 1.20)
1570 public function setWrapperLegendMsg( $msg ) {
1571 if ( !$msg instanceof Message
) {
1572 $msg = $this->msg( $msg );
1574 $this->setWrapperLegend( $msg->text() );
1580 * Set the prefix for various default messages
1581 * @todo Currently only used for the "<fieldset>" legend on forms
1582 * with multiple sections; should be used elsewhere?
1586 * @return HTMLForm $this for chaining calls (since 1.20)
1588 public function setMessagePrefix( $p ) {
1589 $this->mMessagePrefix
= $p;
1595 * Set the title for form submission
1597 * @param Title $t Title of page the form is on/should be posted to
1599 * @return HTMLForm $this for chaining calls (since 1.20)
1601 public function setTitle( $t ) {
1611 public function getTitle() {
1612 return $this->mTitle
=== false
1613 ?
$this->getContext()->getTitle()
1618 * Set the method used to submit the form
1620 * @param string $method
1622 * @return HTMLForm $this for chaining calls (since 1.20)
1624 public function setMethod( $method = 'post' ) {
1625 $this->mMethod
= strtolower( $method );
1631 * @return string Always lowercase
1633 public function getMethod() {
1634 return $this->mMethod
;
1638 * Wraps the given $section into an user-visible fieldset.
1640 * @param string $legend Legend text for the fieldset
1641 * @param string $section The section content in plain Html
1642 * @param array $attributes Additional attributes for the fieldset
1643 * @param bool $isRoot Section is at the root of the tree
1644 * @return string The fieldset's Html
1646 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1647 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1653 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1655 * @param string $sectionName ID attribute of the "<table>" tag for this
1656 * section, ignored if empty.
1657 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1658 * each subsection, ignored if empty.
1659 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1660 * @throws LogicException When called on uninitialized field data, e.g. When
1661 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1666 public function displaySection( $fields,
1668 $fieldsetIDPrefix = '',
1669 &$hasUserVisibleFields = false
1671 if ( $this->mFieldData
=== null ) {
1672 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1673 . 'You probably called displayForm() without calling prepareForm() first.' );
1676 $displayFormat = $this->getDisplayFormat();
1679 $subsectionHtml = '';
1682 // Conveniently, PHP method names are case-insensitive.
1683 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1684 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1686 foreach ( $fields as $key => $value ) {
1687 if ( $value instanceof HTMLFormField
) {
1688 $v = array_key_exists( $key, $this->mFieldData
)
1689 ?
$this->mFieldData
[$key]
1690 : $value->getDefault();
1692 $retval = $value->$getFieldHtmlMethod( $v );
1694 // check, if the form field should be added to
1696 if ( $value->hasVisibleOutput() ) {
1699 $labelValue = trim( $value->getLabel() );
1700 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
1704 $hasUserVisibleFields = true;
1706 } elseif ( is_array( $value ) ) {
1707 $subsectionHasVisibleFields = false;
1709 $this->displaySection( $value,
1711 "$fieldsetIDPrefix$key-",
1712 $subsectionHasVisibleFields );
1715 if ( $subsectionHasVisibleFields === true ) {
1716 // Display the section with various niceties.
1717 $hasUserVisibleFields = true;
1719 $legend = $this->getLegend( $key );
1721 $section = $this->getHeaderText( $key ) .
1723 $this->getFooterText( $key );
1726 if ( $fieldsetIDPrefix ) {
1727 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1729 $subsectionHtml .= $this->wrapFieldSetSection(
1730 $legend, $section, $attributes, $fields === $this->mFieldTree
1733 // Just return the inputs, nothing fancy.
1734 $subsectionHtml .= $section;
1739 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1741 if ( $subsectionHtml ) {
1742 if ( $this->mSubSectionBeforeFields
) {
1743 return $subsectionHtml . "\n" . $html;
1745 return $html . "\n" . $subsectionHtml;
1753 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1754 * @param array $fieldsHtml
1755 * @param string $sectionName
1756 * @param bool $anyFieldHasLabel
1757 * @return string HTML
1759 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1760 if ( !$fieldsHtml ) {
1761 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1762 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1766 $displayFormat = $this->getDisplayFormat();
1767 $html = implode( '', $fieldsHtml );
1769 if ( $displayFormat === 'raw' ) {
1775 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1776 $classes[] = 'mw-htmlform-nolabel';
1780 'class' => implode( ' ', $classes ),
1783 if ( $sectionName ) {
1784 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1787 if ( $displayFormat === 'table' ) {
1788 return Html
::rawElement( 'table',
1790 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1791 } elseif ( $displayFormat === 'inline' ) {
1792 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1794 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1799 * Construct the form fields from the Descriptor array
1801 public function loadData() {
1804 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1805 $request = $this->getRequest();
1806 if ( $field->skipLoadData( $request ) ) {
1808 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1809 $fieldData[$fieldname] = $field->getDefault();
1811 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1816 foreach ( $fieldData as $name => &$value ) {
1817 $field = $this->mFlatFields
[$name];
1818 $value = $field->filter( $value, $this->mFlatFields
);
1821 $this->mFieldData
= $fieldData;
1825 * Stop a reset button being shown for this form
1827 * @param bool $suppressReset Set to false to re-enable the button again
1829 * @return HTMLForm $this for chaining calls (since 1.20)
1831 public function suppressReset( $suppressReset = true ) {
1832 $this->mShowReset
= !$suppressReset;
1838 * Overload this if you want to apply special filtration routines
1839 * to the form as a whole, after it's submitted but before it's
1842 * @param array $data
1846 public function filterDataForSubmit( $data ) {
1851 * Get a string to go in the "<legend>" of a section fieldset.
1852 * Override this if you want something more complicated.
1854 * @param string $key
1856 * @return string Plain text (not HTML-escaped)
1858 public function getLegend( $key ) {
1859 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1863 * Set the value for the action attribute of the form.
1864 * When set to false (which is the default state), the set title is used.
1868 * @param string|bool $action
1870 * @return HTMLForm $this for chaining calls (since 1.20)
1872 public function setAction( $action ) {
1873 $this->mAction
= $action;
1879 * Get the value for the action attribute of the form.
1885 public function getAction() {
1886 // If an action is alredy provided, return it
1887 if ( $this->mAction
!== false ) {
1888 return $this->mAction
;
1891 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1892 // Check whether we are in GET mode and the ArticlePath contains a "?"
1893 // meaning that getLocalURL() would return something like "index.php?title=...".
1894 // As browser remove the query string before submitting GET forms,
1895 // it means that the title would be lost. In such case use wfScript() instead
1896 // and put title in an hidden field (see getHiddenFields()).
1897 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1901 return $this->getTitle()->getLocalURL();
1905 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1906 * When set to null (which is the default state), the attribute get not set.
1910 * @param string|null $autocomplete
1912 * @return HTMLForm $this for chaining calls
1914 public function setAutocomplete( $autocomplete ) {
1915 $this->mAutocomplete
= $autocomplete;
1921 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1922 * name + parameters array) into a Message.
1923 * @param mixed $value
1926 protected function getMessage( $value ) {
1927 return Message
::newFromSpecifier( $value )->setContext( $this );
1931 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1932 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1933 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1934 * agent has JavaScript support, in htmlform.js.
1939 public function needsJSForHtml5FormValidation() {
1940 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1941 if ( $field->needsJSForHtml5FormValidation() ) {