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 * 'required' -- passed through to the object, indicating that it
75 * is a required field.
76 * 'size' -- the length of text fields
77 * 'filter-callback' -- a function name to give you the chance to
78 * massage the inputted value before it's processed.
79 * @see HTMLFormField::filter()
80 * 'validation-callback' -- a function name to give you the chance
81 * to impose extra validation on the field input.
82 * @see HTMLFormField::validate()
83 * 'name' -- By default, the 'name' attribute of the input field
84 * is "wp{$fieldname}". If you want a different name
85 * (eg one without the "wp" prefix), specify it here and
86 * it will be used without modification.
87 * 'hide-if' -- expression given as an array stating when the field
88 * should be hidden. The first array value has to be the
89 * expression's logic operator. Supported expressions:
91 * [ 'NOT', array $expression ]
92 * To hide a field if a given expression is not true.
94 * [ '===', string $fieldName, string $value ]
95 * To hide a field if another field identified by
96 * $field has the value $value.
98 * [ '!==', string $fieldName, string $value ]
99 * Same as [ 'NOT', [ '===', $fieldName, $value ]
100 * 'OR', 'AND', 'NOR', 'NAND'
101 * [ 'XXX', array $expression1, ..., array $expressionN ]
102 * To hide a field if one or more (OR), all (AND),
103 * neither (NOR) or not all (NAND) given expressions
104 * are evaluated as true.
105 * The expressions will be given to a JavaScript frontend
106 * module which will continually update the field's
109 * Since 1.20, you can chain mutators to ease the form generation:
112 * $form = new HTMLForm( $someFields );
113 * $form->setMethod( 'get' )
114 * ->setWrapperLegendMsg( 'message-key' )
116 * ->displayForm( '' );
118 * Note that you will have prepareForm and displayForm at the end. Other
119 * methods call done after that would simply not be part of the form :(
121 * @todo Document 'section' / 'subsection' stuff
123 class HTMLForm
extends ContextSource
{
124 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
125 public static $typeMappings = [
126 'api' => 'HTMLApiField',
127 'text' => 'HTMLTextField',
128 'textwithbutton' => 'HTMLTextFieldWithButton',
129 'textarea' => 'HTMLTextAreaField',
130 'select' => 'HTMLSelectField',
131 'combobox' => 'HTMLComboboxField',
132 'radio' => 'HTMLRadioField',
133 'multiselect' => 'HTMLMultiSelectField',
134 'limitselect' => 'HTMLSelectLimitField',
135 'check' => 'HTMLCheckField',
136 'toggle' => 'HTMLCheckField',
137 'int' => 'HTMLIntField',
138 'float' => 'HTMLFloatField',
139 'info' => 'HTMLInfoField',
140 'selectorother' => 'HTMLSelectOrOtherField',
141 'selectandother' => 'HTMLSelectAndOtherField',
142 'namespaceselect' => 'HTMLSelectNamespace',
143 'namespaceselectwithbutton' => 'HTMLSelectNamespaceWithButton',
144 'tagfilter' => 'HTMLTagFilter',
145 'submit' => 'HTMLSubmitField',
146 'hidden' => 'HTMLHiddenField',
147 'edittools' => 'HTMLEditTools',
148 'checkmatrix' => 'HTMLCheckMatrix',
149 'cloner' => 'HTMLFormFieldCloner',
150 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
151 // HTMLTextField will output the correct type="" attribute automagically.
152 // There are about four zillion other HTML5 input types, like range, but
153 // we don't use those at the moment, so no point in adding all of them.
154 'email' => 'HTMLTextField',
155 'password' => 'HTMLTextField',
156 'url' => 'HTMLTextField',
157 'title' => 'HTMLTitleTextField',
158 'user' => 'HTMLUserTextField',
163 protected $mMessagePrefix;
165 /** @var HTMLFormField[] */
166 protected $mFlatFields;
168 protected $mFieldTree;
169 protected $mShowReset = false;
170 protected $mShowSubmit = true;
171 protected $mSubmitFlags = [ 'constructive', 'primary' ];
172 protected $mShowCancel = false;
173 protected $mCancelTarget;
175 protected $mSubmitCallback;
176 protected $mValidationErrorMessage;
178 protected $mPre = '';
179 protected $mHeader = '';
180 protected $mFooter = '';
181 protected $mSectionHeaders = [];
182 protected $mSectionFooters = [];
183 protected $mPost = '';
186 protected $mTableId = '';
188 protected $mSubmitID;
189 protected $mSubmitName;
190 protected $mSubmitText;
191 protected $mSubmitTooltip;
194 protected $mMethod = 'post';
195 protected $mWasSubmitted = false;
198 * Form action URL. false means we will use the URL to set Title
202 protected $mAction = false;
205 * Form attribute autocomplete. false does not set the attribute
209 protected $mAutocomplete = false;
211 protected $mUseMultipart = false;
212 protected $mHiddenFields = [];
213 protected $mButtons = [];
215 protected $mWrapperLegend = false;
218 * Salt for the edit token.
221 protected $mTokenSalt = '';
224 * If true, sections that contain both fields and subsections will
225 * render their subsections before their fields.
227 * Subclasses may set this to false to render subsections after fields
230 protected $mSubSectionBeforeFields = true;
233 * Format in which to display form. For viable options,
234 * @see $availableDisplayFormats
237 protected $displayFormat = 'table';
240 * Available formats in which to display the form
243 protected $availableDisplayFormats = [
251 * Available formats in which to display the form
254 protected $availableSubclassDisplayFormats = [
260 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
262 * @param string $displayFormat
263 * @param mixed $arguments... Additional arguments to pass to the constructor.
266 public static function factory( $displayFormat/*, $arguments...*/ ) {
267 $arguments = func_get_args();
268 array_shift( $arguments );
270 switch ( $displayFormat ) {
272 $reflector = new ReflectionClass( 'VFormHTMLForm' );
273 return $reflector->newInstanceArgs( $arguments );
275 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
276 return $reflector->newInstanceArgs( $arguments );
278 $reflector = new ReflectionClass( 'HTMLForm' );
279 $form = $reflector->newInstanceArgs( $arguments );
280 $form->setDisplayFormat( $displayFormat );
286 * Build a new HTMLForm from an array of field attributes
288 * @param array $descriptor Array of Field constructs, as described above
289 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
290 * Obviates the need to call $form->setTitle()
291 * @param string $messagePrefix A prefix to go in front of default messages
293 public function __construct( $descriptor, /*IContextSource*/ $context = null,
296 if ( $context instanceof IContextSource
) {
297 $this->setContext( $context );
298 $this->mTitle
= false; // We don't need them to set a title
299 $this->mMessagePrefix
= $messagePrefix;
300 } elseif ( $context === null && $messagePrefix !== '' ) {
301 $this->mMessagePrefix
= $messagePrefix;
302 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
304 // it's actually $messagePrefix
305 $this->mMessagePrefix
= $context;
308 // Evil hack for mobile :(
310 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
311 && $this->displayFormat
=== 'table'
313 $this->displayFormat
= 'div';
316 // Expand out into a tree.
317 $loadedDescriptor = [];
318 $this->mFlatFields
= [];
320 foreach ( $descriptor as $fieldname => $info ) {
321 $section = isset( $info['section'] )
325 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
326 $this->mUseMultipart
= true;
329 $field = static::loadInputFromParameters( $fieldname, $info, $this );
331 $setSection =& $loadedDescriptor;
333 $sectionParts = explode( '/', $section );
335 while ( count( $sectionParts ) ) {
336 $newName = array_shift( $sectionParts );
338 if ( !isset( $setSection[$newName] ) ) {
339 $setSection[$newName] = [];
342 $setSection =& $setSection[$newName];
346 $setSection[$fieldname] = $field;
347 $this->mFlatFields
[$fieldname] = $field;
350 $this->mFieldTree
= $loadedDescriptor;
354 * Set format in which to display the form
356 * @param string $format The name of the format to use, must be one of
357 * $this->availableDisplayFormats
359 * @throws MWException
361 * @return HTMLForm $this for chaining calls (since 1.20)
363 public function setDisplayFormat( $format ) {
365 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
366 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
368 throw new MWException( 'Cannot change display format after creation, ' .
369 'use HTMLForm::factory() instead' );
372 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
373 throw new MWException( 'Display format must be one of ' .
374 print_r( $this->availableDisplayFormats
, true ) );
377 // Evil hack for mobile :(
378 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
382 $this->displayFormat
= $format;
388 * Getter for displayFormat
392 public function getDisplayFormat() {
393 return $this->displayFormat
;
397 * Test if displayFormat is 'vform'
399 * @deprecated since 1.25
402 public function isVForm() {
403 wfDeprecated( __METHOD__
, '1.25' );
408 * Get the HTMLFormField subclass for this descriptor.
410 * The descriptor can be passed either 'class' which is the name of
411 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
412 * This makes sure the 'class' is always set, and also is returned by
413 * this function for ease.
417 * @param string $fieldname Name of the field
418 * @param array $descriptor Input Descriptor, as described above
420 * @throws MWException
421 * @return string Name of a HTMLFormField subclass
423 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
424 if ( isset( $descriptor['class'] ) ) {
425 $class = $descriptor['class'];
426 } elseif ( isset( $descriptor['type'] ) ) {
427 $class = static::$typeMappings[$descriptor['type']];
428 $descriptor['class'] = $class;
434 throw new MWException( "Descriptor with no class for $fieldname: "
435 . print_r( $descriptor, true ) );
442 * Initialise a new Object for the field
444 * @param string $fieldname Name of the field
445 * @param array $descriptor Input Descriptor, as described above
446 * @param HTMLForm|null $parent Parent instance of HTMLForm
448 * @throws MWException
449 * @return HTMLFormField Instance of a subclass of HTMLFormField
451 public static function loadInputFromParameters( $fieldname, $descriptor,
452 HTMLForm
$parent = null
454 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
456 $descriptor['fieldname'] = $fieldname;
458 $descriptor['parent'] = $parent;
461 # @todo This will throw a fatal error whenever someone try to use
462 # 'class' to feed a CSS class instead of 'cssclass'. Would be
463 # great to avoid the fatal error and show a nice error.
464 return new $class( $descriptor );
468 * Prepare form for submission.
470 * @attention When doing method chaining, that should be the very last
471 * method call before displayForm().
473 * @throws MWException
474 * @return HTMLForm $this for chaining calls (since 1.20)
476 public function prepareForm() {
477 # Check if we have the info we need
478 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
479 throw new MWException( 'You must call setTitle() on an HTMLForm' );
482 # Load data from the request.
489 * Try submitting, with edit token check first
490 * @return Status|bool
492 public function tryAuthorizedSubmit() {
496 if ( $this->getMethod() !== 'post' ) {
497 $submit = true; // no session check needed
498 } elseif ( $this->getRequest()->wasPosted() ) {
499 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
500 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
501 // Session tokens for logged-out users have no security value.
502 // However, if the user gave one, check it in order to give a nice
503 // "session expired" error instead of "permission denied" or such.
504 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
511 $this->mWasSubmitted
= true;
512 $result = $this->trySubmit();
519 * The here's-one-I-made-earlier option: do the submission if
520 * posted, or display the form with or without funky validation
522 * @return bool|Status Whether submission was successful.
524 public function show() {
525 $this->prepareForm();
527 $result = $this->tryAuthorizedSubmit();
528 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
532 $this->displayForm( $result );
538 * Same as self::show with the difference, that the form will be
539 * added to the output, no matter, if the validation was good or not.
540 * @return bool|Status Whether submission was successful.
542 public function showAlways() {
543 $this->prepareForm();
545 $result = $this->tryAuthorizedSubmit();
547 $this->displayForm( $result );
553 * Validate all the fields, and call the submission callback
554 * function if everything is kosher.
555 * @throws MWException
556 * @return bool|string|array|Status
557 * - Bool true or a good Status object indicates success,
558 * - Bool false indicates no submission was attempted,
559 * - Anything else indicates failure. The value may be a fatal Status
560 * object, an HTML string, or an array of arrays (message keys and
561 * params) or strings (message keys)
563 public function trySubmit() {
566 $hoistedErrors[] = isset( $this->mValidationErrorMessage
)
567 ?
$this->mValidationErrorMessage
568 : [ 'htmlform-invalid-input' ];
570 $this->mWasSubmitted
= true;
572 # Check for cancelled submission
573 foreach ( $this->mFlatFields
as $fieldname => $field ) {
574 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
577 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
578 $this->mWasSubmitted
= false;
583 # Check for validation
584 foreach ( $this->mFlatFields
as $fieldname => $field ) {
585 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
588 if ( $field->isHidden( $this->mFieldData
) ) {
591 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
592 if ( $res !== true ) {
594 if ( $res !== false && !$field->canDisplayErrors() ) {
595 $hoistedErrors[] = [ 'rawmessage', $res ];
601 if ( count( $hoistedErrors ) === 1 ) {
602 $hoistedErrors = $hoistedErrors[0];
604 return $hoistedErrors;
607 $callback = $this->mSubmitCallback
;
608 if ( !is_callable( $callback ) ) {
609 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
610 'setSubmitCallback() to set one.' );
613 $data = $this->filterDataForSubmit( $this->mFieldData
);
615 $res = call_user_func( $callback, $data, $this );
616 if ( $res === false ) {
617 $this->mWasSubmitted
= false;
624 * Test whether the form was considered to have been submitted or not, i.e.
625 * whether the last call to tryAuthorizedSubmit or trySubmit returned
628 * This will return false until HTMLForm::tryAuthorizedSubmit or
629 * HTMLForm::trySubmit is called.
634 public function wasSubmitted() {
635 return $this->mWasSubmitted
;
639 * Set a callback to a function to do something with the form
640 * once it's been successfully validated.
642 * @param callable $cb The function will be passed the output from
643 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
644 * return as documented for HTMLForm::trySubmit
646 * @return HTMLForm $this for chaining calls (since 1.20)
648 public function setSubmitCallback( $cb ) {
649 $this->mSubmitCallback
= $cb;
655 * Set a message to display on a validation error.
657 * @param string|array $msg String or Array of valid inputs to wfMessage()
658 * (so each entry can be either a String or Array)
660 * @return HTMLForm $this for chaining calls (since 1.20)
662 public function setValidationErrorMessage( $msg ) {
663 $this->mValidationErrorMessage
= $msg;
669 * Set the introductory message, overwriting any existing message.
671 * @param string $msg Complete text of message to display
673 * @return HTMLForm $this for chaining calls (since 1.20)
675 public function setIntro( $msg ) {
676 $this->setPreText( $msg );
682 * Set the introductory message HTML, overwriting any existing message.
685 * @param string $msg Complete HTML of message to display
687 * @return HTMLForm $this for chaining calls (since 1.20)
689 public function setPreText( $msg ) {
696 * Add HTML to introductory message.
698 * @param string $msg Complete HTML of message to display
700 * @return HTMLForm $this for chaining calls (since 1.20)
702 public function addPreText( $msg ) {
709 * Add HTML to the header, inside the form.
711 * @param string $msg Additional HTML to display in header
712 * @param string|null $section The section to add the header to
714 * @return HTMLForm $this for chaining calls (since 1.20)
716 public function addHeaderText( $msg, $section = null ) {
717 if ( $section === null ) {
718 $this->mHeader
.= $msg;
720 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
721 $this->mSectionHeaders
[$section] = '';
723 $this->mSectionHeaders
[$section] .= $msg;
730 * Set header text, inside the form.
733 * @param string $msg Complete HTML of header to display
734 * @param string|null $section The section to add the header to
736 * @return HTMLForm $this for chaining calls (since 1.20)
738 public function setHeaderText( $msg, $section = null ) {
739 if ( $section === null ) {
740 $this->mHeader
= $msg;
742 $this->mSectionHeaders
[$section] = $msg;
751 * @param string|null $section The section to get the header text for
753 * @return string HTML
755 public function getHeaderText( $section = null ) {
756 if ( $section === null ) {
757 return $this->mHeader
;
759 return isset( $this->mSectionHeaders
[$section] ) ?
$this->mSectionHeaders
[$section] : '';
764 * Add footer text, inside the form.
766 * @param string $msg Complete text of message to display
767 * @param string|null $section The section to add the footer text to
769 * @return HTMLForm $this for chaining calls (since 1.20)
771 public function addFooterText( $msg, $section = null ) {
772 if ( $section === null ) {
773 $this->mFooter
.= $msg;
775 if ( !isset( $this->mSectionFooters
[$section] ) ) {
776 $this->mSectionFooters
[$section] = '';
778 $this->mSectionFooters
[$section] .= $msg;
785 * Set footer text, inside the form.
788 * @param string $msg Complete text of message to display
789 * @param string|null $section The section to add the footer text to
791 * @return HTMLForm $this for chaining calls (since 1.20)
793 public function setFooterText( $msg, $section = null ) {
794 if ( $section === null ) {
795 $this->mFooter
= $msg;
797 $this->mSectionFooters
[$section] = $msg;
806 * @param string|null $section The section to get the footer text for
810 public function getFooterText( $section = null ) {
811 if ( $section === null ) {
812 return $this->mFooter
;
814 return isset( $this->mSectionFooters
[$section] ) ?
$this->mSectionFooters
[$section] : '';
819 * Add text to the end of the display.
821 * @param string $msg Complete text of message to display
823 * @return HTMLForm $this for chaining calls (since 1.20)
825 public function addPostText( $msg ) {
826 $this->mPost
.= $msg;
832 * Set text at the end of the display.
834 * @param string $msg Complete text of message to display
836 * @return HTMLForm $this for chaining calls (since 1.20)
838 public function setPostText( $msg ) {
845 * Add a hidden field to the output
847 * @param string $name Field name. This will be used exactly as entered
848 * @param string $value Field value
849 * @param array $attribs
851 * @return HTMLForm $this for chaining calls (since 1.20)
853 public function addHiddenField( $name, $value, array $attribs = [] ) {
854 $attribs +
= [ 'name' => $name ];
855 $this->mHiddenFields
[] = [ $value, $attribs ];
861 * Add an array of hidden fields to the output
865 * @param array $fields Associative array of fields to add;
866 * mapping names to their values
868 * @return HTMLForm $this for chaining calls
870 public function addHiddenFields( array $fields ) {
871 foreach ( $fields as $name => $value ) {
872 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
879 * Add a button to the form
881 * @since 1.27 takes an array as shown. Earlier versions accepted
882 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
884 * @note Custom labels ('label', 'label-message', 'label-raw') are not
885 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
886 * they will be served buttons using 'value' as the button label.
887 * @param array $data Data to define the button:
888 * - name: (string) Button name.
889 * - value: (string) Button value.
890 * - label-message: (string, optional) Button label message key to use
891 * instead of 'value'. Overrides 'label' and 'label-raw'.
892 * - label: (string, optional) Button label text to use instead of
893 * 'value'. Overrides 'label-raw'.
894 * - label-raw: (string, optional) Button label HTML to use instead of
896 * - id: (string, optional) DOM id for the button.
897 * - attribs: (array, optional) Additional HTML attributes.
898 * - flags: (string|string[], optional) OOUI flags.
899 * - framed: (boolean=true, optional) OOUI framed attribute.
900 * @return HTMLForm $this for chaining calls (since 1.20)
902 public function addButton( $data ) {
903 if ( !is_array( $data ) ) {
904 $args = func_get_args();
905 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
906 throw new InvalidArgumentException(
907 'Incorrect number of arguments for deprecated calling style'
913 'id' => isset( $args[2] ) ?
$args[2] : null,
914 'attribs' => isset( $args[3] ) ?
$args[3] : null,
917 if ( !isset( $data['name'] ) ) {
918 throw new InvalidArgumentException( 'A name is required' );
920 if ( !isset( $data['value'] ) ) {
921 throw new InvalidArgumentException( 'A value is required' );
924 $this->mButtons
[] = $data +
[
935 * Set the salt for the edit token.
937 * Only useful when the method is "post".
940 * @param string|array $salt Salt to use
941 * @return HTMLForm $this For chaining calls
943 public function setTokenSalt( $salt ) {
944 $this->mTokenSalt
= $salt;
950 * Display the form (sending to the context's OutputPage object), with an
951 * appropriate error message or stack of messages, and any validation errors, etc.
953 * @attention You should call prepareForm() before calling this function.
954 * Moreover, when doing method chaining this should be the very last method
955 * call just after prepareForm().
957 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
959 * @return void Nothing, should be last call
961 public function displayForm( $submitResult ) {
962 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
966 * Returns the raw HTML generated by the form
968 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
970 * @return string HTML
972 public function getHTML( $submitResult ) {
973 # For good measure (it is the default)
974 $this->getOutput()->preventClickjacking();
975 $this->getOutput()->addModules( 'mediawiki.htmlform' );
976 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
979 . $this->getErrors( $submitResult )
980 . $this->getHeaderText()
982 . $this->getHiddenFields()
983 . $this->getButtons()
984 . $this->getFooterText();
986 $html = $this->wrapForm( $html );
988 return '' . $this->mPre
. $html . $this->mPost
;
992 * Get HTML attributes for the `<form>` tag.
995 protected function getFormAttributes() {
996 # Use multipart/form-data
997 $encType = $this->mUseMultipart
998 ?
'multipart/form-data'
999 : 'application/x-www-form-urlencoded';
1002 'action' => $this->getAction(),
1003 'method' => $this->getMethod(),
1004 'enctype' => $encType,
1007 $attribs['id'] = $this->mId
;
1009 if ( $this->mAutocomplete
) {
1010 $attribs['autocomplete'] = $this->mAutocomplete
;
1012 if ( $this->mName
) {
1013 $attribs['name'] = $this->mName
;
1019 * Wrap the form innards in an actual "<form>" element
1021 * @param string $html HTML contents to wrap.
1023 * @return string Wrapped HTML.
1025 public function wrapForm( $html ) {
1026 # Include a <fieldset> wrapper for style, if requested.
1027 if ( $this->mWrapperLegend
!== false ) {
1028 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1029 $html = Xml
::fieldset( $legend, $html );
1032 return Html
::rawElement(
1034 $this->getFormAttributes() +
[ 'class' => 'visualClear' ],
1040 * Get the hidden fields that should go inside the form.
1041 * @return string HTML.
1043 public function getHiddenFields() {
1045 if ( $this->getMethod() === 'post' ) {
1046 $html .= Html
::hidden(
1048 $this->getUser()->getEditToken( $this->mTokenSalt
),
1049 [ 'id' => 'wpEditToken' ]
1051 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1054 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1055 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1056 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1059 foreach ( $this->mHiddenFields
as $data ) {
1060 list( $value, $attribs ) = $data;
1061 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1068 * Get the submit and (potentially) reset buttons.
1069 * @return string HTML.
1071 public function getButtons() {
1073 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1075 if ( $this->mShowSubmit
) {
1078 if ( isset( $this->mSubmitID
) ) {
1079 $attribs['id'] = $this->mSubmitID
;
1082 if ( isset( $this->mSubmitName
) ) {
1083 $attribs['name'] = $this->mSubmitName
;
1086 if ( isset( $this->mSubmitTooltip
) ) {
1087 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1090 $attribs['class'] = [ 'mw-htmlform-submit' ];
1092 if ( $useMediaWikiUIEverywhere ) {
1093 foreach ( $this->mSubmitFlags
as $flag ) {
1094 $attribs['class'][] = 'mw-ui-' . $flag;
1096 $attribs['class'][] = 'mw-ui-button';
1099 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1102 if ( $this->mShowReset
) {
1103 $buttons .= Html
::element(
1107 'value' => $this->msg( 'htmlform-reset' )->text(),
1108 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1113 if ( $this->mShowCancel
) {
1114 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1115 if ( $target instanceof Title
) {
1116 $target = $target->getLocalURL();
1118 $buttons .= Html
::element(
1121 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1124 $this->msg( 'cancel' )->text()
1128 // IE<8 has bugs with <button>, so we'll need to avoid them.
1129 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1131 foreach ( $this->mButtons
as $button ) {
1134 'name' => $button['name'],
1135 'value' => $button['value']
1138 if ( isset( $button['label-message'] ) ) {
1139 $label = $this->getMessage( $button['label-message'] )->parse();
1140 } elseif ( isset( $button['label'] ) ) {
1141 $label = htmlspecialchars( $button['label'] );
1142 } elseif ( isset( $button['label-raw'] ) ) {
1143 $label = $button['label-raw'];
1145 $label = htmlspecialchars( $button['value'] );
1148 if ( $button['attribs'] ) {
1149 $attrs +
= $button['attribs'];
1152 if ( isset( $button['id'] ) ) {
1153 $attrs['id'] = $button['id'];
1156 if ( $useMediaWikiUIEverywhere ) {
1157 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1158 $attrs['class'][] = 'mw-ui-button';
1162 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1164 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1172 return Html
::rawElement( 'span',
1173 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1177 * Get the whole body of the form.
1180 public function getBody() {
1181 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1185 * Format and display an error message stack.
1187 * @param string|array|Status $errors
1191 public function getErrors( $errors ) {
1192 if ( $errors instanceof Status
) {
1193 if ( $errors->isOK() ) {
1196 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1198 } elseif ( is_array( $errors ) ) {
1199 $errorstr = $this->formatErrors( $errors );
1201 $errorstr = $errors;
1205 ? Html
::rawElement( 'div', [ 'class' => 'error' ], $errorstr )
1210 * Format a stack of error messages into a single HTML string
1212 * @param array $errors Array of message keys/values
1214 * @return string HTML, a "<ul>" list of errors
1216 public function formatErrors( $errors ) {
1219 foreach ( $errors as $error ) {
1220 $errorstr .= Html
::rawElement(
1223 $this->getMessage( $error )->parse()
1227 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1233 * Set the text for the submit button
1235 * @param string $t Plaintext
1237 * @return HTMLForm $this for chaining calls (since 1.20)
1239 public function setSubmitText( $t ) {
1240 $this->mSubmitText
= $t;
1246 * Identify that the submit button in the form has a destructive action
1249 * @return HTMLForm $this for chaining calls (since 1.28)
1251 public function setSubmitDestructive() {
1252 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1258 * Identify that the submit button in the form has a progressive action
1261 * @return HTMLForm $this for chaining calls (since 1.28)
1263 public function setSubmitProgressive() {
1264 $this->mSubmitFlags
= [ 'progressive', 'primary' ];
1270 * Set the text for the submit button to a message
1273 * @param string|Message $msg Message key or Message object
1275 * @return HTMLForm $this for chaining calls (since 1.20)
1277 public function setSubmitTextMsg( $msg ) {
1278 if ( !$msg instanceof Message
) {
1279 $msg = $this->msg( $msg );
1281 $this->setSubmitText( $msg->text() );
1287 * Get the text for the submit button, either customised or a default.
1290 public function getSubmitText() {
1291 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1295 * @param string $name Submit button name
1297 * @return HTMLForm $this for chaining calls (since 1.20)
1299 public function setSubmitName( $name ) {
1300 $this->mSubmitName
= $name;
1306 * @param string $name Tooltip for the submit button
1308 * @return HTMLForm $this for chaining calls (since 1.20)
1310 public function setSubmitTooltip( $name ) {
1311 $this->mSubmitTooltip
= $name;
1317 * Set the id for the submit button.
1321 * @todo FIXME: Integrity of $t is *not* validated
1322 * @return HTMLForm $this for chaining calls (since 1.20)
1324 public function setSubmitID( $t ) {
1325 $this->mSubmitID
= $t;
1331 * Stop a default submit button being shown for this form. This implies that an
1332 * alternate submit method must be provided manually.
1336 * @param bool $suppressSubmit Set to false to re-enable the button again
1338 * @return HTMLForm $this for chaining calls
1340 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1341 $this->mShowSubmit
= !$suppressSubmit;
1347 * Show a cancel button (or prevent it). The button is not shown by default.
1349 * @return HTMLForm $this for chaining calls
1352 public function showCancel( $show = true ) {
1353 $this->mShowCancel
= $show;
1358 * Sets the target where the user is redirected to after clicking cancel.
1359 * @param Title|string $target Target as a Title object or an URL
1360 * @return HTMLForm $this for chaining calls
1363 public function setCancelTarget( $target ) {
1364 $this->mCancelTarget
= $target;
1369 * Set the id of the \<table\> or outermost \<div\> element.
1373 * @param string $id New value of the id attribute, or "" to remove
1375 * @return HTMLForm $this for chaining calls
1377 public function setTableId( $id ) {
1378 $this->mTableId
= $id;
1384 * @param string $id DOM id for the form
1386 * @return HTMLForm $this for chaining calls (since 1.20)
1388 public function setId( $id ) {
1395 * @param string $name 'name' attribute for the form
1396 * @return HTMLForm $this for chaining calls
1398 public function setName( $name ) {
1399 $this->mName
= $name;
1405 * Prompt the whole form to be wrapped in a "<fieldset>", with
1406 * this text as its "<legend>" element.
1408 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1409 * If true, a wrapper will be displayed, but no legend.
1410 * If a string, a wrapper will be displayed with that string as a legend.
1411 * The string will be escaped before being output (this doesn't support HTML).
1413 * @return HTMLForm $this for chaining calls (since 1.20)
1415 public function setWrapperLegend( $legend ) {
1416 $this->mWrapperLegend
= $legend;
1422 * Prompt the whole form to be wrapped in a "<fieldset>", with
1423 * this message as its "<legend>" element.
1426 * @param string|Message $msg Message key or Message object
1428 * @return HTMLForm $this for chaining calls (since 1.20)
1430 public function setWrapperLegendMsg( $msg ) {
1431 if ( !$msg instanceof Message
) {
1432 $msg = $this->msg( $msg );
1434 $this->setWrapperLegend( $msg->text() );
1440 * Set the prefix for various default messages
1441 * @todo Currently only used for the "<fieldset>" legend on forms
1442 * with multiple sections; should be used elsewhere?
1446 * @return HTMLForm $this for chaining calls (since 1.20)
1448 public function setMessagePrefix( $p ) {
1449 $this->mMessagePrefix
= $p;
1455 * Set the title for form submission
1457 * @param Title $t Title of page the form is on/should be posted to
1459 * @return HTMLForm $this for chaining calls (since 1.20)
1461 public function setTitle( $t ) {
1471 public function getTitle() {
1472 return $this->mTitle
=== false
1473 ?
$this->getContext()->getTitle()
1478 * Set the method used to submit the form
1480 * @param string $method
1482 * @return HTMLForm $this for chaining calls (since 1.20)
1484 public function setMethod( $method = 'post' ) {
1485 $this->mMethod
= strtolower( $method );
1491 * @return string Always lowercase
1493 public function getMethod() {
1494 return $this->mMethod
;
1498 * Wraps the given $section into an user-visible fieldset.
1500 * @param string $legend Legend text for the fieldset
1501 * @param string $section The section content in plain Html
1502 * @param array $attributes Additional attributes for the fieldset
1503 * @return string The fieldset's Html
1505 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1506 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1512 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1514 * @param string $sectionName ID attribute of the "<table>" tag for this
1515 * section, ignored if empty.
1516 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1517 * each subsection, ignored if empty.
1518 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1519 * @throws LogicException When called on uninitialized field data, e.g. When
1520 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1525 public function displaySection( $fields,
1527 $fieldsetIDPrefix = '',
1528 &$hasUserVisibleFields = false
1530 if ( $this->mFieldData
=== null ) {
1531 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1532 . 'You probably called displayForm() without calling prepareForm() first.' );
1535 $displayFormat = $this->getDisplayFormat();
1538 $subsectionHtml = '';
1541 // Conveniently, PHP method names are case-insensitive.
1542 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1543 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1545 foreach ( $fields as $key => $value ) {
1546 if ( $value instanceof HTMLFormField
) {
1547 $v = array_key_exists( $key, $this->mFieldData
)
1548 ?
$this->mFieldData
[$key]
1549 : $value->getDefault();
1551 $retval = $value->$getFieldHtmlMethod( $v );
1553 // check, if the form field should be added to
1555 if ( $value->hasVisibleOutput() ) {
1558 $labelValue = trim( $value->getLabel() );
1559 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1563 $hasUserVisibleFields = true;
1565 } elseif ( is_array( $value ) ) {
1566 $subsectionHasVisibleFields = false;
1568 $this->displaySection( $value,
1570 "$fieldsetIDPrefix$key-",
1571 $subsectionHasVisibleFields );
1574 if ( $subsectionHasVisibleFields === true ) {
1575 // Display the section with various niceties.
1576 $hasUserVisibleFields = true;
1578 $legend = $this->getLegend( $key );
1580 $section = $this->getHeaderText( $key ) .
1582 $this->getFooterText( $key );
1585 if ( $fieldsetIDPrefix ) {
1586 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1588 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1590 // Just return the inputs, nothing fancy.
1591 $subsectionHtml .= $section;
1596 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1598 if ( $subsectionHtml ) {
1599 if ( $this->mSubSectionBeforeFields
) {
1600 return $subsectionHtml . "\n" . $html;
1602 return $html . "\n" . $subsectionHtml;
1610 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1611 * @param array $fieldsHtml
1612 * @param string $sectionName
1613 * @param bool $anyFieldHasLabel
1614 * @return string HTML
1616 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1617 $displayFormat = $this->getDisplayFormat();
1618 $html = implode( '', $fieldsHtml );
1620 if ( $displayFormat === 'raw' ) {
1626 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1627 $classes[] = 'mw-htmlform-nolabel';
1631 'class' => implode( ' ', $classes ),
1634 if ( $sectionName ) {
1635 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1638 if ( $displayFormat === 'table' ) {
1639 return Html
::rawElement( 'table',
1641 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1642 } elseif ( $displayFormat === 'inline' ) {
1643 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1645 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1650 * Construct the form fields from the Descriptor array
1652 public function loadData() {
1655 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1656 $request = $this->getRequest();
1657 if ( $field->skipLoadData( $request ) ) {
1659 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1660 $fieldData[$fieldname] = $field->getDefault();
1662 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1667 foreach ( $fieldData as $name => &$value ) {
1668 $field = $this->mFlatFields
[$name];
1669 $value = $field->filter( $value, $this->mFlatFields
);
1672 $this->mFieldData
= $fieldData;
1676 * Stop a reset button being shown for this form
1678 * @param bool $suppressReset Set to false to re-enable the button again
1680 * @return HTMLForm $this for chaining calls (since 1.20)
1682 public function suppressReset( $suppressReset = true ) {
1683 $this->mShowReset
= !$suppressReset;
1689 * Overload this if you want to apply special filtration routines
1690 * to the form as a whole, after it's submitted but before it's
1693 * @param array $data
1697 public function filterDataForSubmit( $data ) {
1702 * Get a string to go in the "<legend>" of a section fieldset.
1703 * Override this if you want something more complicated.
1705 * @param string $key
1709 public function getLegend( $key ) {
1710 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1714 * Set the value for the action attribute of the form.
1715 * When set to false (which is the default state), the set title is used.
1719 * @param string|bool $action
1721 * @return HTMLForm $this for chaining calls (since 1.20)
1723 public function setAction( $action ) {
1724 $this->mAction
= $action;
1730 * Get the value for the action attribute of the form.
1736 public function getAction() {
1737 // If an action is alredy provided, return it
1738 if ( $this->mAction
!== false ) {
1739 return $this->mAction
;
1742 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1743 // Check whether we are in GET mode and the ArticlePath contains a "?"
1744 // meaning that getLocalURL() would return something like "index.php?title=...".
1745 // As browser remove the query string before submitting GET forms,
1746 // it means that the title would be lost. In such case use wfScript() instead
1747 // and put title in an hidden field (see getHiddenFields()).
1748 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1752 return $this->getTitle()->getLocalURL();
1756 * Set the value for the autocomplete attribute of the form.
1757 * When set to false (which is the default state), the attribute get not set.
1761 * @param string|bool $autocomplete
1763 * @return HTMLForm $this for chaining calls
1765 public function setAutocomplete( $autocomplete ) {
1766 $this->mAutocomplete
= $autocomplete;
1772 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1773 * name + parameters array) into a Message.
1774 * @param mixed $value
1777 protected function getMessage( $value ) {
1778 return Message
::newFromSpecifier( $value )->setContext( $this );