4 * HTML form generation and submission handling.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\ObjectFactory
;
27 * Object handling generic submission, CSRF protection, layout and
28 * other logic for UI forms. in a reusable manner.
30 * In order to generate the form, the HTMLForm object takes an array
31 * structure detailing the form fields available. Each element of the
32 * array is a basic property-list, including the type of field, the
33 * label it is to be given in the form, callbacks for validation and
34 * 'filtering', and other pertinent information.
36 * Field types are implemented as subclasses of the generic HTMLFormField
37 * object, and typically implement at least getInputHTML, which generates
38 * the HTML for the input field to be placed in the table.
40 * You can find extensive documentation on the www.mediawiki.org wiki:
41 * - https://www.mediawiki.org/wiki/HTMLForm
42 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
44 * The constructor input is an associative array of $fieldname => $info,
45 * where $info is an Associative Array with any of the following:
47 * 'class' -- the subclass of HTMLFormField that will be used
48 * to create the object. *NOT* the CSS class!
49 * 'type' -- roughly translates into the <select> type attribute.
50 * if 'class' is not specified, this is used as a map
51 * through HTMLForm::$typeMappings to get the class name.
52 * 'default' -- default value when the form is displayed
53 * 'nodata' -- if set (to any value, which casts to true), the data
54 * for this field will not be loaded from the actual request. Instead,
55 * always the default data is set as the value of this field.
56 * 'id' -- HTML id attribute
57 * 'cssclass' -- CSS class
58 * 'csshelpclass' -- CSS class used to style help text
59 * 'dir' -- Direction of the element.
60 * 'options' -- associative array mapping raw text labels to values.
61 * Some field types support multi-level arrays.
62 * Overwrites 'options-message'.
63 * 'options-messages' -- associative array mapping message keys to values.
64 * Some field types support multi-level arrays.
65 * Overwrites 'options' and 'options-message'.
66 * 'options-message' -- message key or object to be parsed to extract the list of
67 * options (like 'ipbreason-dropdown').
68 * 'label-message' -- message key or object for a message to use as the label.
69 * can be an array of msg key and then parameters to
71 * 'label' -- alternatively, a raw text message. Overridden by
73 * 'help' -- message text for a message to use as a help text.
74 * 'help-message' -- message key or object for a message to use as a help text.
75 * can be an array of msg key and then parameters to
77 * Overwrites 'help-messages' and 'help'.
78 * 'help-messages' -- array of message keys/objects. As above, each item can
79 * be an array of msg key and then parameters.
81 * 'help-inline' -- Whether help text (defined using options above) will be shown
82 * inline after the input field, rather than in a popup.
83 * Defaults to true. Only used by OOUI form fields.
84 * 'required' -- passed through to the object, indicating that it
85 * is a required field.
86 * 'size' -- the length of text fields
87 * 'filter-callback' -- a function name to give you the chance to
88 * massage the inputted value before it's processed.
89 * @see HTMLFormField::filter()
90 * 'validation-callback' -- a function name to give you the chance
91 * to impose extra validation on the field input.
92 * @see HTMLFormField::validate()
93 * 'name' -- By default, the 'name' attribute of the input field
94 * is "wp{$fieldname}". If you want a different name
95 * (eg one without the "wp" prefix), specify it here and
96 * it will be used without modification.
97 * 'hide-if' -- expression given as an array stating when the field
98 * should be hidden. The first array value has to be the
99 * expression's logic operator. Supported expressions:
101 * [ 'NOT', array $expression ]
102 * To hide a field if a given expression is not true.
104 * [ '===', string $fieldName, string $value ]
105 * To hide a field if another field identified by
106 * $field has the value $value.
108 * [ '!==', string $fieldName, string $value ]
109 * Same as [ 'NOT', [ '===', $fieldName, $value ]
110 * 'OR', 'AND', 'NOR', 'NAND'
111 * [ 'XXX', array $expression1, ..., array $expressionN ]
112 * To hide a field if one or more (OR), all (AND),
113 * neither (NOR) or not all (NAND) given expressions
114 * are evaluated as true.
115 * The expressions will be given to a JavaScript frontend
116 * module which will continually update the field's
119 * Since 1.20, you can chain mutators to ease the form generation:
122 * $form = new HTMLForm( $someFields );
123 * $form->setMethod( 'get' )
124 * ->setWrapperLegendMsg( 'message-key' )
126 * ->displayForm( '' );
128 * Note that you will have prepareForm and displayForm at the end. Other
129 * methods call done after that would simply not be part of the form :(
131 * @todo Document 'section' / 'subsection' stuff
133 class HTMLForm
extends ContextSource
{
134 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
135 public static $typeMappings = [
136 'api' => HTMLApiField
::class,
137 'text' => HTMLTextField
::class,
138 'textwithbutton' => HTMLTextFieldWithButton
::class,
139 'textarea' => HTMLTextAreaField
::class,
140 'select' => HTMLSelectField
::class,
141 'combobox' => HTMLComboboxField
::class,
142 'radio' => HTMLRadioField
::class,
143 'multiselect' => HTMLMultiSelectField
::class,
144 'limitselect' => HTMLSelectLimitField
::class,
145 'check' => HTMLCheckField
::class,
146 'toggle' => HTMLCheckField
::class,
147 'int' => HTMLIntField
::class,
148 'float' => HTMLFloatField
::class,
149 'info' => HTMLInfoField
::class,
150 'selectorother' => HTMLSelectOrOtherField
::class,
151 'selectandother' => HTMLSelectAndOtherField
::class,
152 'namespaceselect' => HTMLSelectNamespace
::class,
153 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton
::class,
154 'tagfilter' => HTMLTagFilter
::class,
155 'sizefilter' => HTMLSizeFilterField
::class,
156 'submit' => HTMLSubmitField
::class,
157 'hidden' => HTMLHiddenField
::class,
158 'edittools' => HTMLEditTools
::class,
159 'checkmatrix' => HTMLCheckMatrix
::class,
160 'cloner' => HTMLFormFieldCloner
::class,
161 'autocompleteselect' => HTMLAutoCompleteSelectField
::class,
162 'language' => HTMLSelectLanguageField
::class,
163 'date' => HTMLDateTimeField
::class,
164 'time' => HTMLDateTimeField
::class,
165 'datetime' => HTMLDateTimeField
::class,
166 'expiry' => HTMLExpiryField
::class,
167 // HTMLTextField will output the correct type="" attribute automagically.
168 // There are about four zillion other HTML5 input types, like range, but
169 // we don't use those at the moment, so no point in adding all of them.
170 'email' => HTMLTextField
::class,
171 'password' => HTMLTextField
::class,
172 'url' => HTMLTextField
::class,
173 'title' => HTMLTitleTextField
::class,
174 'user' => HTMLUserTextField
::class,
175 'usersmultiselect' => HTMLUsersMultiselectField
::class,
176 'titlesmultiselect' => HTMLTitlesMultiselectField
::class,
177 'namespacesmultiselect' => HTMLNamespacesMultiselectField
::class,
182 protected $mMessagePrefix;
184 /** @var HTMLFormField[] */
185 protected $mFlatFields;
187 protected $mFieldTree;
188 protected $mShowReset = false;
189 protected $mShowSubmit = true;
190 protected $mSubmitFlags = [ 'primary', 'progressive' ];
191 protected $mShowCancel = false;
192 protected $mCancelTarget;
194 protected $mSubmitCallback;
195 protected $mValidationErrorMessage;
197 protected $mPre = '';
198 protected $mHeader = '';
199 protected $mFooter = '';
200 protected $mSectionHeaders = [];
201 protected $mSectionFooters = [];
202 protected $mPost = '';
205 protected $mTableId = '';
207 protected $mSubmitID;
208 protected $mSubmitName;
209 protected $mSubmitText;
210 protected $mSubmitTooltip;
212 protected $mFormIdentifier;
214 protected $mMethod = 'post';
215 protected $mWasSubmitted = false;
218 * Form action URL. false means we will use the URL to set Title
222 protected $mAction = false;
225 * Whether the form can be collapsed
229 protected $mCollapsible = false;
232 * Whether the form is collapsed by default
236 protected $mCollapsed = false;
239 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
243 protected $mAutocomplete = null;
245 protected $mUseMultipart = false;
246 protected $mHiddenFields = [];
247 protected $mButtons = [];
249 protected $mWrapperLegend = false;
250 protected $mWrapperAttributes = [];
253 * Salt for the edit token.
256 protected $mTokenSalt = '';
259 * If true, sections that contain both fields and subsections will
260 * render their subsections before their fields.
262 * Subclasses may set this to false to render subsections after fields
265 protected $mSubSectionBeforeFields = true;
268 * Format in which to display form. For viable options,
269 * @see $availableDisplayFormats
272 protected $displayFormat = 'table';
275 * Available formats in which to display the form
278 protected $availableDisplayFormats = [
286 * Available formats in which to display the form
289 protected $availableSubclassDisplayFormats = [
295 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
297 * @param string $displayFormat
298 * @param mixed $arguments,... Additional arguments to pass to the constructor.
301 public static function factory( $displayFormat/*, $arguments...*/ ) {
302 $arguments = func_get_args();
303 array_shift( $arguments );
305 switch ( $displayFormat ) {
307 return ObjectFactory
::constructClassInstance( VFormHTMLForm
::class, $arguments );
309 return ObjectFactory
::constructClassInstance( OOUIHTMLForm
::class, $arguments );
311 /** @var HTMLForm $form */
312 $form = ObjectFactory
::constructClassInstance( self
::class, $arguments );
313 $form->setDisplayFormat( $displayFormat );
319 * Build a new HTMLForm from an array of field attributes
321 * @param array $descriptor Array of Field constructs, as described above
322 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
323 * Obviates the need to call $form->setTitle()
324 * @param string $messagePrefix A prefix to go in front of default messages
326 public function __construct( $descriptor, /*IContextSource*/ $context = null,
329 if ( $context instanceof IContextSource
) {
330 $this->setContext( $context );
331 $this->mTitle
= false; // We don't need them to set a title
332 $this->mMessagePrefix
= $messagePrefix;
333 } elseif ( $context === null && $messagePrefix !== '' ) {
334 $this->mMessagePrefix
= $messagePrefix;
335 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
337 // it's actually $messagePrefix
338 $this->mMessagePrefix
= $context;
341 // Evil hack for mobile :(
343 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
344 && $this->displayFormat
=== 'table'
346 $this->displayFormat
= 'div';
349 // Expand out into a tree.
350 $loadedDescriptor = [];
351 $this->mFlatFields
= [];
353 foreach ( $descriptor as $fieldname => $info ) {
354 $section = $info['section'] ??
'';
356 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
357 $this->mUseMultipart
= true;
360 $field = static::loadInputFromParameters( $fieldname, $info, $this );
362 $setSection =& $loadedDescriptor;
364 foreach ( explode( '/', $section ) as $newName ) {
365 if ( !isset( $setSection[$newName] ) ) {
366 $setSection[$newName] = [];
369 $setSection =& $setSection[$newName];
373 $setSection[$fieldname] = $field;
374 $this->mFlatFields
[$fieldname] = $field;
377 $this->mFieldTree
= $loadedDescriptor;
381 * @param string $fieldname
384 public function hasField( $fieldname ) {
385 return isset( $this->mFlatFields
[$fieldname] );
389 * @param string $fieldname
390 * @return HTMLFormField
391 * @throws DomainException on invalid field name
393 public function getField( $fieldname ) {
394 if ( !$this->hasField( $fieldname ) ) {
395 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
397 return $this->mFlatFields
[$fieldname];
401 * Set format in which to display the form
403 * @param string $format The name of the format to use, must be one of
404 * $this->availableDisplayFormats
406 * @throws MWException
408 * @return HTMLForm $this for chaining calls (since 1.20)
410 public function setDisplayFormat( $format ) {
412 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
413 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
415 throw new MWException( 'Cannot change display format after creation, ' .
416 'use HTMLForm::factory() instead' );
419 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
420 throw new MWException( 'Display format must be one of ' .
423 $this->availableDisplayFormats
,
424 $this->availableSubclassDisplayFormats
430 // Evil hack for mobile :(
431 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
435 $this->displayFormat
= $format;
441 * Getter for displayFormat
445 public function getDisplayFormat() {
446 return $this->displayFormat
;
450 * Get the HTMLFormField subclass for this descriptor.
452 * The descriptor can be passed either 'class' which is the name of
453 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
454 * This makes sure the 'class' is always set, and also is returned by
455 * this function for ease.
459 * @param string $fieldname Name of the field
460 * @param array &$descriptor Input Descriptor, as described above
462 * @throws MWException
463 * @return string Name of a HTMLFormField subclass
465 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
466 if ( isset( $descriptor['class'] ) ) {
467 $class = $descriptor['class'];
468 } elseif ( isset( $descriptor['type'] ) ) {
469 $class = static::$typeMappings[$descriptor['type']];
470 $descriptor['class'] = $class;
476 throw new MWException( "Descriptor with no class for $fieldname: "
477 . print_r( $descriptor, true ) );
484 * Initialise a new Object for the field
486 * @param string $fieldname Name of the field
487 * @param array $descriptor Input Descriptor, as described above
488 * @param HTMLForm|null $parent Parent instance of HTMLForm
490 * @throws MWException
491 * @return HTMLFormField Instance of a subclass of HTMLFormField
493 public static function loadInputFromParameters( $fieldname, $descriptor,
494 HTMLForm
$parent = null
496 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
498 $descriptor['fieldname'] = $fieldname;
500 $descriptor['parent'] = $parent;
503 # @todo This will throw a fatal error whenever someone try to use
504 # 'class' to feed a CSS class instead of 'cssclass'. Would be
505 # great to avoid the fatal error and show a nice error.
506 return new $class( $descriptor );
510 * Prepare form for submission.
512 * @warning When doing method chaining, that should be the very last
513 * method call before displayForm().
515 * @throws MWException
516 * @return HTMLForm $this for chaining calls (since 1.20)
518 public function prepareForm() {
519 # Check if we have the info we need
520 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
521 throw new MWException( 'You must call setTitle() on an HTMLForm' );
524 # Load data from the request.
526 $this->mFormIdentifier
=== null ||
527 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
531 $this->mFieldData
= [];
538 * Try submitting, with edit token check first
539 * @return Status|bool
541 public function tryAuthorizedSubmit() {
544 if ( $this->mFormIdentifier
=== null ) {
547 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
551 if ( $this->getMethod() !== 'post' ) {
552 $tokenOkay = true; // no session check needed
553 } elseif ( $this->getRequest()->wasPosted() ) {
554 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
555 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
556 // Session tokens for logged-out users have no security value.
557 // However, if the user gave one, check it in order to give a nice
558 // "session expired" error instead of "permission denied" or such.
559 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
565 if ( $tokenOkay && $identOkay ) {
566 $this->mWasSubmitted
= true;
567 $result = $this->trySubmit();
574 * The here's-one-I-made-earlier option: do the submission if
575 * posted, or display the form with or without funky validation
577 * @return bool|Status Whether submission was successful.
579 public function show() {
580 $this->prepareForm();
582 $result = $this->tryAuthorizedSubmit();
583 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
587 $this->displayForm( $result );
593 * Same as self::show with the difference, that the form will be
594 * added to the output, no matter, if the validation was good or not.
595 * @return bool|Status Whether submission was successful.
597 public function showAlways() {
598 $this->prepareForm();
600 $result = $this->tryAuthorizedSubmit();
602 $this->displayForm( $result );
608 * Validate all the fields, and call the submission callback
609 * function if everything is kosher.
610 * @throws MWException
611 * @return bool|string|array|Status
612 * - Bool true or a good Status object indicates success,
613 * - Bool false indicates no submission was attempted,
614 * - Anything else indicates failure. The value may be a fatal Status
615 * object, an HTML string, or an array of arrays (message keys and
616 * params) or strings (message keys)
618 public function trySubmit() {
620 $hoistedErrors = Status
::newGood();
621 if ( $this->mValidationErrorMessage
) {
622 foreach ( $this->mValidationErrorMessage
as $error ) {
623 $hoistedErrors->fatal( ...$error );
626 $hoistedErrors->fatal( 'htmlform-invalid-input' );
629 $this->mWasSubmitted
= true;
631 # Check for cancelled submission
632 foreach ( $this->mFlatFields
as $fieldname => $field ) {
633 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
636 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
637 $this->mWasSubmitted
= false;
642 # Check for validation
643 foreach ( $this->mFlatFields
as $fieldname => $field ) {
644 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
647 if ( $field->isHidden( $this->mFieldData
) ) {
650 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
651 if ( $res !== true ) {
653 if ( $res !== false && !$field->canDisplayErrors() ) {
654 if ( is_string( $res ) ) {
655 $hoistedErrors->fatal( 'rawmessage', $res );
657 $hoistedErrors->fatal( $res );
664 return $hoistedErrors;
667 $callback = $this->mSubmitCallback
;
668 if ( !is_callable( $callback ) ) {
669 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
670 'setSubmitCallback() to set one.' );
673 $data = $this->filterDataForSubmit( $this->mFieldData
);
675 $res = call_user_func( $callback, $data, $this );
676 if ( $res === false ) {
677 $this->mWasSubmitted
= false;
684 * Test whether the form was considered to have been submitted or not, i.e.
685 * whether the last call to tryAuthorizedSubmit or trySubmit returned
688 * This will return false until HTMLForm::tryAuthorizedSubmit or
689 * HTMLForm::trySubmit is called.
694 public function wasSubmitted() {
695 return $this->mWasSubmitted
;
699 * Set a callback to a function to do something with the form
700 * once it's been successfully validated.
702 * @param callable $cb The function will be passed the output from
703 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
704 * return as documented for HTMLForm::trySubmit
706 * @return HTMLForm $this for chaining calls (since 1.20)
708 public function setSubmitCallback( $cb ) {
709 $this->mSubmitCallback
= $cb;
715 * Set a message to display on a validation error.
717 * @param array $msg Array of valid inputs to wfMessage()
718 * (so each entry must itself be an array of arguments)
720 * @return HTMLForm $this for chaining calls (since 1.20)
722 public function setValidationErrorMessage( $msg ) {
723 $this->mValidationErrorMessage
= $msg;
729 * Set the introductory message, overwriting any existing message.
731 * @param string $msg Complete text of message to display
733 * @return HTMLForm $this for chaining calls (since 1.20)
735 public function setIntro( $msg ) {
736 $this->setPreText( $msg );
742 * Set the introductory message HTML, overwriting any existing message.
745 * @param string $msg Complete HTML of message to display
747 * @return HTMLForm $this for chaining calls (since 1.20)
749 public function setPreText( $msg ) {
756 * Add HTML to introductory message.
758 * @param string $msg Complete HTML of message to display
760 * @return HTMLForm $this for chaining calls (since 1.20)
762 public function addPreText( $msg ) {
769 * Get the introductory message HTML.
775 public function getPreText() {
780 * Add HTML to the header, inside the form.
782 * @param string $msg Additional HTML to display in header
783 * @param string|null $section The section to add the header to
785 * @return HTMLForm $this for chaining calls (since 1.20)
787 public function addHeaderText( $msg, $section = null ) {
788 if ( $section === null ) {
789 $this->mHeader
.= $msg;
791 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
792 $this->mSectionHeaders
[$section] = '';
794 $this->mSectionHeaders
[$section] .= $msg;
801 * Set header text, inside the form.
804 * @param string $msg Complete HTML of header to display
805 * @param string|null $section The section to add the header to
807 * @return HTMLForm $this for chaining calls (since 1.20)
809 public function setHeaderText( $msg, $section = null ) {
810 if ( $section === null ) {
811 $this->mHeader
= $msg;
813 $this->mSectionHeaders
[$section] = $msg;
822 * @param string|null $section The section to get the header text for
824 * @return string HTML
826 public function getHeaderText( $section = null ) {
827 if ( $section === null ) {
828 return $this->mHeader
;
830 return $this->mSectionHeaders
[$section] ??
'';
835 * Add footer text, inside the form.
837 * @param string $msg Complete text of message to display
838 * @param string|null $section The section to add the footer text to
840 * @return HTMLForm $this for chaining calls (since 1.20)
842 public function addFooterText( $msg, $section = null ) {
843 if ( $section === null ) {
844 $this->mFooter
.= $msg;
846 if ( !isset( $this->mSectionFooters
[$section] ) ) {
847 $this->mSectionFooters
[$section] = '';
849 $this->mSectionFooters
[$section] .= $msg;
856 * Set footer text, inside the form.
859 * @param string $msg Complete text of message to display
860 * @param string|null $section The section to add the footer text to
862 * @return HTMLForm $this for chaining calls (since 1.20)
864 public function setFooterText( $msg, $section = null ) {
865 if ( $section === null ) {
866 $this->mFooter
= $msg;
868 $this->mSectionFooters
[$section] = $msg;
877 * @param string|null $section The section to get the footer text for
881 public function getFooterText( $section = null ) {
882 if ( $section === null ) {
883 return $this->mFooter
;
885 return $this->mSectionFooters
[$section] ??
'';
890 * Add text to the end of the display.
892 * @param string $msg Complete text of message to display
894 * @return HTMLForm $this for chaining calls (since 1.20)
896 public function addPostText( $msg ) {
897 $this->mPost
.= $msg;
903 * Set text at 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 setPostText( $msg ) {
916 * Add a hidden field to the output
918 * @param string $name Field name. This will be used exactly as entered
919 * @param string $value Field value
920 * @param array $attribs
922 * @return HTMLForm $this for chaining calls (since 1.20)
924 public function addHiddenField( $name, $value, array $attribs = [] ) {
925 $attribs +
= [ 'name' => $name ];
926 $this->mHiddenFields
[] = [ $value, $attribs ];
932 * Add an array of hidden fields to the output
936 * @param array $fields Associative array of fields to add;
937 * mapping names to their values
939 * @return HTMLForm $this for chaining calls
941 public function addHiddenFields( array $fields ) {
942 foreach ( $fields as $name => $value ) {
943 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
950 * Add a button to the form
952 * @since 1.27 takes an array as shown. Earlier versions accepted
953 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
955 * @note Custom labels ('label', 'label-message', 'label-raw') are not
956 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
957 * they will be served buttons using 'value' as the button label.
958 * @param array $data Data to define the button:
959 * - name: (string) Button name.
960 * - value: (string) Button value.
961 * - label-message: (string, optional) Button label message key to use
962 * instead of 'value'. Overrides 'label' and 'label-raw'.
963 * - label: (string, optional) Button label text to use instead of
964 * 'value'. Overrides 'label-raw'.
965 * - label-raw: (string, optional) Button label HTML to use instead of
967 * - id: (string, optional) DOM id for the button.
968 * - attribs: (array, optional) Additional HTML attributes.
969 * - flags: (string|string[], optional) OOUI flags.
970 * - framed: (boolean=true, optional) OOUI framed attribute.
971 * @return HTMLForm $this for chaining calls (since 1.20)
973 public function addButton( $data ) {
974 if ( !is_array( $data ) ) {
975 $args = func_get_args();
976 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
977 throw new InvalidArgumentException(
978 'Incorrect number of arguments for deprecated calling style'
984 'id' => $args[2] ??
null,
985 'attribs' => $args[3] ??
null,
988 if ( !isset( $data['name'] ) ) {
989 throw new InvalidArgumentException( 'A name is required' );
991 if ( !isset( $data['value'] ) ) {
992 throw new InvalidArgumentException( 'A value is required' );
995 $this->mButtons
[] = $data +
[
1006 * Set the salt for the edit token.
1008 * Only useful when the method is "post".
1011 * @param string|array $salt Salt to use
1012 * @return HTMLForm $this For chaining calls
1014 public function setTokenSalt( $salt ) {
1015 $this->mTokenSalt
= $salt;
1021 * Display the form (sending to the context's OutputPage object), with an
1022 * appropriate error message or stack of messages, and any validation errors, etc.
1024 * @warning You should call prepareForm() before calling this function.
1025 * Moreover, when doing method chaining this should be the very last method
1026 * call just after prepareForm().
1028 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1030 * @return void Nothing, should be last call
1032 public function displayForm( $submitResult ) {
1033 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1037 * Returns the raw HTML generated by the form
1039 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1041 * @return string HTML
1042 * @return-taint escaped
1044 public function getHTML( $submitResult ) {
1045 # For good measure (it is the default)
1046 $this->getOutput()->preventClickjacking();
1047 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1048 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1051 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1052 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1053 . $this->getHeaderText()
1055 . $this->getHiddenFields()
1056 . $this->getButtons()
1057 . $this->getFooterText();
1059 $html = $this->wrapForm( $html );
1061 return '' . $this->mPre
. $html . $this->mPost
;
1065 * Set whether the HTML form can be collapsed.
1068 * @param bool $collapsedByDefault (optional) whether the form is collapsed by default
1069 * @return HTMLForm $this for chaining calls
1071 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1072 $this->mCollapsible
= true;
1073 $this->mCollapsed
= $collapsedByDefault;
1078 * Get HTML attributes for the `<form>` tag.
1081 protected function getFormAttributes() {
1082 # Use multipart/form-data
1083 $encType = $this->mUseMultipart
1084 ?
'multipart/form-data'
1085 : 'application/x-www-form-urlencoded';
1088 'class' => 'mw-htmlform',
1089 'action' => $this->getAction(),
1090 'method' => $this->getMethod(),
1091 'enctype' => $encType,
1094 $attribs['id'] = $this->mId
;
1096 if ( is_string( $this->mAutocomplete
) ) {
1097 $attribs['autocomplete'] = $this->mAutocomplete
;
1099 if ( $this->mName
) {
1100 $attribs['name'] = $this->mName
;
1102 if ( $this->needsJSForHtml5FormValidation() ) {
1103 $attribs['novalidate'] = true;
1109 * Wrap the form innards in an actual "<form>" element
1111 * @param string $html HTML contents to wrap.
1113 * @return string Wrapped HTML.
1115 public function wrapForm( $html ) {
1116 # Include a <fieldset> wrapper for style, if requested.
1117 if ( $this->mWrapperLegend
!== false ) {
1118 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1119 $html = Xml
::fieldset( $legend, $html, $this->mWrapperAttributes
);
1122 return Html
::rawElement(
1124 $this->getFormAttributes(),
1130 * Get the hidden fields that should go inside the form.
1131 * @return string HTML.
1133 public function getHiddenFields() {
1135 if ( $this->mFormIdentifier
!== null ) {
1136 $html .= Html
::hidden(
1138 $this->mFormIdentifier
1141 if ( $this->getMethod() === 'post' ) {
1142 $html .= Html
::hidden(
1144 $this->getUser()->getEditToken( $this->mTokenSalt
),
1145 [ 'id' => 'wpEditToken' ]
1147 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1150 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1151 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1152 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1155 foreach ( $this->mHiddenFields
as $data ) {
1156 list( $value, $attribs ) = $data;
1157 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1164 * Get the submit and (potentially) reset buttons.
1165 * @return string HTML.
1167 public function getButtons() {
1169 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1171 if ( $this->mShowSubmit
) {
1174 if ( isset( $this->mSubmitID
) ) {
1175 $attribs['id'] = $this->mSubmitID
;
1178 if ( isset( $this->mSubmitName
) ) {
1179 $attribs['name'] = $this->mSubmitName
;
1182 if ( isset( $this->mSubmitTooltip
) ) {
1183 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1186 $attribs['class'] = [ 'mw-htmlform-submit' ];
1188 if ( $useMediaWikiUIEverywhere ) {
1189 foreach ( $this->mSubmitFlags
as $flag ) {
1190 $attribs['class'][] = 'mw-ui-' . $flag;
1192 $attribs['class'][] = 'mw-ui-button';
1195 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1198 if ( $this->mShowReset
) {
1199 $buttons .= Html
::element(
1203 'value' => $this->msg( 'htmlform-reset' )->text(),
1204 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1209 if ( $this->mShowCancel
) {
1210 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1211 if ( $target instanceof Title
) {
1212 $target = $target->getLocalURL();
1214 $buttons .= Html
::element(
1217 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1220 $this->msg( 'cancel' )->text()
1224 // IE<8 has bugs with <button>, so we'll need to avoid them.
1225 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1227 foreach ( $this->mButtons
as $button ) {
1230 'name' => $button['name'],
1231 'value' => $button['value']
1234 if ( isset( $button['label-message'] ) ) {
1235 $label = $this->getMessage( $button['label-message'] )->parse();
1236 } elseif ( isset( $button['label'] ) ) {
1237 $label = htmlspecialchars( $button['label'] );
1238 } elseif ( isset( $button['label-raw'] ) ) {
1239 $label = $button['label-raw'];
1241 $label = htmlspecialchars( $button['value'] );
1244 if ( $button['attribs'] ) {
1245 $attrs +
= $button['attribs'];
1248 if ( isset( $button['id'] ) ) {
1249 $attrs['id'] = $button['id'];
1252 if ( $useMediaWikiUIEverywhere ) {
1253 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1254 $attrs['class'][] = 'mw-ui-button';
1258 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1260 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1268 return Html
::rawElement( 'span',
1269 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1273 * Get the whole body of the form.
1276 public function getBody() {
1277 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1281 * Format and display an error message stack.
1283 * @param string|array|Status $errors
1285 * @deprecated since 1.28, use getErrorsOrWarnings() instead
1289 public function getErrors( $errors ) {
1290 wfDeprecated( __METHOD__
, '1.28' );
1291 return $this->getErrorsOrWarnings( $errors, 'error' );
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() ) {