4 * HTML form generation and submission handling.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms in a reusable manner.
28 * In order to generate the form, the HTMLForm object takes an array
29 * structure detailing the form fields available. Each element of the
30 * array is a basic property-list, including the type of field, the
31 * label it is to be given in the form, callbacks for validation and
32 * 'filtering', and other pertinent information.
34 * Field types are implemented as subclasses of the generic HTMLFormField
35 * object, and typically implement at least getInputHTML, which generates
36 * the HTML for the input field to be placed in the table.
38 * You can find extensive documentation on the www.mediawiki.org wiki:
39 * - https://www.mediawiki.org/wiki/HTMLForm
40 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
45 * 'class' -- the subclass of HTMLFormField that will be used
46 * to create the object. *NOT* the CSS class!
47 * 'type' -- roughly translates into the <select> type attribute.
48 * if 'class' is not specified, this is used as a map
49 * through HTMLForm::$typeMappings to get the class name.
50 * 'default' -- default value when the form is displayed
51 * 'nodata' -- if set (to any value, which casts to true), the data
52 * for this field will not be loaded from the actual request. Instead,
53 * always the default data is set as the value of this field.
54 * 'id' -- HTML id attribute
55 * 'cssclass' -- CSS class
56 * 'csshelpclass' -- CSS class used to style help text
57 * 'dir' -- Direction of the element.
58 * 'options' -- associative array mapping raw text labels to values.
59 * Some field types support multi-level arrays.
60 * Overwrites 'options-message'.
61 * 'options-messages' -- associative array mapping message keys to values.
62 * Some field types support multi-level arrays.
63 * Overwrites 'options' and 'options-message'.
64 * 'options-message' -- message key or object to be parsed to extract the list of
65 * options (like 'ipbreason-dropdown').
66 * 'label-message' -- message key or object for a message to use as the label.
67 * can be an array of msg key and then parameters to
69 * 'label' -- alternatively, a raw text message. Overridden by
71 * 'help' -- message text for a message to use as a help text.
72 * 'help-message' -- message key or object for a message to use as a help text.
73 * can be an array of msg key and then parameters to
75 * Overwrites 'help-messages' and 'help'.
76 * 'help-messages' -- array of message keys/objects. As above, each item can
77 * be an array of msg key and then parameters.
79 * 'help-inline' -- Whether help text (defined using options above) will be shown
80 * inline after the input field, rather than in a popup.
81 * Defaults to true. Only used by OOUI form fields.
82 * 'required' -- passed through to the object, indicating that it
83 * is a required field.
84 * 'size' -- the length of text fields
85 * 'filter-callback' -- a function name to give you the chance to
86 * massage the inputted value before it's processed.
87 * @see HTMLFormField::filter()
88 * 'validation-callback' -- a function name to give you the chance
89 * to impose extra validation on the field input.
90 * @see HTMLFormField::validate()
91 * 'name' -- By default, the 'name' attribute of the input field
92 * is "wp{$fieldname}". If you want a different name
93 * (eg one without the "wp" prefix), specify it here and
94 * it will be used without modification.
95 * 'hide-if' -- expression given as an array stating when the field
96 * should be hidden. The first array value has to be the
97 * expression's logic operator. Supported expressions:
99 * [ 'NOT', array $expression ]
100 * To hide a field if a given expression is not true.
102 * [ '===', string $fieldName, string $value ]
103 * To hide a field if another field identified by
104 * $field has the value $value.
106 * [ '!==', string $fieldName, string $value ]
107 * Same as [ 'NOT', [ '===', $fieldName, $value ]
108 * 'OR', 'AND', 'NOR', 'NAND'
109 * [ 'XXX', array $expression1, ..., array $expressionN ]
110 * To hide a field if one or more (OR), all (AND),
111 * neither (NOR) or not all (NAND) given expressions
112 * are evaluated as true.
113 * The expressions will be given to a JavaScript frontend
114 * module which will continually update the field's
117 * Since 1.20, you can chain mutators to ease the form generation:
120 * $form = new HTMLForm( $someFields );
121 * $form->setMethod( 'get' )
122 * ->setWrapperLegendMsg( 'message-key' )
124 * ->displayForm( '' );
126 * Note that you will have prepareForm and displayForm at the end. Other
127 * methods call done after that would simply not be part of the form :(
129 * @todo Document 'section' / 'subsection' stuff
131 class HTMLForm
extends ContextSource
{
132 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
133 public static $typeMappings = [
134 'api' => HTMLApiField
::class,
135 'text' => HTMLTextField
::class,
136 'textwithbutton' => HTMLTextFieldWithButton
::class,
137 'textarea' => HTMLTextAreaField
::class,
138 'select' => HTMLSelectField
::class,
139 'combobox' => HTMLComboboxField
::class,
140 'radio' => HTMLRadioField
::class,
141 'multiselect' => HTMLMultiSelectField
::class,
142 'limitselect' => HTMLSelectLimitField
::class,
143 'check' => HTMLCheckField
::class,
144 'toggle' => HTMLCheckField
::class,
145 'int' => HTMLIntField
::class,
146 'float' => HTMLFloatField
::class,
147 'info' => HTMLInfoField
::class,
148 'selectorother' => HTMLSelectOrOtherField
::class,
149 'selectandother' => HTMLSelectAndOtherField
::class,
150 'namespaceselect' => HTMLSelectNamespace
::class,
151 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton
::class,
152 'tagfilter' => HTMLTagFilter
::class,
153 'sizefilter' => HTMLSizeFilterField
::class,
154 'submit' => HTMLSubmitField
::class,
155 'hidden' => HTMLHiddenField
::class,
156 'edittools' => HTMLEditTools
::class,
157 'checkmatrix' => HTMLCheckMatrix
::class,
158 'cloner' => HTMLFormFieldCloner
::class,
159 'autocompleteselect' => HTMLAutoCompleteSelectField
::class,
160 'language' => HTMLSelectLanguageField
::class,
161 'date' => HTMLDateTimeField
::class,
162 'time' => HTMLDateTimeField
::class,
163 'datetime' => HTMLDateTimeField
::class,
164 'expiry' => HTMLExpiryField
::class,
165 // HTMLTextField will output the correct type="" attribute automagically.
166 // There are about four zillion other HTML5 input types, like range, but
167 // we don't use those at the moment, so no point in adding all of them.
168 'email' => HTMLTextField
::class,
169 'password' => HTMLTextField
::class,
170 'url' => HTMLTextField
::class,
171 'title' => HTMLTitleTextField
::class,
172 'user' => HTMLUserTextField
::class,
173 'usersmultiselect' => HTMLUsersMultiselectField
::class,
174 'titlesmultiselect' => HTMLTitlesMultiselectField
::class,
175 'namespacesmultiselect' => HTMLNamespacesMultiselectField
::class,
180 protected $mMessagePrefix;
182 /** @var HTMLFormField[] */
183 protected $mFlatFields = [];
184 protected $mFieldTree = [];
185 protected $mShowReset = false;
186 protected $mShowSubmit = true;
188 protected $mSubmitFlags = [ 'primary', 'progressive' ];
189 protected $mShowCancel = false;
190 protected $mCancelTarget;
192 protected $mSubmitCallback;
193 protected $mValidationErrorMessage;
195 protected $mPre = '';
196 protected $mHeader = '';
197 protected $mFooter = '';
198 protected $mSectionHeaders = [];
199 protected $mSectionFooters = [];
200 protected $mPost = '';
203 protected $mTableId = '';
205 protected $mSubmitID;
206 protected $mSubmitName;
207 protected $mSubmitText;
208 protected $mSubmitTooltip;
210 protected $mFormIdentifier;
212 protected $mMethod = 'post';
213 protected $mWasSubmitted = false;
216 * Form action URL. false means we will use the URL to set Title
220 protected $mAction = false;
223 * Whether the form can be collapsed
227 protected $mCollapsible = false;
230 * Whether the form is collapsed by default
234 protected $mCollapsed = false;
237 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
241 protected $mAutocomplete = null;
243 protected $mUseMultipart = false;
244 protected $mHiddenFields = [];
247 * @phan-var array<array{name:string,value:string,label-message?:string,label?:string,label-raw?:string,id?:string,attribs?:array,flags?:string|string[],framed?:bool}>
249 protected $mButtons = [];
251 protected $mWrapperLegend = false;
252 protected $mWrapperAttributes = [];
255 * Salt for the edit token.
258 protected $mTokenSalt = '';
261 * If true, sections that contain both fields and subsections will
262 * render their subsections before their fields.
264 * Subclasses may set this to false to render subsections after fields
267 protected $mSubSectionBeforeFields = true;
270 * Format in which to display form. For viable options,
271 * @see $availableDisplayFormats
274 protected $displayFormat = 'table';
277 * Available formats in which to display the form
280 protected $availableDisplayFormats = [
288 * Available formats in which to display the form
291 protected $availableSubclassDisplayFormats = [
297 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
299 * @param string $displayFormat
300 * @param mixed $arguments,... Additional arguments to pass to the constructor.
301 * @suppress PhanCommentParamWithoutRealParam HHVM bug T228695#5450847
304 public static function factory( $displayFormat/*, $arguments...*/ ) {
305 $arguments = func_get_args();
306 array_shift( $arguments );
308 switch ( $displayFormat ) {
310 return new VFormHTMLForm( ...$arguments );
312 return new OOUIHTMLForm( ...$arguments );
314 $form = new self( ...$arguments );
315 $form->setDisplayFormat( $displayFormat );
321 * Build a new HTMLForm from an array of field attributes
323 * @param array $descriptor Array of Field constructs, as described
324 * in the class documentation
325 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
326 * Obviates the need to call $form->setTitle()
327 * @param string $messagePrefix A prefix to go in front of default messages
329 public function __construct( $descriptor, /*IContextSource*/ $context = null,
332 if ( $context instanceof IContextSource
) {
333 $this->setContext( $context );
334 $this->mTitle
= false; // We don't need them to set a title
335 $this->mMessagePrefix
= $messagePrefix;
336 } elseif ( $context === null && $messagePrefix !== '' ) {
337 $this->mMessagePrefix
= $messagePrefix;
338 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
340 // it's actually $messagePrefix
341 $this->mMessagePrefix
= $context;
344 // Evil hack for mobile :(
346 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
347 && $this->displayFormat
=== 'table'
349 $this->displayFormat
= 'div';
352 $this->addFields( $descriptor );
356 * Add fields to the form
360 * @param array $descriptor Array of Field constructs, as described
361 * in the class documentation
364 public function addFields( $descriptor ) {
365 $loadedDescriptor = [];
367 foreach ( $descriptor as $fieldname => $info ) {
369 $section = $info['section'] ??
'';
371 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
372 $this->mUseMultipart
= true;
375 $field = static::loadInputFromParameters( $fieldname, $info, $this );
377 $setSection =& $loadedDescriptor;
379 foreach ( explode( '/', $section ) as $newName ) {
380 if ( !isset( $setSection[$newName] ) ) {
381 $setSection[$newName] = [];
384 $setSection =& $setSection[$newName];
388 $setSection[$fieldname] = $field;
389 $this->mFlatFields
[$fieldname] = $field;
392 $this->mFieldTree
= array_merge( $this->mFieldTree
, $loadedDescriptor );
398 * @param string $fieldname
401 public function hasField( $fieldname ) {
402 return isset( $this->mFlatFields
[$fieldname] );
406 * @param string $fieldname
407 * @return HTMLFormField
408 * @throws DomainException on invalid field name
410 public function getField( $fieldname ) {
411 if ( !$this->hasField( $fieldname ) ) {
412 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
414 return $this->mFlatFields
[$fieldname];
418 * Set format in which to display the form
420 * @param string $format The name of the format to use, must be one of
421 * $this->availableDisplayFormats
423 * @throws MWException
425 * @return HTMLForm $this for chaining calls (since 1.20)
427 public function setDisplayFormat( $format ) {
429 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
430 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
432 throw new MWException( 'Cannot change display format after creation, ' .
433 'use HTMLForm::factory() instead' );
436 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
437 throw new MWException( 'Display format must be one of ' .
440 $this->availableDisplayFormats
,
441 $this->availableSubclassDisplayFormats
447 // Evil hack for mobile :(
448 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
452 $this->displayFormat
= $format;
458 * Getter for displayFormat
462 public function getDisplayFormat() {
463 return $this->displayFormat
;
467 * Get the HTMLFormField subclass for this descriptor.
469 * The descriptor can be passed either 'class' which is the name of
470 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
471 * This makes sure the 'class' is always set, and also is returned by
472 * this function for ease.
476 * @param string $fieldname Name of the field
477 * @param array &$descriptor Input Descriptor, as described
478 * in the class documentation
480 * @throws MWException
481 * @return string Name of a HTMLFormField subclass
483 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
484 if ( isset( $descriptor['class'] ) ) {
485 $class = $descriptor['class'];
486 } elseif ( isset( $descriptor['type'] ) ) {
487 $class = static::$typeMappings[$descriptor['type']];
488 $descriptor['class'] = $class;
494 throw new MWException( "Descriptor with no class for $fieldname: "
495 . print_r( $descriptor, true ) );
502 * Initialise a new Object for the field
504 * @param string $fieldname Name of the field
505 * @param array $descriptor Input Descriptor, as described
506 * in the class documentation
507 * @param HTMLForm|null $parent Parent instance of HTMLForm
509 * @throws MWException
510 * @return HTMLFormField Instance of a subclass of HTMLFormField
512 public static function loadInputFromParameters( $fieldname, $descriptor,
513 HTMLForm
$parent = null
515 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
517 $descriptor['fieldname'] = $fieldname;
519 $descriptor['parent'] = $parent;
522 # @todo This will throw a fatal error whenever someone try to use
523 # 'class' to feed a CSS class instead of 'cssclass'. Would be
524 # great to avoid the fatal error and show a nice error.
525 return new $class( $descriptor );
529 * Prepare form for submission.
531 * @warning When doing method chaining, that should be the very last
532 * method call before displayForm().
534 * @throws MWException
535 * @return HTMLForm $this for chaining calls (since 1.20)
537 public function prepareForm() {
538 # Check if we have the info we need
539 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
540 throw new MWException( 'You must call setTitle() on an HTMLForm' );
543 # Load data from the request.
545 $this->mFormIdentifier
=== null ||
546 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
550 $this->mFieldData
= [];
557 * Try submitting, with edit token check first
558 * @return Status|bool
560 public function tryAuthorizedSubmit() {
563 if ( $this->mFormIdentifier
=== null ) {
566 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
570 if ( $this->getMethod() !== 'post' ) {
571 $tokenOkay = true; // no session check needed
572 } elseif ( $this->getRequest()->wasPosted() ) {
573 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
574 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
575 // Session tokens for logged-out users have no security value.
576 // However, if the user gave one, check it in order to give a nice
577 // "session expired" error instead of "permission denied" or such.
578 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
584 if ( $tokenOkay && $identOkay ) {
585 $this->mWasSubmitted
= true;
586 $result = $this->trySubmit();
593 * The here's-one-I-made-earlier option: do the submission if
594 * posted, or display the form with or without funky validation
596 * @return bool|Status Whether submission was successful.
598 public function show() {
599 $this->prepareForm();
601 $result = $this->tryAuthorizedSubmit();
602 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
606 $this->displayForm( $result );
612 * Same as self::show with the difference, that the form will be
613 * added to the output, no matter, if the validation was good or not.
614 * @return bool|Status Whether submission was successful.
616 public function showAlways() {
617 $this->prepareForm();
619 $result = $this->tryAuthorizedSubmit();
621 $this->displayForm( $result );
627 * Validate all the fields, and call the submission callback
628 * function if everything is kosher.
629 * @throws MWException
630 * @return bool|string|array|Status
631 * - Bool true or a good Status object indicates success,
632 * - Bool false indicates no submission was attempted,
633 * - Anything else indicates failure. The value may be a fatal Status
634 * object, an HTML string, or an array of arrays (message keys and
635 * params) or strings (message keys)
637 public function trySubmit() {
639 $hoistedErrors = Status
::newGood();
640 if ( $this->mValidationErrorMessage
) {
641 foreach ( $this->mValidationErrorMessage
as $error ) {
642 $hoistedErrors->fatal( ...$error );
645 $hoistedErrors->fatal( 'htmlform-invalid-input' );
648 $this->mWasSubmitted
= true;
650 # Check for cancelled submission
651 foreach ( $this->mFlatFields
as $fieldname => $field ) {
652 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
655 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
656 $this->mWasSubmitted
= false;
661 # Check for validation
662 foreach ( $this->mFlatFields
as $fieldname => $field ) {
663 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
666 if ( $field->isHidden( $this->mFieldData
) ) {
669 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
670 if ( $res !== true ) {
672 if ( $res !== false && !$field->canDisplayErrors() ) {
673 if ( is_string( $res ) ) {
674 $hoistedErrors->fatal( 'rawmessage', $res );
676 $hoistedErrors->fatal( $res );
683 return $hoistedErrors;
686 $callback = $this->mSubmitCallback
;
687 if ( !is_callable( $callback ) ) {
688 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
689 'setSubmitCallback() to set one.' );
692 $data = $this->filterDataForSubmit( $this->mFieldData
);
694 $res = call_user_func( $callback, $data, $this );
695 if ( $res === false ) {
696 $this->mWasSubmitted
= false;
703 * Test whether the form was considered to have been submitted or not, i.e.
704 * whether the last call to tryAuthorizedSubmit or trySubmit returned
707 * This will return false until HTMLForm::tryAuthorizedSubmit or
708 * HTMLForm::trySubmit is called.
713 public function wasSubmitted() {
714 return $this->mWasSubmitted
;
718 * Set a callback to a function to do something with the form
719 * once it's been successfully validated.
721 * @param callable $cb The function will be passed the output from
722 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
723 * return as documented for HTMLForm::trySubmit
725 * @return HTMLForm $this for chaining calls (since 1.20)
727 public function setSubmitCallback( $cb ) {
728 $this->mSubmitCallback
= $cb;
734 * Set a message to display on a validation error.
736 * @param array $msg Array of valid inputs to wfMessage()
737 * (so each entry must itself be an array of arguments)
739 * @return HTMLForm $this for chaining calls (since 1.20)
741 public function setValidationErrorMessage( $msg ) {
742 $this->mValidationErrorMessage
= $msg;
748 * Set the introductory message, overwriting any existing message.
750 * @param string $msg Complete text of message to display
752 * @return HTMLForm $this for chaining calls (since 1.20)
754 public function setIntro( $msg ) {
755 $this->setPreText( $msg );
761 * Set the introductory message HTML, overwriting any existing message.
764 * @param string $msg Complete HTML of message to display
766 * @return HTMLForm $this for chaining calls (since 1.20)
768 public function setPreText( $msg ) {
775 * Add HTML to introductory message.
777 * @param string $msg Complete HTML of message to display
779 * @return HTMLForm $this for chaining calls (since 1.20)
781 public function addPreText( $msg ) {
788 * Get the introductory message HTML.
794 public function getPreText() {
799 * Add HTML to the header, inside the form.
801 * @param string $msg Additional HTML to display in header
802 * @param string|null $section The section to add the header to
804 * @return HTMLForm $this for chaining calls (since 1.20)
806 public function addHeaderText( $msg, $section = null ) {
807 if ( $section === null ) {
808 $this->mHeader
.= $msg;
810 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
811 $this->mSectionHeaders
[$section] = '';
813 $this->mSectionHeaders
[$section] .= $msg;
820 * Set header text, inside the form.
823 * @param string $msg Complete HTML of header to display
824 * @param string|null $section The section to add the header to
826 * @return HTMLForm $this for chaining calls (since 1.20)
828 public function setHeaderText( $msg, $section = null ) {
829 if ( $section === null ) {
830 $this->mHeader
= $msg;
832 $this->mSectionHeaders
[$section] = $msg;
841 * @param string|null $section The section to get the header text for
843 * @return string HTML
845 public function getHeaderText( $section = null ) {
846 if ( $section === null ) {
847 return $this->mHeader
;
849 return $this->mSectionHeaders
[$section] ??
'';
854 * Add footer text, inside the form.
856 * @param string $msg Complete text of message to display
857 * @param string|null $section The section to add the footer text to
859 * @return HTMLForm $this for chaining calls (since 1.20)
861 public function addFooterText( $msg, $section = null ) {
862 if ( $section === null ) {
863 $this->mFooter
.= $msg;
865 if ( !isset( $this->mSectionFooters
[$section] ) ) {
866 $this->mSectionFooters
[$section] = '';
868 $this->mSectionFooters
[$section] .= $msg;
875 * Set footer text, inside the form.
878 * @param string $msg Complete text of message to display
879 * @param string|null $section The section to add the footer text to
881 * @return HTMLForm $this for chaining calls (since 1.20)
883 public function setFooterText( $msg, $section = null ) {
884 if ( $section === null ) {
885 $this->mFooter
= $msg;
887 $this->mSectionFooters
[$section] = $msg;
896 * @param string|null $section The section to get the footer text for
900 public function getFooterText( $section = null ) {
901 if ( $section === null ) {
902 return $this->mFooter
;
904 return $this->mSectionFooters
[$section] ??
'';
909 * Add text to the end of the display.
911 * @param string $msg Complete text of message to display
913 * @return HTMLForm $this for chaining calls (since 1.20)
915 public function addPostText( $msg ) {
916 $this->mPost
.= $msg;
922 * Set text at the end of the display.
924 * @param string $msg Complete text of message to display
926 * @return HTMLForm $this for chaining calls (since 1.20)
928 public function setPostText( $msg ) {
935 * Add a hidden field to the output
937 * @param string $name Field name. This will be used exactly as entered
938 * @param string $value Field value
939 * @param array $attribs
941 * @return HTMLForm $this for chaining calls (since 1.20)
943 public function addHiddenField( $name, $value, array $attribs = [] ) {
944 $attribs +
= [ 'name' => $name ];
945 $this->mHiddenFields
[] = [ $value, $attribs ];
951 * Add an array of hidden fields to the output
955 * @param array $fields Associative array of fields to add;
956 * mapping names to their values
958 * @return HTMLForm $this for chaining calls
960 public function addHiddenFields( array $fields ) {
961 foreach ( $fields as $name => $value ) {
962 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
969 * Add a button to the form
971 * @since 1.27 takes an array as shown. Earlier versions accepted
972 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
974 * @note Custom labels ('label', 'label-message', 'label-raw') are not
975 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
976 * they will be served buttons using 'value' as the button label.
977 * @param array $data Data to define the button:
978 * - name: (string) Button name.
979 * - value: (string) Button value.
980 * - label-message: (string, optional) Button label message key to use
981 * instead of 'value'. Overrides 'label' and 'label-raw'.
982 * - label: (string, optional) Button label text to use instead of
983 * 'value'. Overrides 'label-raw'.
984 * - label-raw: (string, optional) Button label HTML to use instead of
986 * - id: (string, optional) DOM id for the button.
987 * - attribs: (array, optional) Additional HTML attributes.
988 * - flags: (string|string[], optional) OOUI flags.
989 * - framed: (boolean=true, optional) OOUI framed attribute.
990 * @codingStandardsIgnoreStart
991 * @phan-param array{name:string,value:string,label-message?:string,label?:string,label-raw?:string,id?:string,attribs?:array,flags?:string|string[],framed?:bool} $data
992 * @codingStandardsIgnoreEnd
993 * @return HTMLForm $this for chaining calls (since 1.20)
995 public function addButton( $data ) {
996 if ( !is_array( $data ) ) {
997 $args = func_get_args();
998 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
999 throw new InvalidArgumentException(
1000 'Incorrect number of arguments for deprecated calling style'
1005 'value' => $args[1],
1006 'id' => $args[2] ??
null,
1007 'attribs' => $args[3] ??
null,
1010 if ( !isset( $data['name'] ) ) {
1011 throw new InvalidArgumentException( 'A name is required' );
1013 if ( !isset( $data['value'] ) ) {
1014 throw new InvalidArgumentException( 'A value is required' );
1017 $this->mButtons
[] = $data +
[
1028 * Set the salt for the edit token.
1030 * Only useful when the method is "post".
1033 * @param string|array $salt Salt to use
1034 * @return HTMLForm $this For chaining calls
1036 public function setTokenSalt( $salt ) {
1037 $this->mTokenSalt
= $salt;
1043 * Display the form (sending to the context's OutputPage object), with an
1044 * appropriate error message or stack of messages, and any validation errors, etc.
1046 * @warning You should call prepareForm() before calling this function.
1047 * Moreover, when doing method chaining this should be the very last method
1048 * call just after prepareForm().
1050 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1052 * @return void Nothing, should be last call
1054 public function displayForm( $submitResult ) {
1055 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1059 * Returns the raw HTML generated by the form
1061 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1063 * @return string HTML
1064 * @return-taint escaped
1066 public function getHTML( $submitResult ) {
1067 # For good measure (it is the default)
1068 $this->getOutput()->preventClickjacking();
1069 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1070 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1073 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1074 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1075 . $this->getHeaderText()
1077 . $this->getHiddenFields()
1078 . $this->getButtons()
1079 . $this->getFooterText();
1081 $html = $this->wrapForm( $html );
1083 return '' . $this->mPre
. $html . $this->mPost
;
1087 * Enable collapsible mode, and set whether the form is collapsed by default.
1090 * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
1091 * @return HTMLForm $this for chaining calls
1093 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1094 $this->mCollapsible
= true;
1095 $this->mCollapsed
= $collapsedByDefault;
1100 * Get HTML attributes for the `<form>` tag.
1103 protected function getFormAttributes() {
1104 # Use multipart/form-data
1105 $encType = $this->mUseMultipart
1106 ?
'multipart/form-data'
1107 : 'application/x-www-form-urlencoded';
1110 'class' => 'mw-htmlform',
1111 'action' => $this->getAction(),
1112 'method' => $this->getMethod(),
1113 'enctype' => $encType,
1116 $attribs['id'] = $this->mId
;
1118 if ( is_string( $this->mAutocomplete
) ) {
1119 $attribs['autocomplete'] = $this->mAutocomplete
;
1121 if ( $this->mName
) {
1122 $attribs['name'] = $this->mName
;
1124 if ( $this->needsJSForHtml5FormValidation() ) {
1125 $attribs['novalidate'] = true;
1131 * Wrap the form innards in an actual "<form>" element
1133 * @param string $html HTML contents to wrap.
1135 * @return string Wrapped HTML.
1137 public function wrapForm( $html ) {
1138 # Include a <fieldset> wrapper for style, if requested.
1139 if ( $this->mWrapperLegend
!== false ) {
1140 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1141 $html = Xml
::fieldset( $legend, $html, $this->mWrapperAttributes
);
1144 return Html
::rawElement(
1146 $this->getFormAttributes(),
1152 * Get the hidden fields that should go inside the form.
1153 * @return string HTML.
1155 public function getHiddenFields() {
1157 if ( $this->mFormIdentifier
!== null ) {
1158 $html .= Html
::hidden(
1160 $this->mFormIdentifier
1163 if ( $this->getMethod() === 'post' ) {
1164 $html .= Html
::hidden(
1166 $this->getUser()->getEditToken( $this->mTokenSalt
),
1167 [ 'id' => 'wpEditToken' ]
1169 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1172 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1173 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1174 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1177 foreach ( $this->mHiddenFields
as $data ) {
1178 list( $value, $attribs ) = $data;
1179 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1186 * Get the submit and (potentially) reset buttons.
1187 * @return string HTML.
1189 public function getButtons() {
1191 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1193 if ( $this->mShowSubmit
) {
1196 if ( isset( $this->mSubmitID
) ) {
1197 $attribs['id'] = $this->mSubmitID
;
1200 if ( isset( $this->mSubmitName
) ) {
1201 $attribs['name'] = $this->mSubmitName
;
1204 if ( isset( $this->mSubmitTooltip
) ) {
1205 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1208 $attribs['class'] = [ 'mw-htmlform-submit' ];
1210 if ( $useMediaWikiUIEverywhere ) {
1211 foreach ( $this->mSubmitFlags
as $flag ) {
1212 $attribs['class'][] = 'mw-ui-' . $flag;
1214 $attribs['class'][] = 'mw-ui-button';
1217 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1220 if ( $this->mShowReset
) {
1221 $buttons .= Html
::element(
1225 'value' => $this->msg( 'htmlform-reset' )->text(),
1226 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1231 if ( $this->mShowCancel
) {
1232 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1233 if ( $target instanceof Title
) {
1234 $target = $target->getLocalURL();
1236 $buttons .= Html
::element(
1239 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1242 $this->msg( 'cancel' )->text()
1246 // IE<8 has bugs with <button>, so we'll need to avoid them.
1247 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1249 foreach ( $this->mButtons
as $button ) {
1252 'name' => $button['name'],
1253 'value' => $button['value']
1256 if ( isset( $button['label-message'] ) ) {
1257 $label = $this->getMessage( $button['label-message'] )->parse();
1258 } elseif ( isset( $button['label'] ) ) {
1259 $label = htmlspecialchars( $button['label'] );
1260 } elseif ( isset( $button['label-raw'] ) ) {
1261 $label = $button['label-raw'];
1263 $label = htmlspecialchars( $button['value'] );
1266 if ( $button['attribs'] ) {
1267 $attrs +
= $button['attribs'];
1270 if ( isset( $button['id'] ) ) {
1271 $attrs['id'] = $button['id'];
1274 if ( $useMediaWikiUIEverywhere ) {
1275 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1276 $attrs['class'][] = 'mw-ui-button';
1280 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1282 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1290 return Html
::rawElement( 'span',
1291 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1295 * Get the whole body of the form.
1298 public function getBody() {
1299 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1303 * Returns a formatted list of errors or warnings from the given elements.
1305 * @param string|array|Status $elements The set of errors/warnings to process.
1306 * @param string $elementsType Should warnings or errors be returned. This is meant
1307 * for Status objects, all other valid types are always considered as errors.
1310 public function getErrorsOrWarnings( $elements, $elementsType ) {
1311 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1312 throw new DomainException( $elementsType . ' is not a valid type.' );
1314 $elementstr = false;
1315 if ( $elements instanceof Status
) {
1316 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1317 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1318 if ( $status->isGood() ) {
1321 $elementstr = $this->getOutput()->parseAsInterface(
1322 $status->getWikiText()
1325 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1326 $elementstr = $this->formatErrors( $elements );
1327 } elseif ( $elementsType === 'error' ) {
1328 $elementstr = $elements;
1332 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1337 * Format a stack of error messages into a single HTML string
1339 * @param array $errors Array of message keys/values
1341 * @return string HTML, a "<ul>" list of errors
1343 public function formatErrors( $errors ) {
1346 foreach ( $errors as $error ) {
1347 $errorstr .= Html
::rawElement(
1350 $this->getMessage( $error )->parse()
1354 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1360 * Set the text for the submit button
1362 * @param string $t Plaintext
1364 * @return HTMLForm $this for chaining calls (since 1.20)
1366 public function setSubmitText( $t ) {
1367 $this->mSubmitText
= $t;
1373 * Identify that the submit button in the form has a destructive action
1376 * @return HTMLForm $this for chaining calls (since 1.28)
1378 public function setSubmitDestructive() {
1379 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1385 * Set the text for the submit button to a message
1388 * @param string|Message $msg Message key or Message object
1390 * @return HTMLForm $this for chaining calls (since 1.20)
1392 public function setSubmitTextMsg( $msg ) {
1393 if ( !$msg instanceof Message
) {
1394 $msg = $this->msg( $msg );
1396 $this->setSubmitText( $msg->text() );
1402 * Get the text for the submit button, either customised or a default.
1405 public function getSubmitText() {
1406 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1410 * @param string $name Submit button name
1412 * @return HTMLForm $this for chaining calls (since 1.20)
1414 public function setSubmitName( $name ) {
1415 $this->mSubmitName
= $name;
1421 * @param string $name Tooltip for the submit button
1423 * @return HTMLForm $this for chaining calls (since 1.20)
1425 public function setSubmitTooltip( $name ) {
1426 $this->mSubmitTooltip
= $name;
1432 * Set the id for the submit button.
1436 * @todo FIXME: Integrity of $t is *not* validated
1437 * @return HTMLForm $this for chaining calls (since 1.20)
1439 public function setSubmitID( $t ) {
1440 $this->mSubmitID
= $t;
1446 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1447 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1450 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1451 * was submitted, and not attempt to validate the other ones.
1452 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1453 * HTMLForm to distinguish between the initial page view and a form submission with all
1454 * checkboxes or select options unchecked.
1457 * @param string $ident
1460 public function setFormIdentifier( $ident ) {
1461 $this->mFormIdentifier
= $ident;
1467 * Stop a default submit button being shown for this form. This implies that an
1468 * alternate submit method must be provided manually.
1472 * @param bool $suppressSubmit Set to false to re-enable the button again
1474 * @return HTMLForm $this for chaining calls
1476 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1477 $this->mShowSubmit
= !$suppressSubmit;
1483 * Show a cancel button (or prevent it). The button is not shown by default.
1485 * @return HTMLForm $this for chaining calls
1488 public function showCancel( $show = true ) {
1489 $this->mShowCancel
= $show;
1494 * Sets the target where the user is redirected to after clicking cancel.
1495 * @param Title|string $target Target as a Title object or an URL
1496 * @return HTMLForm $this for chaining calls
1499 public function setCancelTarget( $target ) {
1500 $this->mCancelTarget
= $target;
1505 * Set the id of the \<table\> or outermost \<div\> element.
1509 * @param string $id New value of the id attribute, or "" to remove
1511 * @return HTMLForm $this for chaining calls
1513 public function setTableId( $id ) {
1514 $this->mTableId
= $id;
1520 * @param string $id DOM id for the form
1522 * @return HTMLForm $this for chaining calls (since 1.20)
1524 public function setId( $id ) {
1531 * @param string $name 'name' attribute for the form
1532 * @return HTMLForm $this for chaining calls
1534 public function setName( $name ) {
1535 $this->mName
= $name;
1541 * Prompt the whole form to be wrapped in a "<fieldset>", with
1542 * this text as its "<legend>" element.
1544 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1545 * If true, a wrapper will be displayed, but no legend.
1546 * If a string, a wrapper will be displayed with that string as a legend.
1547 * The string will be escaped before being output (this doesn't support HTML).
1549 * @return HTMLForm $this for chaining calls (since 1.20)
1551 public function setWrapperLegend( $legend ) {
1552 $this->mWrapperLegend
= $legend;
1558 * For internal use only. Use is discouraged, and should only be used where
1559 * support for gadgets/user scripts is warranted.
1560 * @param array $attributes
1562 * @return HTMLForm $this for chaining calls
1564 public function setWrapperAttributes( $attributes ) {
1565 $this->mWrapperAttributes
= $attributes;
1571 * Prompt the whole form to be wrapped in a "<fieldset>", with
1572 * this message as its "<legend>" element.
1575 * @param string|Message $msg Message key or Message object
1577 * @return HTMLForm $this for chaining calls (since 1.20)
1579 public function setWrapperLegendMsg( $msg ) {
1580 if ( !$msg instanceof Message
) {
1581 $msg = $this->msg( $msg );
1583 $this->setWrapperLegend( $msg->text() );
1589 * Set the prefix for various default messages
1590 * @todo Currently only used for the "<fieldset>" legend on forms
1591 * with multiple sections; should be used elsewhere?
1595 * @return HTMLForm $this for chaining calls (since 1.20)
1597 public function setMessagePrefix( $p ) {
1598 $this->mMessagePrefix
= $p;
1604 * Set the title for form submission
1606 * @param Title $t Title of page the form is on/should be posted to
1608 * @return HTMLForm $this for chaining calls (since 1.20)
1610 public function setTitle( $t ) {
1620 public function getTitle() {
1621 return $this->mTitle
=== false
1622 ?
$this->getContext()->getTitle()
1627 * Set the method used to submit the form
1629 * @param string $method
1631 * @return HTMLForm $this for chaining calls (since 1.20)
1633 public function setMethod( $method = 'post' ) {
1634 $this->mMethod
= strtolower( $method );
1640 * @return string Always lowercase
1642 public function getMethod() {
1643 return $this->mMethod
;
1647 * Wraps the given $section into an user-visible fieldset.
1649 * @param string $legend Legend text for the fieldset
1650 * @param string $section The section content in plain Html
1651 * @param array $attributes Additional attributes for the fieldset
1652 * @param bool $isRoot Section is at the root of the tree
1653 * @return string The fieldset's Html
1655 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1656 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1662 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1664 * @param string $sectionName ID attribute of the "<table>" tag for this
1665 * section, ignored if empty.
1666 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1667 * each subsection, ignored if empty.
1668 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1669 * @throws LogicException When called on uninitialized field data, e.g. When
1670 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1675 public function displaySection( $fields,
1677 $fieldsetIDPrefix = '',
1678 &$hasUserVisibleFields = false
1680 if ( $this->mFieldData
=== null ) {
1681 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1682 . 'You probably called displayForm() without calling prepareForm() first.' );
1685 $displayFormat = $this->getDisplayFormat();
1688 $subsectionHtml = '';
1691 // Conveniently, PHP method names are case-insensitive.
1692 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1693 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1695 foreach ( $fields as $key => $value ) {
1696 if ( $value instanceof HTMLFormField
) {
1697 $v = array_key_exists( $key, $this->mFieldData
)
1698 ?
$this->mFieldData
[$key]
1699 : $value->getDefault();
1701 $retval = $value->$getFieldHtmlMethod( $v );
1703 // check, if the form field should be added to
1705 if ( $value->hasVisibleOutput() ) {
1708 $labelValue = trim( $value->getLabel() );
1709 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
1713 $hasUserVisibleFields = true;
1715 } elseif ( is_array( $value ) ) {
1716 $subsectionHasVisibleFields = false;
1718 $this->displaySection( $value,
1720 "$fieldsetIDPrefix$key-",
1721 $subsectionHasVisibleFields );
1724 if ( $subsectionHasVisibleFields === true ) {
1725 // Display the section with various niceties.
1726 $hasUserVisibleFields = true;
1728 $legend = $this->getLegend( $key );
1730 $section = $this->getHeaderText( $key ) .
1732 $this->getFooterText( $key );
1735 if ( $fieldsetIDPrefix ) {
1736 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1738 $subsectionHtml .= $this->wrapFieldSetSection(
1739 $legend, $section, $attributes, $fields === $this->mFieldTree
1742 // Just return the inputs, nothing fancy.
1743 $subsectionHtml .= $section;
1748 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1750 if ( $subsectionHtml ) {
1751 if ( $this->mSubSectionBeforeFields
) {
1752 return $subsectionHtml . "\n" . $html;
1754 return $html . "\n" . $subsectionHtml;
1762 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1763 * @param array $fieldsHtml
1764 * @param string $sectionName
1765 * @param bool $anyFieldHasLabel
1766 * @return string HTML
1768 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1769 if ( !$fieldsHtml ) {
1770 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1771 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1775 $displayFormat = $this->getDisplayFormat();
1776 $html = implode( '', $fieldsHtml );
1778 if ( $displayFormat === 'raw' ) {
1784 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1785 $classes[] = 'mw-htmlform-nolabel';
1789 'class' => implode( ' ', $classes ),
1792 if ( $sectionName ) {
1793 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1796 if ( $displayFormat === 'table' ) {
1797 return Html
::rawElement( 'table',
1799 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1800 } elseif ( $displayFormat === 'inline' ) {
1801 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1803 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1808 * Construct the form fields from the Descriptor array
1810 public function loadData() {
1813 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1814 $request = $this->getRequest();
1815 if ( $field->skipLoadData( $request ) ) {
1817 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1818 $fieldData[$fieldname] = $field->getDefault();
1820 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1825 foreach ( $fieldData as $name => &$value ) {
1826 $field = $this->mFlatFields
[$name];
1827 $value = $field->filter( $value, $this->mFlatFields
);
1830 $this->mFieldData
= $fieldData;
1834 * Stop a reset button being shown for this form
1836 * @param bool $suppressReset Set to false to re-enable the button again
1838 * @return HTMLForm $this for chaining calls (since 1.20)
1840 public function suppressReset( $suppressReset = true ) {
1841 $this->mShowReset
= !$suppressReset;
1847 * Overload this if you want to apply special filtration routines
1848 * to the form as a whole, after it's submitted but before it's
1851 * @param array $data
1855 public function filterDataForSubmit( $data ) {
1860 * Get a string to go in the "<legend>" of a section fieldset.
1861 * Override this if you want something more complicated.
1863 * @param string $key
1865 * @return string Plain text (not HTML-escaped)
1867 public function getLegend( $key ) {
1868 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1872 * Set the value for the action attribute of the form.
1873 * When set to false (which is the default state), the set title is used.
1877 * @param string|bool $action
1879 * @return HTMLForm $this for chaining calls (since 1.20)
1881 public function setAction( $action ) {
1882 $this->mAction
= $action;
1888 * Get the value for the action attribute of the form.
1894 public function getAction() {
1895 // If an action is alredy provided, return it
1896 if ( $this->mAction
!== false ) {
1897 return $this->mAction
;
1900 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1901 // Check whether we are in GET mode and the ArticlePath contains a "?"
1902 // meaning that getLocalURL() would return something like "index.php?title=...".
1903 // As browser remove the query string before submitting GET forms,
1904 // it means that the title would be lost. In such case use wfScript() instead
1905 // and put title in an hidden field (see getHiddenFields()).
1906 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1910 return $this->getTitle()->getLocalURL();
1914 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1915 * When set to null (which is the default state), the attribute get not set.
1919 * @param string|null $autocomplete
1921 * @return HTMLForm $this for chaining calls
1923 public function setAutocomplete( $autocomplete ) {
1924 $this->mAutocomplete
= $autocomplete;
1930 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1931 * name + parameters array) into a Message.
1932 * @param mixed $value
1935 protected function getMessage( $value ) {
1936 return Message
::newFromSpecifier( $value )->setContext( $this );
1940 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1941 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1942 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1943 * agent has JavaScript support, in htmlform.js.
1948 public function needsJSForHtml5FormValidation() {
1949 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1950 if ( $field->needsJSForHtml5FormValidation() ) {