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 * 'id' -- HTML id attribute
54 * 'cssclass' -- CSS class
55 * 'csshelpclass' -- CSS class used to style help text
56 * 'dir' -- Direction of the element.
57 * 'options' -- associative array mapping labels to values.
58 * Some field types support multi-level arrays.
59 * 'options-messages' -- associative array mapping message keys to values.
60 * Some field types support multi-level arrays.
61 * 'options-message' -- message key or object to be parsed to extract the list of
62 * options (like 'ipbreason-dropdown').
63 * 'label-message' -- message key or object for a message to use as the label.
64 * can be an array of msg key and then parameters to
66 * 'label' -- alternatively, a raw text message. Overridden by
68 * 'help' -- message text for a message to use as a help text.
69 * 'help-message' -- message key or object for a message to use as a help text.
70 * can be an array of msg key and then parameters to
72 * Overwrites 'help-messages' and 'help'.
73 * 'help-messages' -- array of message keys/objects. As above, each item can
74 * be an array of msg key and then parameters.
76 * 'notice' -- message text for a message to use as a notice in the field.
77 * Currently used by OOUI form fields only.
78 * 'notice-messages' -- array of message keys/objects to use for notice.
80 * 'notice-message' -- message key or object to use as a notice.
81 * 'required' -- passed through to the object, indicating that it
82 * is a required field.
83 * 'size' -- the length of text fields
84 * 'filter-callback' -- a function name to give you the chance to
85 * massage the inputted value before it's processed.
86 * @see HTMLFormField::filter()
87 * 'validation-callback' -- a function name to give you the chance
88 * to impose extra validation on the field input.
89 * @see HTMLFormField::validate()
90 * 'name' -- By default, the 'name' attribute of the input field
91 * is "wp{$fieldname}". If you want a different name
92 * (eg one without the "wp" prefix), specify it here and
93 * it will be used without modification.
94 * 'hide-if' -- expression given as an array stating when the field
95 * should be hidden. The first array value has to be the
96 * expression's logic operator. Supported expressions:
98 * [ 'NOT', array $expression ]
99 * To hide a field if a given expression is not true.
101 * [ '===', string $fieldName, string $value ]
102 * To hide a field if another field identified by
103 * $field has the value $value.
105 * [ '!==', string $fieldName, string $value ]
106 * Same as [ 'NOT', [ '===', $fieldName, $value ]
107 * 'OR', 'AND', 'NOR', 'NAND'
108 * [ 'XXX', array $expression1, ..., array $expressionN ]
109 * To hide a field if one or more (OR), all (AND),
110 * neither (NOR) or not all (NAND) given expressions
111 * are evaluated as true.
112 * The expressions will be given to a JavaScript frontend
113 * module which will continually update the field's
116 * Since 1.20, you can chain mutators to ease the form generation:
119 * $form = new HTMLForm( $someFields );
120 * $form->setMethod( 'get' )
121 * ->setWrapperLegendMsg( 'message-key' )
123 * ->displayForm( '' );
125 * Note that you will have prepareForm and displayForm at the end. Other
126 * methods call done after that would simply not be part of the form :(
128 * @todo Document 'section' / 'subsection' stuff
130 class HTMLForm
extends ContextSource
{
131 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
132 public static $typeMappings = [
133 'api' => HTMLApiField
::class,
134 'text' => HTMLTextField
::class,
135 'textwithbutton' => HTMLTextFieldWithButton
::class,
136 'textarea' => HTMLTextAreaField
::class,
137 'select' => HTMLSelectField
::class,
138 'combobox' => HTMLComboboxField
::class,
139 'radio' => HTMLRadioField
::class,
140 'multiselect' => HTMLMultiSelectField
::class,
141 'limitselect' => HTMLSelectLimitField
::class,
142 'check' => HTMLCheckField
::class,
143 'toggle' => HTMLCheckField
::class,
144 'int' => HTMLIntField
::class,
145 'float' => HTMLFloatField
::class,
146 'info' => HTMLInfoField
::class,
147 'selectorother' => HTMLSelectOrOtherField
::class,
148 'selectandother' => HTMLSelectAndOtherField
::class,
149 'namespaceselect' => HTMLSelectNamespace
::class,
150 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton
::class,
151 'tagfilter' => HTMLTagFilter
::class,
152 'sizefilter' => HTMLSizeFilterField
::class,
153 'submit' => HTMLSubmitField
::class,
154 'hidden' => HTMLHiddenField
::class,
155 'edittools' => HTMLEditTools
::class,
156 'checkmatrix' => HTMLCheckMatrix
::class,
157 'cloner' => HTMLFormFieldCloner
::class,
158 'autocompleteselect' => HTMLAutoCompleteSelectField
::class,
159 'date' => HTMLDateTimeField
::class,
160 'time' => HTMLDateTimeField
::class,
161 'datetime' => HTMLDateTimeField
::class,
162 'expiry' => HTMLExpiryField
::class,
163 // HTMLTextField will output the correct type="" attribute automagically.
164 // There are about four zillion other HTML5 input types, like range, but
165 // we don't use those at the moment, so no point in adding all of them.
166 'email' => HTMLTextField
::class,
167 'password' => HTMLTextField
::class,
168 'url' => HTMLTextField
::class,
169 'title' => HTMLTitleTextField
::class,
170 'user' => HTMLUserTextField
::class,
171 'usersmultiselect' => HTMLUsersMultiselectField
::class,
176 protected $mMessagePrefix;
178 /** @var HTMLFormField[] */
179 protected $mFlatFields;
181 protected $mFieldTree;
182 protected $mShowReset = false;
183 protected $mShowSubmit = true;
184 protected $mSubmitFlags = [ 'primary', 'progressive' ];
185 protected $mShowCancel = false;
186 protected $mCancelTarget;
188 protected $mSubmitCallback;
189 protected $mValidationErrorMessage;
191 protected $mPre = '';
192 protected $mHeader = '';
193 protected $mFooter = '';
194 protected $mSectionHeaders = [];
195 protected $mSectionFooters = [];
196 protected $mPost = '';
199 protected $mTableId = '';
201 protected $mSubmitID;
202 protected $mSubmitName;
203 protected $mSubmitText;
204 protected $mSubmitTooltip;
206 protected $mFormIdentifier;
208 protected $mMethod = 'post';
209 protected $mWasSubmitted = false;
212 * Form action URL. false means we will use the URL to set Title
216 protected $mAction = false;
219 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
223 protected $mAutocomplete = null;
225 protected $mUseMultipart = false;
226 protected $mHiddenFields = [];
227 protected $mButtons = [];
229 protected $mWrapperLegend = false;
232 * Salt for the edit token.
235 protected $mTokenSalt = '';
238 * If true, sections that contain both fields and subsections will
239 * render their subsections before their fields.
241 * Subclasses may set this to false to render subsections after fields
244 protected $mSubSectionBeforeFields = true;
247 * Format in which to display form. For viable options,
248 * @see $availableDisplayFormats
251 protected $displayFormat = 'table';
254 * Available formats in which to display the form
257 protected $availableDisplayFormats = [
265 * Available formats in which to display the form
268 protected $availableSubclassDisplayFormats = [
274 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
276 * @param string $displayFormat
277 * @param mixed $arguments,... Additional arguments to pass to the constructor.
280 public static function factory( $displayFormat/*, $arguments...*/ ) {
281 $arguments = func_get_args();
282 array_shift( $arguments );
284 switch ( $displayFormat ) {
286 return ObjectFactory
::constructClassInstance( VFormHTMLForm
::class, $arguments );
288 return ObjectFactory
::constructClassInstance( OOUIHTMLForm
::class, $arguments );
290 /** @var HTMLForm $form */
291 $form = ObjectFactory
::constructClassInstance( self
::class, $arguments );
292 $form->setDisplayFormat( $displayFormat );
298 * Build a new HTMLForm from an array of field attributes
300 * @param array $descriptor Array of Field constructs, as described above
301 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
302 * Obviates the need to call $form->setTitle()
303 * @param string $messagePrefix A prefix to go in front of default messages
305 public function __construct( $descriptor, /*IContextSource*/ $context = null,
308 if ( $context instanceof IContextSource
) {
309 $this->setContext( $context );
310 $this->mTitle
= false; // We don't need them to set a title
311 $this->mMessagePrefix
= $messagePrefix;
312 } elseif ( $context === null && $messagePrefix !== '' ) {
313 $this->mMessagePrefix
= $messagePrefix;
314 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
316 // it's actually $messagePrefix
317 $this->mMessagePrefix
= $context;
320 // Evil hack for mobile :(
322 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
323 && $this->displayFormat
=== 'table'
325 $this->displayFormat
= 'div';
328 // Expand out into a tree.
329 $loadedDescriptor = [];
330 $this->mFlatFields
= [];
332 foreach ( $descriptor as $fieldname => $info ) {
333 $section = isset( $info['section'] )
337 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
338 $this->mUseMultipart
= true;
341 $field = static::loadInputFromParameters( $fieldname, $info, $this );
343 $setSection =& $loadedDescriptor;
345 $sectionParts = explode( '/', $section );
347 while ( count( $sectionParts ) ) {
348 $newName = array_shift( $sectionParts );
350 if ( !isset( $setSection[$newName] ) ) {
351 $setSection[$newName] = [];
354 $setSection =& $setSection[$newName];
358 $setSection[$fieldname] = $field;
359 $this->mFlatFields
[$fieldname] = $field;
362 $this->mFieldTree
= $loadedDescriptor;
366 * @param string $fieldname
369 public function hasField( $fieldname ) {
370 return isset( $this->mFlatFields
[$fieldname] );
374 * @param string $fieldname
375 * @return HTMLFormField
376 * @throws DomainException on invalid field name
378 public function getField( $fieldname ) {
379 if ( !$this->hasField( $fieldname ) ) {
380 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
382 return $this->mFlatFields
[$fieldname];
386 * Set format in which to display the form
388 * @param string $format The name of the format to use, must be one of
389 * $this->availableDisplayFormats
391 * @throws MWException
393 * @return HTMLForm $this for chaining calls (since 1.20)
395 public function setDisplayFormat( $format ) {
397 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
398 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
400 throw new MWException( 'Cannot change display format after creation, ' .
401 'use HTMLForm::factory() instead' );
404 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
405 throw new MWException( 'Display format must be one of ' .
408 $this->availableDisplayFormats
,
409 $this->availableSubclassDisplayFormats
415 // Evil hack for mobile :(
416 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
420 $this->displayFormat
= $format;
426 * Getter for displayFormat
430 public function getDisplayFormat() {
431 return $this->displayFormat
;
435 * Get the HTMLFormField subclass for this descriptor.
437 * The descriptor can be passed either 'class' which is the name of
438 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
439 * This makes sure the 'class' is always set, and also is returned by
440 * this function for ease.
444 * @param string $fieldname Name of the field
445 * @param array &$descriptor Input Descriptor, as described above
447 * @throws MWException
448 * @return string Name of a HTMLFormField subclass
450 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
451 if ( isset( $descriptor['class'] ) ) {
452 $class = $descriptor['class'];
453 } elseif ( isset( $descriptor['type'] ) ) {
454 $class = static::$typeMappings[$descriptor['type']];
455 $descriptor['class'] = $class;
461 throw new MWException( "Descriptor with no class for $fieldname: "
462 . print_r( $descriptor, true ) );
469 * Initialise a new Object for the field
471 * @param string $fieldname Name of the field
472 * @param array $descriptor Input Descriptor, as described above
473 * @param HTMLForm|null $parent Parent instance of HTMLForm
475 * @throws MWException
476 * @return HTMLFormField Instance of a subclass of HTMLFormField
478 public static function loadInputFromParameters( $fieldname, $descriptor,
479 HTMLForm
$parent = null
481 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
483 $descriptor['fieldname'] = $fieldname;
485 $descriptor['parent'] = $parent;
488 # @todo This will throw a fatal error whenever someone try to use
489 # 'class' to feed a CSS class instead of 'cssclass'. Would be
490 # great to avoid the fatal error and show a nice error.
491 return new $class( $descriptor );
495 * Prepare form for submission.
497 * @warning When doing method chaining, that should be the very last
498 * method call before displayForm().
500 * @throws MWException
501 * @return HTMLForm $this for chaining calls (since 1.20)
503 public function prepareForm() {
504 # Check if we have the info we need
505 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
506 throw new MWException( 'You must call setTitle() on an HTMLForm' );
509 # Load data from the request.
511 $this->mFormIdentifier
=== null ||
512 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
516 $this->mFieldData
= [];
523 * Try submitting, with edit token check first
524 * @return Status|bool
526 public function tryAuthorizedSubmit() {
530 if ( $this->mFormIdentifier
=== null ) {
533 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
537 if ( $this->getMethod() !== 'post' ) {
538 $tokenOkay = true; // no session check needed
539 } elseif ( $this->getRequest()->wasPosted() ) {
540 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
541 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
542 // Session tokens for logged-out users have no security value.
543 // However, if the user gave one, check it in order to give a nice
544 // "session expired" error instead of "permission denied" or such.
545 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
551 if ( $tokenOkay && $identOkay ) {
552 $this->mWasSubmitted
= true;
553 $result = $this->trySubmit();
560 * The here's-one-I-made-earlier option: do the submission if
561 * posted, or display the form with or without funky validation
563 * @return bool|Status Whether submission was successful.
565 public function show() {
566 $this->prepareForm();
568 $result = $this->tryAuthorizedSubmit();
569 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
573 $this->displayForm( $result );
579 * Same as self::show with the difference, that the form will be
580 * added to the output, no matter, if the validation was good or not.
581 * @return bool|Status Whether submission was successful.
583 public function showAlways() {
584 $this->prepareForm();
586 $result = $this->tryAuthorizedSubmit();
588 $this->displayForm( $result );
594 * Validate all the fields, and call the submission callback
595 * function if everything is kosher.
596 * @throws MWException
597 * @return bool|string|array|Status
598 * - Bool true or a good Status object indicates success,
599 * - Bool false indicates no submission was attempted,
600 * - Anything else indicates failure. The value may be a fatal Status
601 * object, an HTML string, or an array of arrays (message keys and
602 * params) or strings (message keys)
604 public function trySubmit() {
606 $hoistedErrors = Status
::newGood();
607 if ( $this->mValidationErrorMessage
) {
608 foreach ( (array)$this->mValidationErrorMessage
as $error ) {
609 call_user_func_array( [ $hoistedErrors, 'fatal' ], $error );
612 $hoistedErrors->fatal( 'htmlform-invalid-input' );
615 $this->mWasSubmitted
= true;
617 # Check for cancelled submission
618 foreach ( $this->mFlatFields
as $fieldname => $field ) {
619 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
622 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
623 $this->mWasSubmitted
= false;
628 # Check for validation
629 foreach ( $this->mFlatFields
as $fieldname => $field ) {
630 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
633 if ( $field->isHidden( $this->mFieldData
) ) {
636 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
637 if ( $res !== true ) {
639 if ( $res !== false && !$field->canDisplayErrors() ) {
640 if ( is_string( $res ) ) {
641 $hoistedErrors->fatal( 'rawmessage', $res );
643 $hoistedErrors->fatal( $res );
650 return $hoistedErrors;
653 $callback = $this->mSubmitCallback
;
654 if ( !is_callable( $callback ) ) {
655 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
656 'setSubmitCallback() to set one.' );
659 $data = $this->filterDataForSubmit( $this->mFieldData
);
661 $res = call_user_func( $callback, $data, $this );
662 if ( $res === false ) {
663 $this->mWasSubmitted
= false;
670 * Test whether the form was considered to have been submitted or not, i.e.
671 * whether the last call to tryAuthorizedSubmit or trySubmit returned
674 * This will return false until HTMLForm::tryAuthorizedSubmit or
675 * HTMLForm::trySubmit is called.
680 public function wasSubmitted() {
681 return $this->mWasSubmitted
;
685 * Set a callback to a function to do something with the form
686 * once it's been successfully validated.
688 * @param callable $cb The function will be passed the output from
689 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
690 * return as documented for HTMLForm::trySubmit
692 * @return HTMLForm $this for chaining calls (since 1.20)
694 public function setSubmitCallback( $cb ) {
695 $this->mSubmitCallback
= $cb;
701 * Set a message to display on a validation error.
703 * @param string|array $msg String or Array of valid inputs to wfMessage()
704 * (so each entry can be either a String or Array)
706 * @return HTMLForm $this for chaining calls (since 1.20)
708 public function setValidationErrorMessage( $msg ) {
709 $this->mValidationErrorMessage
= $msg;
715 * Set the introductory message, overwriting any existing message.
717 * @param string $msg Complete text of message to display
719 * @return HTMLForm $this for chaining calls (since 1.20)
721 public function setIntro( $msg ) {
722 $this->setPreText( $msg );
728 * Set the introductory message HTML, overwriting any existing message.
731 * @param string $msg Complete HTML of message to display
733 * @return HTMLForm $this for chaining calls (since 1.20)
735 public function setPreText( $msg ) {
742 * Add HTML to introductory message.
744 * @param string $msg Complete HTML of message to display
746 * @return HTMLForm $this for chaining calls (since 1.20)
748 public function addPreText( $msg ) {
755 * Add HTML to the header, inside the form.
757 * @param string $msg Additional HTML to display in header
758 * @param string|null $section The section to add the header to
760 * @return HTMLForm $this for chaining calls (since 1.20)
762 public function addHeaderText( $msg, $section = null ) {
763 if ( $section === null ) {
764 $this->mHeader
.= $msg;
766 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
767 $this->mSectionHeaders
[$section] = '';
769 $this->mSectionHeaders
[$section] .= $msg;
776 * Set header text, inside the form.
779 * @param string $msg Complete HTML of header to display
780 * @param string|null $section The section to add the header to
782 * @return HTMLForm $this for chaining calls (since 1.20)
784 public function setHeaderText( $msg, $section = null ) {
785 if ( $section === null ) {
786 $this->mHeader
= $msg;
788 $this->mSectionHeaders
[$section] = $msg;
797 * @param string|null $section The section to get the header text for
799 * @return string HTML
801 public function getHeaderText( $section = null ) {
802 if ( $section === null ) {
803 return $this->mHeader
;
805 return isset( $this->mSectionHeaders
[$section] ) ?
$this->mSectionHeaders
[$section] : '';
810 * Add footer text, inside the form.
812 * @param string $msg Complete text of message to display
813 * @param string|null $section The section to add the footer text to
815 * @return HTMLForm $this for chaining calls (since 1.20)
817 public function addFooterText( $msg, $section = null ) {
818 if ( $section === null ) {
819 $this->mFooter
.= $msg;
821 if ( !isset( $this->mSectionFooters
[$section] ) ) {
822 $this->mSectionFooters
[$section] = '';
824 $this->mSectionFooters
[$section] .= $msg;
831 * Set footer text, inside the form.
834 * @param string $msg Complete text of message to display
835 * @param string|null $section The section to add the footer text to
837 * @return HTMLForm $this for chaining calls (since 1.20)
839 public function setFooterText( $msg, $section = null ) {
840 if ( $section === null ) {
841 $this->mFooter
= $msg;
843 $this->mSectionFooters
[$section] = $msg;
852 * @param string|null $section The section to get the footer text for
856 public function getFooterText( $section = null ) {
857 if ( $section === null ) {
858 return $this->mFooter
;
860 return isset( $this->mSectionFooters
[$section] ) ?
$this->mSectionFooters
[$section] : '';
865 * Add text to the end of the display.
867 * @param string $msg Complete text of message to display
869 * @return HTMLForm $this for chaining calls (since 1.20)
871 public function addPostText( $msg ) {
872 $this->mPost
.= $msg;
878 * Set text at the end of the display.
880 * @param string $msg Complete text of message to display
882 * @return HTMLForm $this for chaining calls (since 1.20)
884 public function setPostText( $msg ) {
891 * Add a hidden field to the output
893 * @param string $name Field name. This will be used exactly as entered
894 * @param string $value Field value
895 * @param array $attribs
897 * @return HTMLForm $this for chaining calls (since 1.20)
899 public function addHiddenField( $name, $value, array $attribs = [] ) {
900 $attribs +
= [ 'name' => $name ];
901 $this->mHiddenFields
[] = [ $value, $attribs ];
907 * Add an array of hidden fields to the output
911 * @param array $fields Associative array of fields to add;
912 * mapping names to their values
914 * @return HTMLForm $this for chaining calls
916 public function addHiddenFields( array $fields ) {
917 foreach ( $fields as $name => $value ) {
918 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
925 * Add a button to the form
927 * @since 1.27 takes an array as shown. Earlier versions accepted
928 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
930 * @note Custom labels ('label', 'label-message', 'label-raw') are not
931 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
932 * they will be served buttons using 'value' as the button label.
933 * @param array $data Data to define the button:
934 * - name: (string) Button name.
935 * - value: (string) Button value.
936 * - label-message: (string, optional) Button label message key to use
937 * instead of 'value'. Overrides 'label' and 'label-raw'.
938 * - label: (string, optional) Button label text to use instead of
939 * 'value'. Overrides 'label-raw'.
940 * - label-raw: (string, optional) Button label HTML to use instead of
942 * - id: (string, optional) DOM id for the button.
943 * - attribs: (array, optional) Additional HTML attributes.
944 * - flags: (string|string[], optional) OOUI flags.
945 * - framed: (boolean=true, optional) OOUI framed attribute.
946 * @return HTMLForm $this for chaining calls (since 1.20)
948 public function addButton( $data ) {
949 if ( !is_array( $data ) ) {
950 $args = func_get_args();
951 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
952 throw new InvalidArgumentException(
953 'Incorrect number of arguments for deprecated calling style'
959 'id' => isset( $args[2] ) ?
$args[2] : null,
960 'attribs' => isset( $args[3] ) ?
$args[3] : null,
963 if ( !isset( $data['name'] ) ) {
964 throw new InvalidArgumentException( 'A name is required' );
966 if ( !isset( $data['value'] ) ) {
967 throw new InvalidArgumentException( 'A value is required' );
970 $this->mButtons
[] = $data +
[
981 * Set the salt for the edit token.
983 * Only useful when the method is "post".
986 * @param string|array $salt Salt to use
987 * @return HTMLForm $this For chaining calls
989 public function setTokenSalt( $salt ) {
990 $this->mTokenSalt
= $salt;
996 * Display the form (sending to the context's OutputPage object), with an
997 * appropriate error message or stack of messages, and any validation errors, etc.
999 * @warning You should call prepareForm() before calling this function.
1000 * Moreover, when doing method chaining this should be the very last method
1001 * call just after prepareForm().
1003 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1005 * @return void Nothing, should be last call
1007 public function displayForm( $submitResult ) {
1008 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1012 * Returns the raw HTML generated by the form
1014 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1016 * @return string HTML
1018 public function getHTML( $submitResult ) {
1019 # For good measure (it is the default)
1020 $this->getOutput()->preventClickjacking();
1021 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1022 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1025 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1026 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1027 . $this->getHeaderText()
1029 . $this->getHiddenFields()
1030 . $this->getButtons()
1031 . $this->getFooterText();
1033 $html = $this->wrapForm( $html );
1035 return '' . $this->mPre
. $html . $this->mPost
;
1039 * Get HTML attributes for the `<form>` tag.
1042 protected function getFormAttributes() {
1043 # Use multipart/form-data
1044 $encType = $this->mUseMultipart
1045 ?
'multipart/form-data'
1046 : 'application/x-www-form-urlencoded';
1049 'class' => 'mw-htmlform',
1050 'action' => $this->getAction(),
1051 'method' => $this->getMethod(),
1052 'enctype' => $encType,
1055 $attribs['id'] = $this->mId
;
1057 if ( is_string( $this->mAutocomplete
) ) {
1058 $attribs['autocomplete'] = $this->mAutocomplete
;
1060 if ( $this->mName
) {
1061 $attribs['name'] = $this->mName
;
1063 if ( $this->needsJSForHtml5FormValidation() ) {
1064 $attribs['novalidate'] = true;
1070 * Wrap the form innards in an actual "<form>" element
1072 * @param string $html HTML contents to wrap.
1074 * @return string Wrapped HTML.
1076 public function wrapForm( $html ) {
1077 # Include a <fieldset> wrapper for style, if requested.
1078 if ( $this->mWrapperLegend
!== false ) {
1079 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1080 $html = Xml
::fieldset( $legend, $html );
1083 return Html
::rawElement(
1085 $this->getFormAttributes(),
1091 * Get the hidden fields that should go inside the form.
1092 * @return string HTML.
1094 public function getHiddenFields() {
1096 if ( $this->mFormIdentifier
!== null ) {
1097 $html .= Html
::hidden(
1099 $this->mFormIdentifier
1102 if ( $this->getMethod() === 'post' ) {
1103 $html .= Html
::hidden(
1105 $this->getUser()->getEditToken( $this->mTokenSalt
),
1106 [ 'id' => 'wpEditToken' ]
1108 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1111 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1112 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1113 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1116 foreach ( $this->mHiddenFields
as $data ) {
1117 list( $value, $attribs ) = $data;
1118 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1125 * Get the submit and (potentially) reset buttons.
1126 * @return string HTML.
1128 public function getButtons() {
1130 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1132 if ( $this->mShowSubmit
) {
1135 if ( isset( $this->mSubmitID
) ) {
1136 $attribs['id'] = $this->mSubmitID
;
1139 if ( isset( $this->mSubmitName
) ) {
1140 $attribs['name'] = $this->mSubmitName
;
1143 if ( isset( $this->mSubmitTooltip
) ) {
1144 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1147 $attribs['class'] = [ 'mw-htmlform-submit' ];
1149 if ( $useMediaWikiUIEverywhere ) {
1150 foreach ( $this->mSubmitFlags
as $flag ) {
1151 $attribs['class'][] = 'mw-ui-' . $flag;
1153 $attribs['class'][] = 'mw-ui-button';
1156 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1159 if ( $this->mShowReset
) {
1160 $buttons .= Html
::element(
1164 'value' => $this->msg( 'htmlform-reset' )->text(),
1165 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1170 if ( $this->mShowCancel
) {
1171 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1172 if ( $target instanceof Title
) {
1173 $target = $target->getLocalURL();
1175 $buttons .= Html
::element(
1178 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1181 $this->msg( 'cancel' )->text()
1185 // IE<8 has bugs with <button>, so we'll need to avoid them.
1186 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1188 foreach ( $this->mButtons
as $button ) {
1191 'name' => $button['name'],
1192 'value' => $button['value']
1195 if ( isset( $button['label-message'] ) ) {
1196 $label = $this->getMessage( $button['label-message'] )->parse();
1197 } elseif ( isset( $button['label'] ) ) {
1198 $label = htmlspecialchars( $button['label'] );
1199 } elseif ( isset( $button['label-raw'] ) ) {
1200 $label = $button['label-raw'];
1202 $label = htmlspecialchars( $button['value'] );
1205 if ( $button['attribs'] ) {
1206 $attrs +
= $button['attribs'];
1209 if ( isset( $button['id'] ) ) {
1210 $attrs['id'] = $button['id'];
1213 if ( $useMediaWikiUIEverywhere ) {
1214 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1215 $attrs['class'][] = 'mw-ui-button';
1219 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1221 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1229 return Html
::rawElement( 'span',
1230 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1234 * Get the whole body of the form.
1237 public function getBody() {
1238 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1242 * Format and display an error message stack.
1244 * @param string|array|Status $errors
1246 * @deprecated since 1.28, use getErrorsOrWarnings() instead
1250 public function getErrors( $errors ) {
1251 wfDeprecated( __METHOD__
);
1252 return $this->getErrorsOrWarnings( $errors, 'error' );
1256 * Returns a formatted list of errors or warnings from the given elements.
1258 * @param string|array|Status $elements The set of errors/warnings to process.
1259 * @param string $elementsType Should warnings or errors be returned. This is meant
1260 * for Status objects, all other valid types are always considered as errors.
1263 public function getErrorsOrWarnings( $elements, $elementsType ) {
1264 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1265 throw new DomainException( $elementsType . ' is not a valid type.' );
1267 $elementstr = false;
1268 if ( $elements instanceof Status
) {
1269 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1270 $status = $elementsType === 'error' ?
$errorStatus : $warningStatus;
1271 if ( $status->isGood() ) {
1274 $elementstr = $this->getOutput()->parse(
1275 $status->getWikiText()
1278 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1279 $elementstr = $this->formatErrors( $elements );
1280 } elseif ( $elementsType === 'error' ) {
1281 $elementstr = $elements;
1285 ? Html
::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1290 * Format a stack of error messages into a single HTML string
1292 * @param array $errors Array of message keys/values
1294 * @return string HTML, a "<ul>" list of errors
1296 public function formatErrors( $errors ) {
1299 foreach ( $errors as $error ) {
1300 $errorstr .= Html
::rawElement(
1303 $this->getMessage( $error )->parse()
1307 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1313 * Set the text for the submit button
1315 * @param string $t Plaintext
1317 * @return HTMLForm $this for chaining calls (since 1.20)
1319 public function setSubmitText( $t ) {
1320 $this->mSubmitText
= $t;
1326 * Identify that the submit button in the form has a destructive action
1329 * @return HTMLForm $this for chaining calls (since 1.28)
1331 public function setSubmitDestructive() {
1332 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1338 * Identify that the submit button in the form has a progressive action
1340 * @deprecated since 1.32, No need to call. Submit button already
1341 * has a progressive action form.
1343 * @return HTMLForm $this for chaining calls (since 1.28)
1345 public function setSubmitProgressive() {
1346 wfDeprecated( __METHOD__
, '1.32' );
1347 $this->mSubmitFlags
= [ 'progressive', 'primary' ];
1353 * Set the text for the submit button to a message
1356 * @param string|Message $msg Message key or Message object
1358 * @return HTMLForm $this for chaining calls (since 1.20)
1360 public function setSubmitTextMsg( $msg ) {
1361 if ( !$msg instanceof Message
) {
1362 $msg = $this->msg( $msg );
1364 $this->setSubmitText( $msg->text() );
1370 * Get the text for the submit button, either customised or a default.
1373 public function getSubmitText() {
1374 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1378 * @param string $name Submit button name
1380 * @return HTMLForm $this for chaining calls (since 1.20)
1382 public function setSubmitName( $name ) {
1383 $this->mSubmitName
= $name;
1389 * @param string $name Tooltip for the submit button
1391 * @return HTMLForm $this for chaining calls (since 1.20)
1393 public function setSubmitTooltip( $name ) {
1394 $this->mSubmitTooltip
= $name;
1400 * Set the id for the submit button.
1404 * @todo FIXME: Integrity of $t is *not* validated
1405 * @return HTMLForm $this for chaining calls (since 1.20)
1407 public function setSubmitID( $t ) {
1408 $this->mSubmitID
= $t;
1414 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1415 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1418 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1419 * was submitted, and not attempt to validate the other ones.
1420 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1421 * HTMLForm to distinguish between the initial page view and a form submission with all
1422 * checkboxes or select options unchecked.
1425 * @param string $ident
1428 public function setFormIdentifier( $ident ) {
1429 $this->mFormIdentifier
= $ident;
1435 * Stop a default submit button being shown for this form. This implies that an
1436 * alternate submit method must be provided manually.
1440 * @param bool $suppressSubmit Set to false to re-enable the button again
1442 * @return HTMLForm $this for chaining calls
1444 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1445 $this->mShowSubmit
= !$suppressSubmit;
1451 * Show a cancel button (or prevent it). The button is not shown by default.
1453 * @return HTMLForm $this for chaining calls
1456 public function showCancel( $show = true ) {
1457 $this->mShowCancel
= $show;
1462 * Sets the target where the user is redirected to after clicking cancel.
1463 * @param Title|string $target Target as a Title object or an URL
1464 * @return HTMLForm $this for chaining calls
1467 public function setCancelTarget( $target ) {
1468 $this->mCancelTarget
= $target;
1473 * Set the id of the \<table\> or outermost \<div\> element.
1477 * @param string $id New value of the id attribute, or "" to remove
1479 * @return HTMLForm $this for chaining calls
1481 public function setTableId( $id ) {
1482 $this->mTableId
= $id;
1488 * @param string $id DOM id for the form
1490 * @return HTMLForm $this for chaining calls (since 1.20)
1492 public function setId( $id ) {
1499 * @param string $name 'name' attribute for the form
1500 * @return HTMLForm $this for chaining calls
1502 public function setName( $name ) {
1503 $this->mName
= $name;
1509 * Prompt the whole form to be wrapped in a "<fieldset>", with
1510 * this text as its "<legend>" element.
1512 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1513 * If true, a wrapper will be displayed, but no legend.
1514 * If a string, a wrapper will be displayed with that string as a legend.
1515 * The string will be escaped before being output (this doesn't support HTML).
1517 * @return HTMLForm $this for chaining calls (since 1.20)
1519 public function setWrapperLegend( $legend ) {
1520 $this->mWrapperLegend
= $legend;
1526 * Prompt the whole form to be wrapped in a "<fieldset>", with
1527 * this message as its "<legend>" element.
1530 * @param string|Message $msg Message key or Message object
1532 * @return HTMLForm $this for chaining calls (since 1.20)
1534 public function setWrapperLegendMsg( $msg ) {
1535 if ( !$msg instanceof Message
) {
1536 $msg = $this->msg( $msg );
1538 $this->setWrapperLegend( $msg->text() );
1544 * Set the prefix for various default messages
1545 * @todo Currently only used for the "<fieldset>" legend on forms
1546 * with multiple sections; should be used elsewhere?
1550 * @return HTMLForm $this for chaining calls (since 1.20)
1552 public function setMessagePrefix( $p ) {
1553 $this->mMessagePrefix
= $p;
1559 * Set the title for form submission
1561 * @param Title $t Title of page the form is on/should be posted to
1563 * @return HTMLForm $this for chaining calls (since 1.20)
1565 public function setTitle( $t ) {
1575 public function getTitle() {
1576 return $this->mTitle
=== false
1577 ?
$this->getContext()->getTitle()
1582 * Set the method used to submit the form
1584 * @param string $method
1586 * @return HTMLForm $this for chaining calls (since 1.20)
1588 public function setMethod( $method = 'post' ) {
1589 $this->mMethod
= strtolower( $method );
1595 * @return string Always lowercase
1597 public function getMethod() {
1598 return $this->mMethod
;
1602 * Wraps the given $section into an user-visible fieldset.
1604 * @param string $legend Legend text for the fieldset
1605 * @param string $section The section content in plain Html
1606 * @param array $attributes Additional attributes for the fieldset
1607 * @return string The fieldset's Html
1609 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1610 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1616 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1618 * @param string $sectionName ID attribute of the "<table>" tag for this
1619 * section, ignored if empty.
1620 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1621 * each subsection, ignored if empty.
1622 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1623 * @throws LogicException When called on uninitialized field data, e.g. When
1624 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1629 public function displaySection( $fields,
1631 $fieldsetIDPrefix = '',
1632 &$hasUserVisibleFields = false
1634 if ( $this->mFieldData
=== null ) {
1635 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1636 . 'You probably called displayForm() without calling prepareForm() first.' );
1639 $displayFormat = $this->getDisplayFormat();
1642 $subsectionHtml = '';
1645 // Conveniently, PHP method names are case-insensitive.
1646 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1647 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1649 foreach ( $fields as $key => $value ) {
1650 if ( $value instanceof HTMLFormField
) {
1651 $v = array_key_exists( $key, $this->mFieldData
)
1652 ?
$this->mFieldData
[$key]
1653 : $value->getDefault();
1655 $retval = $value->$getFieldHtmlMethod( $v );
1657 // check, if the form field should be added to
1659 if ( $value->hasVisibleOutput() ) {
1662 $labelValue = trim( $value->getLabel() );
1663 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1667 $hasUserVisibleFields = true;
1669 } elseif ( is_array( $value ) ) {
1670 $subsectionHasVisibleFields = false;
1672 $this->displaySection( $value,
1674 "$fieldsetIDPrefix$key-",
1675 $subsectionHasVisibleFields );
1678 if ( $subsectionHasVisibleFields === true ) {
1679 // Display the section with various niceties.
1680 $hasUserVisibleFields = true;
1682 $legend = $this->getLegend( $key );
1684 $section = $this->getHeaderText( $key ) .
1686 $this->getFooterText( $key );
1689 if ( $fieldsetIDPrefix ) {
1690 $attributes['id'] = Sanitizer
::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1692 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1694 // Just return the inputs, nothing fancy.
1695 $subsectionHtml .= $section;
1700 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1702 if ( $subsectionHtml ) {
1703 if ( $this->mSubSectionBeforeFields
) {
1704 return $subsectionHtml . "\n" . $html;
1706 return $html . "\n" . $subsectionHtml;
1714 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1715 * @param array $fieldsHtml
1716 * @param string $sectionName
1717 * @param bool $anyFieldHasLabel
1718 * @return string HTML
1720 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1721 if ( !$fieldsHtml ) {
1722 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1723 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1727 $displayFormat = $this->getDisplayFormat();
1728 $html = implode( '', $fieldsHtml );
1730 if ( $displayFormat === 'raw' ) {
1736 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1737 $classes[] = 'mw-htmlform-nolabel';
1741 'class' => implode( ' ', $classes ),
1744 if ( $sectionName ) {
1745 $attribs['id'] = Sanitizer
::escapeIdForAttribute( $sectionName );
1748 if ( $displayFormat === 'table' ) {
1749 return Html
::rawElement( 'table',
1751 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1752 } elseif ( $displayFormat === 'inline' ) {
1753 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1755 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1760 * Construct the form fields from the Descriptor array
1762 public function loadData() {
1765 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1766 $request = $this->getRequest();
1767 if ( $field->skipLoadData( $request ) ) {
1769 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1770 $fieldData[$fieldname] = $field->getDefault();
1772 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1777 foreach ( $fieldData as $name => &$value ) {
1778 $field = $this->mFlatFields
[$name];
1779 $value = $field->filter( $value, $this->mFlatFields
);
1782 $this->mFieldData
= $fieldData;
1786 * Stop a reset button being shown for this form
1788 * @param bool $suppressReset Set to false to re-enable the button again
1790 * @return HTMLForm $this for chaining calls (since 1.20)
1792 public function suppressReset( $suppressReset = true ) {
1793 $this->mShowReset
= !$suppressReset;
1799 * Overload this if you want to apply special filtration routines
1800 * to the form as a whole, after it's submitted but before it's
1803 * @param array $data
1807 public function filterDataForSubmit( $data ) {
1812 * Get a string to go in the "<legend>" of a section fieldset.
1813 * Override this if you want something more complicated.
1815 * @param string $key
1819 public function getLegend( $key ) {
1820 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1824 * Set the value for the action attribute of the form.
1825 * When set to false (which is the default state), the set title is used.
1829 * @param string|bool $action
1831 * @return HTMLForm $this for chaining calls (since 1.20)
1833 public function setAction( $action ) {
1834 $this->mAction
= $action;
1840 * Get the value for the action attribute of the form.
1846 public function getAction() {
1847 // If an action is alredy provided, return it
1848 if ( $this->mAction
!== false ) {
1849 return $this->mAction
;
1852 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1853 // Check whether we are in GET mode and the ArticlePath contains a "?"
1854 // meaning that getLocalURL() would return something like "index.php?title=...".
1855 // As browser remove the query string before submitting GET forms,
1856 // it means that the title would be lost. In such case use wfScript() instead
1857 // and put title in an hidden field (see getHiddenFields()).
1858 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1862 return $this->getTitle()->getLocalURL();
1866 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1867 * When set to null (which is the default state), the attribute get not set.
1871 * @param string|null $autocomplete
1873 * @return HTMLForm $this for chaining calls
1875 public function setAutocomplete( $autocomplete ) {
1876 $this->mAutocomplete
= $autocomplete;
1882 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1883 * name + parameters array) into a Message.
1884 * @param mixed $value
1887 protected function getMessage( $value ) {
1888 return Message
::newFromSpecifier( $value )->setContext( $this );
1892 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1893 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1894 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1895 * agent has JavaScript support, in htmlform.js.
1900 public function needsJSForHtml5FormValidation() {
1901 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1902 if ( $field->needsJSForHtml5FormValidation() ) {