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 * 'id' -- HTML id attribute
52 * 'cssclass' -- CSS class
53 * 'csshelpclass' -- CSS class used to style help text
54 * 'dir' -- Direction of the element.
55 * 'options' -- associative array mapping labels to values.
56 * Some field types support multi-level arrays.
57 * 'options-messages' -- associative array mapping message keys to values.
58 * Some field types support multi-level arrays.
59 * 'options-message' -- message key or object to be parsed to extract the list of
60 * options (like 'ipbreason-dropdown').
61 * 'label-message' -- message key or object for a message to use as the label.
62 * can be an array of msg key and then parameters to
64 * 'label' -- alternatively, a raw text message. Overridden by
66 * 'help' -- message text for a message to use as a help text.
67 * 'help-message' -- message key or object for a message to use as a help text.
68 * can be an array of msg key and then parameters to
70 * Overwrites 'help-messages' and 'help'.
71 * 'help-messages' -- array of message keys/objects. As above, each item can
72 * be an array of msg key and then parameters.
74 * 'notice' -- message text for a message to use as a notice in the field.
75 * Currently used by OOUI form fields only.
76 * 'notice-messages' -- array of message keys/objects to use for notice.
78 * 'notice-message' -- message key or object to use as a notice.
79 * 'required' -- passed through to the object, indicating that it
80 * is a required field.
81 * 'size' -- the length of text fields
82 * 'filter-callback' -- a function name to give you the chance to
83 * massage the inputted value before it's processed.
84 * @see HTMLFormField::filter()
85 * 'validation-callback' -- a function name to give you the chance
86 * to impose extra validation on the field input.
87 * @see HTMLFormField::validate()
88 * 'name' -- By default, the 'name' attribute of the input field
89 * is "wp{$fieldname}". If you want a different name
90 * (eg one without the "wp" prefix), specify it here and
91 * it will be used without modification.
92 * 'hide-if' -- expression given as an array stating when the field
93 * should be hidden. The first array value has to be the
94 * expression's logic operator. Supported expressions:
96 * [ 'NOT', array $expression ]
97 * To hide a field if a given expression is not true.
99 * [ '===', string $fieldName, string $value ]
100 * To hide a field if another field identified by
101 * $field has the value $value.
103 * [ '!==', string $fieldName, string $value ]
104 * Same as [ 'NOT', [ '===', $fieldName, $value ]
105 * 'OR', 'AND', 'NOR', 'NAND'
106 * [ 'XXX', array $expression1, ..., array $expressionN ]
107 * To hide a field if one or more (OR), all (AND),
108 * neither (NOR) or not all (NAND) given expressions
109 * are evaluated as true.
110 * The expressions will be given to a JavaScript frontend
111 * module which will continually update the field's
114 * Since 1.20, you can chain mutators to ease the form generation:
117 * $form = new HTMLForm( $someFields );
118 * $form->setMethod( 'get' )
119 * ->setWrapperLegendMsg( 'message-key' )
121 * ->displayForm( '' );
123 * Note that you will have prepareForm and displayForm at the end. Other
124 * methods call done after that would simply not be part of the form :(
126 * @todo Document 'section' / 'subsection' stuff
128 class HTMLForm
extends ContextSource
{
129 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
130 public static $typeMappings = [
131 'api' => 'HTMLApiField',
132 'text' => 'HTMLTextField',
133 'textwithbutton' => 'HTMLTextFieldWithButton',
134 'textarea' => 'HTMLTextAreaField',
135 'select' => 'HTMLSelectField',
136 'combobox' => 'HTMLComboboxField',
137 'radio' => 'HTMLRadioField',
138 'multiselect' => 'HTMLMultiSelectField',
139 'limitselect' => 'HTMLSelectLimitField',
140 'check' => 'HTMLCheckField',
141 'toggle' => 'HTMLCheckField',
142 'int' => 'HTMLIntField',
143 'float' => 'HTMLFloatField',
144 'info' => 'HTMLInfoField',
145 'selectorother' => 'HTMLSelectOrOtherField',
146 'selectandother' => 'HTMLSelectAndOtherField',
147 'namespaceselect' => 'HTMLSelectNamespace',
148 'namespaceselectwithbutton' => 'HTMLSelectNamespaceWithButton',
149 'tagfilter' => 'HTMLTagFilter',
150 'submit' => 'HTMLSubmitField',
151 'hidden' => 'HTMLHiddenField',
152 'edittools' => 'HTMLEditTools',
153 'checkmatrix' => 'HTMLCheckMatrix',
154 'cloner' => 'HTMLFormFieldCloner',
155 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
156 // HTMLTextField will output the correct type="" attribute automagically.
157 // There are about four zillion other HTML5 input types, like range, but
158 // we don't use those at the moment, so no point in adding all of them.
159 'email' => 'HTMLTextField',
160 'password' => 'HTMLTextField',
161 'url' => 'HTMLTextField',
162 'title' => 'HTMLTitleTextField',
163 'user' => 'HTMLUserTextField',
168 protected $mMessagePrefix;
170 /** @var HTMLFormField[] */
171 protected $mFlatFields;
173 protected $mFieldTree;
174 protected $mShowReset = false;
175 protected $mShowSubmit = true;
176 protected $mSubmitFlags = [ 'constructive', 'primary' ];
177 protected $mShowCancel = false;
178 protected $mCancelTarget;
180 protected $mSubmitCallback;
181 protected $mValidationErrorMessage;
183 protected $mPre = '';
184 protected $mHeader = '';
185 protected $mFooter = '';
186 protected $mSectionHeaders = [];
187 protected $mSectionFooters = [];
188 protected $mPost = '';
191 protected $mTableId = '';
193 protected $mSubmitID;
194 protected $mSubmitName;
195 protected $mSubmitText;
196 protected $mSubmitTooltip;
198 protected $mFormIdentifier;
200 protected $mMethod = 'post';
201 protected $mWasSubmitted = false;
204 * Form action URL. false means we will use the URL to set Title
208 protected $mAction = false;
211 * Form attribute autocomplete. false does not set the attribute
215 protected $mAutocomplete = false;
217 protected $mUseMultipart = false;
218 protected $mHiddenFields = [];
219 protected $mButtons = [];
221 protected $mWrapperLegend = false;
224 * Salt for the edit token.
227 protected $mTokenSalt = '';
230 * If true, sections that contain both fields and subsections will
231 * render their subsections before their fields.
233 * Subclasses may set this to false to render subsections after fields
236 protected $mSubSectionBeforeFields = true;
239 * Format in which to display form. For viable options,
240 * @see $availableDisplayFormats
243 protected $displayFormat = 'table';
246 * Available formats in which to display the form
249 protected $availableDisplayFormats = [
257 * Available formats in which to display the form
260 protected $availableSubclassDisplayFormats = [
266 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
268 * @param string $displayFormat
269 * @param mixed $arguments... Additional arguments to pass to the constructor.
272 public static function factory( $displayFormat/*, $arguments...*/ ) {
273 $arguments = func_get_args();
274 array_shift( $arguments );
276 switch ( $displayFormat ) {
278 return ObjectFactory
::constructClassInstance( VFormHTMLForm
::class, $arguments );
280 return ObjectFactory
::constructClassInstance( OOUIHTMLForm
::class, $arguments );
282 /** @var HTMLForm $form */
283 $form = ObjectFactory
::constructClassInstance( HTMLForm
::class, $arguments );
284 $form->setDisplayFormat( $displayFormat );
290 * Build a new HTMLForm from an array of field attributes
292 * @param array $descriptor Array of Field constructs, as described above
293 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
294 * Obviates the need to call $form->setTitle()
295 * @param string $messagePrefix A prefix to go in front of default messages
297 public function __construct( $descriptor, /*IContextSource*/ $context = null,
300 if ( $context instanceof IContextSource
) {
301 $this->setContext( $context );
302 $this->mTitle
= false; // We don't need them to set a title
303 $this->mMessagePrefix
= $messagePrefix;
304 } elseif ( $context === null && $messagePrefix !== '' ) {
305 $this->mMessagePrefix
= $messagePrefix;
306 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
308 // it's actually $messagePrefix
309 $this->mMessagePrefix
= $context;
312 // Evil hack for mobile :(
314 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
315 && $this->displayFormat
=== 'table'
317 $this->displayFormat
= 'div';
320 // Expand out into a tree.
321 $loadedDescriptor = [];
322 $this->mFlatFields
= [];
324 foreach ( $descriptor as $fieldname => $info ) {
325 $section = isset( $info['section'] )
329 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
330 $this->mUseMultipart
= true;
333 $field = static::loadInputFromParameters( $fieldname, $info, $this );
335 $setSection =& $loadedDescriptor;
337 $sectionParts = explode( '/', $section );
339 while ( count( $sectionParts ) ) {
340 $newName = array_shift( $sectionParts );
342 if ( !isset( $setSection[$newName] ) ) {
343 $setSection[$newName] = [];
346 $setSection =& $setSection[$newName];
350 $setSection[$fieldname] = $field;
351 $this->mFlatFields
[$fieldname] = $field;
354 $this->mFieldTree
= $loadedDescriptor;
358 * @param string $fieldname
361 public function hasField( $fieldname ) {
362 return isset( $this->mFlatFields
[$fieldname] );
366 * @param string $fieldname
367 * @return HTMLFormField
368 * @throws DomainException on invalid field name
370 public function getField( $fieldname ) {
371 if ( !$this->hasField( $fieldname ) ) {
372 throw new DomainException( __METHOD__
. ': no field named ' . $fieldname );
374 return $this->mFlatFields
[$fieldname];
378 * Set format in which to display the form
380 * @param string $format The name of the format to use, must be one of
381 * $this->availableDisplayFormats
383 * @throws MWException
385 * @return HTMLForm $this for chaining calls (since 1.20)
387 public function setDisplayFormat( $format ) {
389 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
390 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
392 throw new MWException( 'Cannot change display format after creation, ' .
393 'use HTMLForm::factory() instead' );
396 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
397 throw new MWException( 'Display format must be one of ' .
398 print_r( $this->availableDisplayFormats
, true ) );
401 // Evil hack for mobile :(
402 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
406 $this->displayFormat
= $format;
412 * Getter for displayFormat
416 public function getDisplayFormat() {
417 return $this->displayFormat
;
421 * Test if displayFormat is 'vform'
423 * @deprecated since 1.25
426 public function isVForm() {
427 wfDeprecated( __METHOD__
, '1.25' );
432 * Get the HTMLFormField subclass for this descriptor.
434 * The descriptor can be passed either 'class' which is the name of
435 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
436 * This makes sure the 'class' is always set, and also is returned by
437 * this function for ease.
441 * @param string $fieldname Name of the field
442 * @param array $descriptor Input Descriptor, as described above
444 * @throws MWException
445 * @return string Name of a HTMLFormField subclass
447 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
448 if ( isset( $descriptor['class'] ) ) {
449 $class = $descriptor['class'];
450 } elseif ( isset( $descriptor['type'] ) ) {
451 $class = static::$typeMappings[$descriptor['type']];
452 $descriptor['class'] = $class;
458 throw new MWException( "Descriptor with no class for $fieldname: "
459 . print_r( $descriptor, true ) );
466 * Initialise a new Object for the field
468 * @param string $fieldname Name of the field
469 * @param array $descriptor Input Descriptor, as described above
470 * @param HTMLForm|null $parent Parent instance of HTMLForm
472 * @throws MWException
473 * @return HTMLFormField Instance of a subclass of HTMLFormField
475 public static function loadInputFromParameters( $fieldname, $descriptor,
476 HTMLForm
$parent = null
478 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
480 $descriptor['fieldname'] = $fieldname;
482 $descriptor['parent'] = $parent;
485 # @todo This will throw a fatal error whenever someone try to use
486 # 'class' to feed a CSS class instead of 'cssclass'. Would be
487 # great to avoid the fatal error and show a nice error.
488 return new $class( $descriptor );
492 * Prepare form for submission.
494 * @attention When doing method chaining, that should be the very last
495 * method call before displayForm().
497 * @throws MWException
498 * @return HTMLForm $this for chaining calls (since 1.20)
500 public function prepareForm() {
501 # Check if we have the info we need
502 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
503 throw new MWException( 'You must call setTitle() on an HTMLForm' );
506 # Load data from the request.
508 $this->mFormIdentifier
=== null ||
509 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
513 $this->mFieldData
= [];
520 * Try submitting, with edit token check first
521 * @return Status|bool
523 public function tryAuthorizedSubmit() {
527 if ( $this->mFormIdentifier
=== null ) {
530 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
534 if ( $this->getMethod() !== 'post' ) {
535 $tokenOkay = true; // no session check needed
536 } elseif ( $this->getRequest()->wasPosted() ) {
537 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
538 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
539 // Session tokens for logged-out users have no security value.
540 // However, if the user gave one, check it in order to give a nice
541 // "session expired" error instead of "permission denied" or such.
542 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
548 if ( $tokenOkay && $identOkay ) {
549 $this->mWasSubmitted
= true;
550 $result = $this->trySubmit();
557 * The here's-one-I-made-earlier option: do the submission if
558 * posted, or display the form with or without funky validation
560 * @return bool|Status Whether submission was successful.
562 public function show() {
563 $this->prepareForm();
565 $result = $this->tryAuthorizedSubmit();
566 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
570 $this->displayForm( $result );
576 * Same as self::show with the difference, that the form will be
577 * added to the output, no matter, if the validation was good or not.
578 * @return bool|Status Whether submission was successful.
580 public function showAlways() {
581 $this->prepareForm();
583 $result = $this->tryAuthorizedSubmit();
585 $this->displayForm( $result );
591 * Validate all the fields, and call the submission callback
592 * function if everything is kosher.
593 * @throws MWException
594 * @return bool|string|array|Status
595 * - Bool true or a good Status object indicates success,
596 * - Bool false indicates no submission was attempted,
597 * - Anything else indicates failure. The value may be a fatal Status
598 * object, an HTML string, or an array of arrays (message keys and
599 * params) or strings (message keys)
601 public function trySubmit() {
604 $hoistedErrors[] = isset( $this->mValidationErrorMessage
)
605 ?
$this->mValidationErrorMessage
606 : [ 'htmlform-invalid-input' ];
608 $this->mWasSubmitted
= true;
610 # Check for cancelled submission
611 foreach ( $this->mFlatFields
as $fieldname => $field ) {
612 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
615 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
616 $this->mWasSubmitted
= false;
621 # Check for validation
622 foreach ( $this->mFlatFields
as $fieldname => $field ) {
623 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
626 if ( $field->isHidden( $this->mFieldData
) ) {
629 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
630 if ( $res !== true ) {
632 if ( $res !== false && !$field->canDisplayErrors() ) {
633 $hoistedErrors[] = [ 'rawmessage', $res ];
639 if ( count( $hoistedErrors ) === 1 ) {
640 $hoistedErrors = $hoistedErrors[0];
642 return $hoistedErrors;
645 $callback = $this->mSubmitCallback
;
646 if ( !is_callable( $callback ) ) {
647 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
648 'setSubmitCallback() to set one.' );
651 $data = $this->filterDataForSubmit( $this->mFieldData
);
653 $res = call_user_func( $callback, $data, $this );
654 if ( $res === false ) {
655 $this->mWasSubmitted
= false;
662 * Test whether the form was considered to have been submitted or not, i.e.
663 * whether the last call to tryAuthorizedSubmit or trySubmit returned
666 * This will return false until HTMLForm::tryAuthorizedSubmit or
667 * HTMLForm::trySubmit is called.
672 public function wasSubmitted() {
673 return $this->mWasSubmitted
;
677 * Set a callback to a function to do something with the form
678 * once it's been successfully validated.
680 * @param callable $cb The function will be passed the output from
681 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
682 * return as documented for HTMLForm::trySubmit
684 * @return HTMLForm $this for chaining calls (since 1.20)
686 public function setSubmitCallback( $cb ) {
687 $this->mSubmitCallback
= $cb;
693 * Set a message to display on a validation error.
695 * @param string|array $msg String or Array of valid inputs to wfMessage()
696 * (so each entry can be either a String or Array)
698 * @return HTMLForm $this for chaining calls (since 1.20)
700 public function setValidationErrorMessage( $msg ) {
701 $this->mValidationErrorMessage
= $msg;
707 * Set the introductory message, overwriting any existing message.
709 * @param string $msg Complete text of message to display
711 * @return HTMLForm $this for chaining calls (since 1.20)
713 public function setIntro( $msg ) {
714 $this->setPreText( $msg );
720 * Set the introductory message HTML, overwriting any existing message.
723 * @param string $msg Complete HTML of message to display
725 * @return HTMLForm $this for chaining calls (since 1.20)
727 public function setPreText( $msg ) {
734 * Add HTML to introductory message.
736 * @param string $msg Complete HTML of message to display
738 * @return HTMLForm $this for chaining calls (since 1.20)
740 public function addPreText( $msg ) {
747 * Add HTML to the header, inside the form.
749 * @param string $msg Additional HTML to display in header
750 * @param string|null $section The section to add the header to
752 * @return HTMLForm $this for chaining calls (since 1.20)
754 public function addHeaderText( $msg, $section = null ) {
755 if ( $section === null ) {
756 $this->mHeader
.= $msg;
758 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
759 $this->mSectionHeaders
[$section] = '';
761 $this->mSectionHeaders
[$section] .= $msg;
768 * Set header text, inside the form.
771 * @param string $msg Complete HTML of header to display
772 * @param string|null $section The section to add the header to
774 * @return HTMLForm $this for chaining calls (since 1.20)
776 public function setHeaderText( $msg, $section = null ) {
777 if ( $section === null ) {
778 $this->mHeader
= $msg;
780 $this->mSectionHeaders
[$section] = $msg;
789 * @param string|null $section The section to get the header text for
791 * @return string HTML
793 public function getHeaderText( $section = null ) {
794 if ( $section === null ) {
795 return $this->mHeader
;
797 return isset( $this->mSectionHeaders
[$section] ) ?
$this->mSectionHeaders
[$section] : '';
802 * Add footer text, inside the form.
804 * @param string $msg Complete text of message to display
805 * @param string|null $section The section to add the footer text to
807 * @return HTMLForm $this for chaining calls (since 1.20)
809 public function addFooterText( $msg, $section = null ) {
810 if ( $section === null ) {
811 $this->mFooter
.= $msg;
813 if ( !isset( $this->mSectionFooters
[$section] ) ) {
814 $this->mSectionFooters
[$section] = '';
816 $this->mSectionFooters
[$section] .= $msg;
823 * Set footer text, inside the form.
826 * @param string $msg Complete text of message to display
827 * @param string|null $section The section to add the footer text to
829 * @return HTMLForm $this for chaining calls (since 1.20)
831 public function setFooterText( $msg, $section = null ) {
832 if ( $section === null ) {
833 $this->mFooter
= $msg;
835 $this->mSectionFooters
[$section] = $msg;
844 * @param string|null $section The section to get the footer text for
848 public function getFooterText( $section = null ) {
849 if ( $section === null ) {
850 return $this->mFooter
;
852 return isset( $this->mSectionFooters
[$section] ) ?
$this->mSectionFooters
[$section] : '';
857 * Add text to the end of the display.
859 * @param string $msg Complete text of message to display
861 * @return HTMLForm $this for chaining calls (since 1.20)
863 public function addPostText( $msg ) {
864 $this->mPost
.= $msg;
870 * Set text at the end of the display.
872 * @param string $msg Complete text of message to display
874 * @return HTMLForm $this for chaining calls (since 1.20)
876 public function setPostText( $msg ) {
883 * Add a hidden field to the output
885 * @param string $name Field name. This will be used exactly as entered
886 * @param string $value Field value
887 * @param array $attribs
889 * @return HTMLForm $this for chaining calls (since 1.20)
891 public function addHiddenField( $name, $value, array $attribs = [] ) {
892 $attribs +
= [ 'name' => $name ];
893 $this->mHiddenFields
[] = [ $value, $attribs ];
899 * Add an array of hidden fields to the output
903 * @param array $fields Associative array of fields to add;
904 * mapping names to their values
906 * @return HTMLForm $this for chaining calls
908 public function addHiddenFields( array $fields ) {
909 foreach ( $fields as $name => $value ) {
910 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
917 * Add a button to the form
919 * @since 1.27 takes an array as shown. Earlier versions accepted
920 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
922 * @note Custom labels ('label', 'label-message', 'label-raw') are not
923 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
924 * they will be served buttons using 'value' as the button label.
925 * @param array $data Data to define the button:
926 * - name: (string) Button name.
927 * - value: (string) Button value.
928 * - label-message: (string, optional) Button label message key to use
929 * instead of 'value'. Overrides 'label' and 'label-raw'.
930 * - label: (string, optional) Button label text to use instead of
931 * 'value'. Overrides 'label-raw'.
932 * - label-raw: (string, optional) Button label HTML to use instead of
934 * - id: (string, optional) DOM id for the button.
935 * - attribs: (array, optional) Additional HTML attributes.
936 * - flags: (string|string[], optional) OOUI flags.
937 * - framed: (boolean=true, optional) OOUI framed attribute.
938 * @return HTMLForm $this for chaining calls (since 1.20)
940 public function addButton( $data ) {
941 if ( !is_array( $data ) ) {
942 $args = func_get_args();
943 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
944 throw new InvalidArgumentException(
945 'Incorrect number of arguments for deprecated calling style'
951 'id' => isset( $args[2] ) ?
$args[2] : null,
952 'attribs' => isset( $args[3] ) ?
$args[3] : null,
955 if ( !isset( $data['name'] ) ) {
956 throw new InvalidArgumentException( 'A name is required' );
958 if ( !isset( $data['value'] ) ) {
959 throw new InvalidArgumentException( 'A value is required' );
962 $this->mButtons
[] = $data +
[
973 * Set the salt for the edit token.
975 * Only useful when the method is "post".
978 * @param string|array $salt Salt to use
979 * @return HTMLForm $this For chaining calls
981 public function setTokenSalt( $salt ) {
982 $this->mTokenSalt
= $salt;
988 * Display the form (sending to the context's OutputPage object), with an
989 * appropriate error message or stack of messages, and any validation errors, etc.
991 * @attention You should call prepareForm() before calling this function.
992 * Moreover, when doing method chaining this should be the very last method
993 * call just after prepareForm().
995 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
997 * @return void Nothing, should be last call
999 public function displayForm( $submitResult ) {
1000 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1004 * Returns the raw HTML generated by the form
1006 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1008 * @return string HTML
1010 public function getHTML( $submitResult ) {
1011 # For good measure (it is the default)
1012 $this->getOutput()->preventClickjacking();
1013 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1014 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1017 . $this->getErrors( $submitResult )
1018 . $this->getHeaderText()
1020 . $this->getHiddenFields()
1021 . $this->getButtons()
1022 . $this->getFooterText();
1024 $html = $this->wrapForm( $html );
1026 return '' . $this->mPre
. $html . $this->mPost
;
1030 * Get HTML attributes for the `<form>` tag.
1033 protected function getFormAttributes() {
1034 # Use multipart/form-data
1035 $encType = $this->mUseMultipart
1036 ?
'multipart/form-data'
1037 : 'application/x-www-form-urlencoded';
1040 'action' => $this->getAction(),
1041 'method' => $this->getMethod(),
1042 'enctype' => $encType,
1045 $attribs['id'] = $this->mId
;
1047 if ( $this->mAutocomplete
) {
1048 $attribs['autocomplete'] = $this->mAutocomplete
;
1050 if ( $this->mName
) {
1051 $attribs['name'] = $this->mName
;
1057 * Wrap the form innards in an actual "<form>" element
1059 * @param string $html HTML contents to wrap.
1061 * @return string Wrapped HTML.
1063 public function wrapForm( $html ) {
1064 # Include a <fieldset> wrapper for style, if requested.
1065 if ( $this->mWrapperLegend
!== false ) {
1066 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1067 $html = Xml
::fieldset( $legend, $html );
1070 return Html
::rawElement(
1072 $this->getFormAttributes() +
[ 'class' => 'visualClear' ],
1078 * Get the hidden fields that should go inside the form.
1079 * @return string HTML.
1081 public function getHiddenFields() {
1083 if ( $this->mFormIdentifier
!== null ) {
1084 $html .= Html
::hidden(
1086 $this->mFormIdentifier
1089 if ( $this->getMethod() === 'post' ) {
1090 $html .= Html
::hidden(
1092 $this->getUser()->getEditToken( $this->mTokenSalt
),
1093 [ 'id' => 'wpEditToken' ]
1095 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1098 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1099 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1100 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1103 foreach ( $this->mHiddenFields
as $data ) {
1104 list( $value, $attribs ) = $data;
1105 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1112 * Get the submit and (potentially) reset buttons.
1113 * @return string HTML.
1115 public function getButtons() {
1117 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1119 if ( $this->mShowSubmit
) {
1122 if ( isset( $this->mSubmitID
) ) {
1123 $attribs['id'] = $this->mSubmitID
;
1126 if ( isset( $this->mSubmitName
) ) {
1127 $attribs['name'] = $this->mSubmitName
;
1130 if ( isset( $this->mSubmitTooltip
) ) {
1131 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1134 $attribs['class'] = [ 'mw-htmlform-submit' ];
1136 if ( $useMediaWikiUIEverywhere ) {
1137 foreach ( $this->mSubmitFlags
as $flag ) {
1138 $attribs['class'][] = 'mw-ui-' . $flag;
1140 $attribs['class'][] = 'mw-ui-button';
1143 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1146 if ( $this->mShowReset
) {
1147 $buttons .= Html
::element(
1151 'value' => $this->msg( 'htmlform-reset' )->text(),
1152 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1157 if ( $this->mShowCancel
) {
1158 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1159 if ( $target instanceof Title
) {
1160 $target = $target->getLocalURL();
1162 $buttons .= Html
::element(
1165 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1168 $this->msg( 'cancel' )->text()
1172 // IE<8 has bugs with <button>, so we'll need to avoid them.
1173 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1175 foreach ( $this->mButtons
as $button ) {
1178 'name' => $button['name'],
1179 'value' => $button['value']
1182 if ( isset( $button['label-message'] ) ) {
1183 $label = $this->getMessage( $button['label-message'] )->parse();
1184 } elseif ( isset( $button['label'] ) ) {
1185 $label = htmlspecialchars( $button['label'] );
1186 } elseif ( isset( $button['label-raw'] ) ) {
1187 $label = $button['label-raw'];
1189 $label = htmlspecialchars( $button['value'] );
1192 if ( $button['attribs'] ) {
1193 $attrs +
= $button['attribs'];
1196 if ( isset( $button['id'] ) ) {
1197 $attrs['id'] = $button['id'];
1200 if ( $useMediaWikiUIEverywhere ) {
1201 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1202 $attrs['class'][] = 'mw-ui-button';
1206 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1208 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1216 return Html
::rawElement( 'span',
1217 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1221 * Get the whole body of the form.
1224 public function getBody() {
1225 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1229 * Format and display an error message stack.
1231 * @param string|array|Status $errors
1235 public function getErrors( $errors ) {
1236 if ( $errors instanceof Status
) {
1237 if ( $errors->isOK() ) {
1240 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1242 } elseif ( is_array( $errors ) ) {
1243 $errorstr = $this->formatErrors( $errors );
1245 $errorstr = $errors;
1249 ? Html
::rawElement( 'div', [ 'class' => 'error' ], $errorstr )
1254 * Format a stack of error messages into a single HTML string
1256 * @param array $errors Array of message keys/values
1258 * @return string HTML, a "<ul>" list of errors
1260 public function formatErrors( $errors ) {
1263 foreach ( $errors as $error ) {
1264 $errorstr .= Html
::rawElement(
1267 $this->getMessage( $error )->parse()
1271 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1277 * Set the text for the submit button
1279 * @param string $t Plaintext
1281 * @return HTMLForm $this for chaining calls (since 1.20)
1283 public function setSubmitText( $t ) {
1284 $this->mSubmitText
= $t;
1290 * Identify that the submit button in the form has a destructive action
1293 * @return HTMLForm $this for chaining calls (since 1.28)
1295 public function setSubmitDestructive() {
1296 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1302 * Identify that the submit button in the form has a progressive action
1305 * @return HTMLForm $this for chaining calls (since 1.28)
1307 public function setSubmitProgressive() {
1308 $this->mSubmitFlags
= [ 'progressive', 'primary' ];
1314 * Set the text for the submit button to a message
1317 * @param string|Message $msg Message key or Message object
1319 * @return HTMLForm $this for chaining calls (since 1.20)
1321 public function setSubmitTextMsg( $msg ) {
1322 if ( !$msg instanceof Message
) {
1323 $msg = $this->msg( $msg );
1325 $this->setSubmitText( $msg->text() );
1331 * Get the text for the submit button, either customised or a default.
1334 public function getSubmitText() {
1335 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1339 * @param string $name Submit button name
1341 * @return HTMLForm $this for chaining calls (since 1.20)
1343 public function setSubmitName( $name ) {
1344 $this->mSubmitName
= $name;
1350 * @param string $name Tooltip for the submit button
1352 * @return HTMLForm $this for chaining calls (since 1.20)
1354 public function setSubmitTooltip( $name ) {
1355 $this->mSubmitTooltip
= $name;
1361 * Set the id for the submit button.
1365 * @todo FIXME: Integrity of $t is *not* validated
1366 * @return HTMLForm $this for chaining calls (since 1.20)
1368 public function setSubmitID( $t ) {
1369 $this->mSubmitID
= $t;
1375 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1376 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1379 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1380 * was submitted, and not attempt to validate the other ones.
1381 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1382 * HTMLForm to distinguish between the initial page view and a form submission with all
1383 * checkboxes or select options unchecked.
1386 * @param string $ident
1389 public function setFormIdentifier( $ident ) {
1390 $this->mFormIdentifier
= $ident;
1396 * Stop a default submit button being shown for this form. This implies that an
1397 * alternate submit method must be provided manually.
1401 * @param bool $suppressSubmit Set to false to re-enable the button again
1403 * @return HTMLForm $this for chaining calls
1405 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1406 $this->mShowSubmit
= !$suppressSubmit;
1412 * Show a cancel button (or prevent it). The button is not shown by default.
1414 * @return HTMLForm $this for chaining calls
1417 public function showCancel( $show = true ) {
1418 $this->mShowCancel
= $show;
1423 * Sets the target where the user is redirected to after clicking cancel.
1424 * @param Title|string $target Target as a Title object or an URL
1425 * @return HTMLForm $this for chaining calls
1428 public function setCancelTarget( $target ) {
1429 $this->mCancelTarget
= $target;
1434 * Set the id of the \<table\> or outermost \<div\> element.
1438 * @param string $id New value of the id attribute, or "" to remove
1440 * @return HTMLForm $this for chaining calls
1442 public function setTableId( $id ) {
1443 $this->mTableId
= $id;
1449 * @param string $id DOM id for the form
1451 * @return HTMLForm $this for chaining calls (since 1.20)
1453 public function setId( $id ) {
1460 * @param string $name 'name' attribute for the form
1461 * @return HTMLForm $this for chaining calls
1463 public function setName( $name ) {
1464 $this->mName
= $name;
1470 * Prompt the whole form to be wrapped in a "<fieldset>", with
1471 * this text as its "<legend>" element.
1473 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1474 * If true, a wrapper will be displayed, but no legend.
1475 * If a string, a wrapper will be displayed with that string as a legend.
1476 * The string will be escaped before being output (this doesn't support HTML).
1478 * @return HTMLForm $this for chaining calls (since 1.20)
1480 public function setWrapperLegend( $legend ) {
1481 $this->mWrapperLegend
= $legend;
1487 * Prompt the whole form to be wrapped in a "<fieldset>", with
1488 * this message as its "<legend>" element.
1491 * @param string|Message $msg Message key or Message object
1493 * @return HTMLForm $this for chaining calls (since 1.20)
1495 public function setWrapperLegendMsg( $msg ) {
1496 if ( !$msg instanceof Message
) {
1497 $msg = $this->msg( $msg );
1499 $this->setWrapperLegend( $msg->text() );
1505 * Set the prefix for various default messages
1506 * @todo Currently only used for the "<fieldset>" legend on forms
1507 * with multiple sections; should be used elsewhere?
1511 * @return HTMLForm $this for chaining calls (since 1.20)
1513 public function setMessagePrefix( $p ) {
1514 $this->mMessagePrefix
= $p;
1520 * Set the title for form submission
1522 * @param Title $t Title of page the form is on/should be posted to
1524 * @return HTMLForm $this for chaining calls (since 1.20)
1526 public function setTitle( $t ) {
1536 public function getTitle() {
1537 return $this->mTitle
=== false
1538 ?
$this->getContext()->getTitle()
1543 * Set the method used to submit the form
1545 * @param string $method
1547 * @return HTMLForm $this for chaining calls (since 1.20)
1549 public function setMethod( $method = 'post' ) {
1550 $this->mMethod
= strtolower( $method );
1556 * @return string Always lowercase
1558 public function getMethod() {
1559 return $this->mMethod
;
1563 * Wraps the given $section into an user-visible fieldset.
1565 * @param string $legend Legend text for the fieldset
1566 * @param string $section The section content in plain Html
1567 * @param array $attributes Additional attributes for the fieldset
1568 * @return string The fieldset's Html
1570 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1571 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1577 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1579 * @param string $sectionName ID attribute of the "<table>" tag for this
1580 * section, ignored if empty.
1581 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1582 * each subsection, ignored if empty.
1583 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1584 * @throws LogicException When called on uninitialized field data, e.g. When
1585 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1590 public function displaySection( $fields,
1592 $fieldsetIDPrefix = '',
1593 &$hasUserVisibleFields = false
1595 if ( $this->mFieldData
=== null ) {
1596 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1597 . 'You probably called displayForm() without calling prepareForm() first.' );
1600 $displayFormat = $this->getDisplayFormat();
1603 $subsectionHtml = '';
1606 // Conveniently, PHP method names are case-insensitive.
1607 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1608 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1610 foreach ( $fields as $key => $value ) {
1611 if ( $value instanceof HTMLFormField
) {
1612 $v = array_key_exists( $key, $this->mFieldData
)
1613 ?
$this->mFieldData
[$key]
1614 : $value->getDefault();
1616 $retval = $value->$getFieldHtmlMethod( $v );
1618 // check, if the form field should be added to
1620 if ( $value->hasVisibleOutput() ) {
1623 $labelValue = trim( $value->getLabel() );
1624 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1628 $hasUserVisibleFields = true;
1630 } elseif ( is_array( $value ) ) {
1631 $subsectionHasVisibleFields = false;
1633 $this->displaySection( $value,
1635 "$fieldsetIDPrefix$key-",
1636 $subsectionHasVisibleFields );
1639 if ( $subsectionHasVisibleFields === true ) {
1640 // Display the section with various niceties.
1641 $hasUserVisibleFields = true;
1643 $legend = $this->getLegend( $key );
1645 $section = $this->getHeaderText( $key ) .
1647 $this->getFooterText( $key );
1650 if ( $fieldsetIDPrefix ) {
1651 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1653 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1655 // Just return the inputs, nothing fancy.
1656 $subsectionHtml .= $section;
1661 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1663 if ( $subsectionHtml ) {
1664 if ( $this->mSubSectionBeforeFields
) {
1665 return $subsectionHtml . "\n" . $html;
1667 return $html . "\n" . $subsectionHtml;
1675 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1676 * @param array $fieldsHtml
1677 * @param string $sectionName
1678 * @param bool $anyFieldHasLabel
1679 * @return string HTML
1681 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1682 $displayFormat = $this->getDisplayFormat();
1683 $html = implode( '', $fieldsHtml );
1685 if ( $displayFormat === 'raw' ) {
1691 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1692 $classes[] = 'mw-htmlform-nolabel';
1696 'class' => implode( ' ', $classes ),
1699 if ( $sectionName ) {
1700 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1703 if ( $displayFormat === 'table' ) {
1704 return Html
::rawElement( 'table',
1706 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1707 } elseif ( $displayFormat === 'inline' ) {
1708 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1710 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1715 * Construct the form fields from the Descriptor array
1717 public function loadData() {
1720 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1721 $request = $this->getRequest();
1722 if ( $field->skipLoadData( $request ) ) {
1724 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1725 $fieldData[$fieldname] = $field->getDefault();
1727 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1732 foreach ( $fieldData as $name => &$value ) {
1733 $field = $this->mFlatFields
[$name];
1734 $value = $field->filter( $value, $this->mFlatFields
);
1737 $this->mFieldData
= $fieldData;
1741 * Stop a reset button being shown for this form
1743 * @param bool $suppressReset Set to false to re-enable the button again
1745 * @return HTMLForm $this for chaining calls (since 1.20)
1747 public function suppressReset( $suppressReset = true ) {
1748 $this->mShowReset
= !$suppressReset;
1754 * Overload this if you want to apply special filtration routines
1755 * to the form as a whole, after it's submitted but before it's
1758 * @param array $data
1762 public function filterDataForSubmit( $data ) {
1767 * Get a string to go in the "<legend>" of a section fieldset.
1768 * Override this if you want something more complicated.
1770 * @param string $key
1774 public function getLegend( $key ) {
1775 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1779 * Set the value for the action attribute of the form.
1780 * When set to false (which is the default state), the set title is used.
1784 * @param string|bool $action
1786 * @return HTMLForm $this for chaining calls (since 1.20)
1788 public function setAction( $action ) {
1789 $this->mAction
= $action;
1795 * Get the value for the action attribute of the form.
1801 public function getAction() {
1802 // If an action is alredy provided, return it
1803 if ( $this->mAction
!== false ) {
1804 return $this->mAction
;
1807 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1808 // Check whether we are in GET mode and the ArticlePath contains a "?"
1809 // meaning that getLocalURL() would return something like "index.php?title=...".
1810 // As browser remove the query string before submitting GET forms,
1811 // it means that the title would be lost. In such case use wfScript() instead
1812 // and put title in an hidden field (see getHiddenFields()).
1813 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1817 return $this->getTitle()->getLocalURL();
1821 * Set the value for the autocomplete attribute of the form.
1822 * When set to false (which is the default state), the attribute get not set.
1826 * @param string|bool $autocomplete
1828 * @return HTMLForm $this for chaining calls
1830 public function setAutocomplete( $autocomplete ) {
1831 $this->mAutocomplete
= $autocomplete;
1837 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1838 * name + parameters array) into a Message.
1839 * @param mixed $value
1842 protected function getMessage( $value ) {
1843 return Message
::newFromSpecifier( $value )->setContext( $this );