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 to be parsed to extract the list of
60 * options (like 'ipbreason-dropdown').
61 * 'label-message' -- message key 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 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 key. 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 = array(
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 = array( 'constructive', 'primary' );
173 protected $mSubmitCallback;
174 protected $mValidationErrorMessage;
176 protected $mPre = '';
177 protected $mHeader = '';
178 protected $mFooter = '';
179 protected $mSectionHeaders = array();
180 protected $mSectionFooters = array();
181 protected $mPost = '';
183 protected $mTableId = '';
185 protected $mSubmitID;
186 protected $mSubmitName;
187 protected $mSubmitText;
188 protected $mSubmitTooltip;
191 protected $mMethod = 'post';
192 protected $mWasSubmitted = false;
195 * Form action URL. false means we will use the URL to set Title
199 protected $mAction = false;
201 protected $mUseMultipart = false;
202 protected $mHiddenFields = array();
203 protected $mButtons = array();
205 protected $mWrapperLegend = false;
208 * Salt for the edit token.
211 protected $mTokenSalt = '';
214 * If true, sections that contain both fields and subsections will
215 * render their subsections before their fields.
217 * Subclasses may set this to false to render subsections after fields
220 protected $mSubSectionBeforeFields = true;
223 * Format in which to display form. For viable options,
224 * @see $availableDisplayFormats
227 protected $displayFormat = 'table';
230 * Available formats in which to display the form
233 protected $availableDisplayFormats = array(
241 * Available formats in which to display the form
244 protected $availableSubclassDisplayFormats = array(
250 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
252 * @param string $displayFormat
253 * @param mixed $arguments... Additional arguments to pass to the constructor.
256 public static function factory( $displayFormat/*, $arguments...*/ ) {
257 $arguments = func_get_args();
258 array_shift( $arguments );
260 switch ( $displayFormat ) {
262 $reflector = new ReflectionClass( 'VFormHTMLForm' );
263 return $reflector->newInstanceArgs( $arguments );
265 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
266 return $reflector->newInstanceArgs( $arguments );
268 $reflector = new ReflectionClass( 'HTMLForm' );
269 $form = $reflector->newInstanceArgs( $arguments );
270 $form->setDisplayFormat( $displayFormat );
276 * Build a new HTMLForm from an array of field attributes
278 * @param array $descriptor Array of Field constructs, as described above
279 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
280 * Obviates the need to call $form->setTitle()
281 * @param string $messagePrefix A prefix to go in front of default messages
283 public function __construct( $descriptor, /*IContextSource*/ $context = null,
286 if ( $context instanceof IContextSource
) {
287 $this->setContext( $context );
288 $this->mTitle
= false; // We don't need them to set a title
289 $this->mMessagePrefix
= $messagePrefix;
290 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
291 $this->mMessagePrefix
= $messagePrefix;
292 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
294 // it's actually $messagePrefix
295 $this->mMessagePrefix
= $context;
298 // Evil hack for mobile :(
300 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
301 && $this->displayFormat
=== 'table'
303 $this->displayFormat
= 'div';
306 // Expand out into a tree.
307 $loadedDescriptor = array();
308 $this->mFlatFields
= array();
310 foreach ( $descriptor as $fieldname => $info ) {
311 $section = isset( $info['section'] )
315 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
316 $this->mUseMultipart
= true;
319 $field = static::loadInputFromParameters( $fieldname, $info, $this );
321 $setSection =& $loadedDescriptor;
323 $sectionParts = explode( '/', $section );
325 while ( count( $sectionParts ) ) {
326 $newName = array_shift( $sectionParts );
328 if ( !isset( $setSection[$newName] ) ) {
329 $setSection[$newName] = array();
332 $setSection =& $setSection[$newName];
336 $setSection[$fieldname] = $field;
337 $this->mFlatFields
[$fieldname] = $field;
340 $this->mFieldTree
= $loadedDescriptor;
344 * Set format in which to display the form
346 * @param string $format The name of the format to use, must be one of
347 * $this->availableDisplayFormats
349 * @throws MWException
351 * @return HTMLForm $this for chaining calls (since 1.20)
353 public function setDisplayFormat( $format ) {
355 in_array( $format, $this->availableSubclassDisplayFormats
) ||
356 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
358 throw new MWException( 'Cannot change display format after creation, ' .
359 'use HTMLForm::factory() instead' );
362 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
363 throw new MWException( 'Display format must be one of ' .
364 print_r( $this->availableDisplayFormats
, true ) );
367 // Evil hack for mobile :(
368 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
372 $this->displayFormat
= $format;
378 * Getter for displayFormat
382 public function getDisplayFormat() {
383 return $this->displayFormat
;
387 * Test if displayFormat is 'vform'
389 * @deprecated since 1.25
392 public function isVForm() {
393 wfDeprecated( __METHOD__
, '1.25' );
398 * Get the HTMLFormField subclass for this descriptor.
400 * The descriptor can be passed either 'class' which is the name of
401 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
402 * This makes sure the 'class' is always set, and also is returned by
403 * this function for ease.
407 * @param string $fieldname Name of the field
408 * @param array $descriptor Input Descriptor, as described above
410 * @throws MWException
411 * @return string Name of a HTMLFormField subclass
413 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
414 if ( isset( $descriptor['class'] ) ) {
415 $class = $descriptor['class'];
416 } elseif ( isset( $descriptor['type'] ) ) {
417 $class = static::$typeMappings[$descriptor['type']];
418 $descriptor['class'] = $class;
424 throw new MWException( "Descriptor with no class for $fieldname: "
425 . print_r( $descriptor, true ) );
432 * Initialise a new Object for the field
434 * @param string $fieldname Name of the field
435 * @param array $descriptor Input Descriptor, as described above
436 * @param HTMLForm|null $parent Parent instance of HTMLForm
438 * @throws MWException
439 * @return HTMLFormField Instance of a subclass of HTMLFormField
441 public static function loadInputFromParameters( $fieldname, $descriptor,
442 HTMLForm
$parent = null
444 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
446 $descriptor['fieldname'] = $fieldname;
448 $descriptor['parent'] = $parent;
451 # @todo This will throw a fatal error whenever someone try to use
452 # 'class' to feed a CSS class instead of 'cssclass'. Would be
453 # great to avoid the fatal error and show a nice error.
454 $obj = new $class( $descriptor );
460 * Prepare form for submission.
462 * @attention When doing method chaining, that should be the very last
463 * method call before displayForm().
465 * @throws MWException
466 * @return HTMLForm $this for chaining calls (since 1.20)
468 function prepareForm() {
469 # Check if we have the info we need
470 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
471 throw new MWException( "You must call setTitle() on an HTMLForm" );
474 # Load data from the request.
481 * Try submitting, with edit token check first
482 * @return Status|bool
484 function tryAuthorizedSubmit() {
488 if ( $this->getMethod() != 'post' ) {
489 $submit = true; // no session check needed
490 } elseif ( $this->getRequest()->wasPosted() ) {
491 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
492 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
493 // Session tokens for logged-out users have no security value.
494 // However, if the user gave one, check it in order to give a nice
495 // "session expired" error instead of "permission denied" or such.
496 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
503 $this->mWasSubmitted
= true;
504 $result = $this->trySubmit();
511 * The here's-one-I-made-earlier option: do the submission if
512 * posted, or display the form with or without funky validation
514 * @return bool|Status Whether submission was successful.
517 $this->prepareForm();
519 $result = $this->tryAuthorizedSubmit();
520 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
524 $this->displayForm( $result );
530 * Same as self::show with the difference, that the form will be
531 * added to the output, no matter, if the validation was good or not.
532 * @return bool|Status Whether submission was successful.
534 function showAlways() {
535 $this->prepareForm();
537 $result = $this->tryAuthorizedSubmit();
539 $this->displayForm( $result );
545 * Validate all the fields, and call the submission callback
546 * function if everything is kosher.
547 * @throws MWException
548 * @return bool|string|array|Status
549 * - Bool true or a good Status object indicates success,
550 * - Bool false indicates no submission was attempted,
551 * - Anything else indicates failure. The value may be a fatal Status
552 * object, an HTML string, or an array of arrays (message keys and
553 * params) or strings (message keys)
555 function trySubmit() {
557 $hoistedErrors = array();
558 $hoistedErrors[] = isset( $this->mValidationErrorMessage
)
559 ?
$this->mValidationErrorMessage
560 : array( 'htmlform-invalid-input' );
562 $this->mWasSubmitted
= true;
564 # Check for cancelled submission
565 foreach ( $this->mFlatFields
as $fieldname => $field ) {
566 if ( !empty( $field->mParams
['nodata'] ) ) {
569 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
570 $this->mWasSubmitted
= false;
575 # Check for validation
576 foreach ( $this->mFlatFields
as $fieldname => $field ) {
577 if ( !empty( $field->mParams
['nodata'] ) ) {
580 if ( $field->isHidden( $this->mFieldData
) ) {
583 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
584 if ( $res !== true ) {
586 if ( $res !== false && !$field->canDisplayErrors() ) {
587 $hoistedErrors[] = array( 'rawmessage', $res );
593 if ( count( $hoistedErrors ) === 1 ) {
594 $hoistedErrors = $hoistedErrors[0];
596 return $hoistedErrors;
599 $callback = $this->mSubmitCallback
;
600 if ( !is_callable( $callback ) ) {
601 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
602 'setSubmitCallback() to set one.' );
605 $data = $this->filterDataForSubmit( $this->mFieldData
);
607 $res = call_user_func( $callback, $data, $this );
608 if ( $res === false ) {
609 $this->mWasSubmitted
= false;
616 * Test whether the form was considered to have been submitted or not, i.e.
617 * whether the last call to tryAuthorizedSubmit or trySubmit returned
620 * This will return false until HTMLForm::tryAuthorizedSubmit or
621 * HTMLForm::trySubmit is called.
626 function wasSubmitted() {
627 return $this->mWasSubmitted
;
631 * Set a callback to a function to do something with the form
632 * once it's been successfully validated.
634 * @param callable $cb The function will be passed the output from
635 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
636 * return as documented for HTMLForm::trySubmit
638 * @return HTMLForm $this for chaining calls (since 1.20)
640 function setSubmitCallback( $cb ) {
641 $this->mSubmitCallback
= $cb;
647 * Set a message to display on a validation error.
649 * @param string|array $msg String or Array of valid inputs to wfMessage()
650 * (so each entry can be either a String or Array)
652 * @return HTMLForm $this for chaining calls (since 1.20)
654 function setValidationErrorMessage( $msg ) {
655 $this->mValidationErrorMessage
= $msg;
661 * Set the introductory message, overwriting any existing message.
663 * @param string $msg Complete text of message to display
665 * @return HTMLForm $this for chaining calls (since 1.20)
667 function setIntro( $msg ) {
668 $this->setPreText( $msg );
674 * Set the introductory message HTML, overwriting any existing message.
677 * @param string $msg Complete HTML of message to display
679 * @return HTMLForm $this for chaining calls (since 1.20)
681 function setPreText( $msg ) {
688 * Add HTML to introductory message.
690 * @param string $msg Complete HTML of message to display
692 * @return HTMLForm $this for chaining calls (since 1.20)
694 function addPreText( $msg ) {
701 * Add HTML to the header, inside the form.
703 * @param string $msg Additional HTML to display in header
704 * @param string|null $section The section to add the header to
706 * @return HTMLForm $this for chaining calls (since 1.20)
708 function addHeaderText( $msg, $section = null ) {
709 if ( is_null( $section ) ) {
710 $this->mHeader
.= $msg;
712 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
713 $this->mSectionHeaders
[$section] = '';
715 $this->mSectionHeaders
[$section] .= $msg;
722 * Set header text, inside the form.
725 * @param string $msg Complete HTML of header to display
726 * @param string|null $section The section to add the header to
728 * @return HTMLForm $this for chaining calls (since 1.20)
730 function setHeaderText( $msg, $section = null ) {
731 if ( is_null( $section ) ) {
732 $this->mHeader
= $msg;
734 $this->mSectionHeaders
[$section] = $msg;
743 * @param string|null $section The section to get the header text for
745 * @return string HTML
747 function getHeaderText( $section = null ) {
748 if ( is_null( $section ) ) {
749 return $this->mHeader
;
751 return isset( $this->mSectionHeaders
[$section] ) ?
$this->mSectionHeaders
[$section] : '';
756 * Add footer text, inside the form.
758 * @param string $msg Complete text of message to display
759 * @param string|null $section The section to add the footer text to
761 * @return HTMLForm $this for chaining calls (since 1.20)
763 function addFooterText( $msg, $section = null ) {
764 if ( is_null( $section ) ) {
765 $this->mFooter
.= $msg;
767 if ( !isset( $this->mSectionFooters
[$section] ) ) {
768 $this->mSectionFooters
[$section] = '';
770 $this->mSectionFooters
[$section] .= $msg;
777 * Set footer text, inside the form.
780 * @param string $msg Complete text of message to display
781 * @param string|null $section The section to add the footer text to
783 * @return HTMLForm $this for chaining calls (since 1.20)
785 function setFooterText( $msg, $section = null ) {
786 if ( is_null( $section ) ) {
787 $this->mFooter
= $msg;
789 $this->mSectionFooters
[$section] = $msg;
798 * @param string|null $section The section to get the footer text for
802 function getFooterText( $section = null ) {
803 if ( is_null( $section ) ) {
804 return $this->mFooter
;
806 return isset( $this->mSectionFooters
[$section] ) ?
$this->mSectionFooters
[$section] : '';
811 * Add text to the end of the display.
813 * @param string $msg Complete text of message to display
815 * @return HTMLForm $this for chaining calls (since 1.20)
817 function addPostText( $msg ) {
818 $this->mPost
.= $msg;
824 * Set text at the end of the display.
826 * @param string $msg Complete text of message to display
828 * @return HTMLForm $this for chaining calls (since 1.20)
830 function setPostText( $msg ) {
837 * Add a hidden field to the output
839 * @param string $name Field name. This will be used exactly as entered
840 * @param string $value Field value
841 * @param array $attribs
843 * @return HTMLForm $this for chaining calls (since 1.20)
845 public function addHiddenField( $name, $value, $attribs = array() ) {
846 $attribs +
= array( 'name' => $name );
847 $this->mHiddenFields
[] = array( $value, $attribs );
853 * Add an array of hidden fields to the output
857 * @param array $fields Associative array of fields to add;
858 * mapping names to their values
860 * @return HTMLForm $this for chaining calls
862 public function addHiddenFields( array $fields ) {
863 foreach ( $fields as $name => $value ) {
864 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
871 * Add a button to the form
873 * @since 1.27 takes an array as shown. Earlier versions accepted
874 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
876 * @note Custom labels ('label', 'label-message', 'label-raw') are not
877 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
878 * they will be served buttons using 'value' as the button label.
879 * @param array $data Data to define the button:
880 * - name: (string) Button name.
881 * - value: (string) Button value.
882 * - label-message: (string, optional) Button label message key to use
883 * instead of 'value'. Overrides 'label' and 'label-raw'.
884 * - label: (string, optional) Button label text to use instead of
885 * 'value'. Overrides 'label-raw'.
886 * - label-raw: (string, optional) Button label HTML to use instead of
888 * - id: (string, optional) DOM id for the button.
889 * - attribs: (array, optional) Additional HTML attributes.
890 * - flags: (string|string[], optional) OOUI flags.
891 * @return HTMLForm $this for chaining calls (since 1.20)
893 public function addButton( $data ) {
894 if ( !is_array( $data ) ) {
895 $args = func_get_args();
896 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
897 throw new InvalidArgumentException(
898 'Incorrect number of arguments for deprecated calling style'
904 'id' => isset( $args[2] ) ?
$args[2] : null,
905 'attribs' => isset( $args[3] ) ?
$args[3] : null,
908 if ( !isset( $data['name'] ) ) {
909 throw new InvalidArgumentException( 'A name is required' );
911 if ( !isset( $data['value'] ) ) {
912 throw new InvalidArgumentException( 'A value is required' );
915 $this->mButtons
[] = $data +
array(
925 * Set the salt for the edit token.
927 * Only useful when the method is "post".
930 * @param string|array $salt Salt to use
931 * @return HTMLForm $this For chaining calls
933 public function setTokenSalt( $salt ) {
934 $this->mTokenSalt
= $salt;
940 * Display the form (sending to the context's OutputPage object), with an
941 * appropriate error message or stack of messages, and any validation errors, etc.
943 * @attention You should call prepareForm() before calling this function.
944 * Moreover, when doing method chaining this should be the very last method
945 * call just after prepareForm().
947 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
949 * @return void Nothing, should be last call
951 function displayForm( $submitResult ) {
952 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
956 * Returns the raw HTML generated by the form
958 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
960 * @return string HTML
962 function getHTML( $submitResult ) {
963 # For good measure (it is the default)
964 $this->getOutput()->preventClickjacking();
965 $this->getOutput()->addModules( 'mediawiki.htmlform' );
966 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
969 . $this->getErrors( $submitResult )
970 . $this->getHeaderText()
972 . $this->getHiddenFields()
973 . $this->getButtons()
974 . $this->getFooterText();
976 $html = $this->wrapForm( $html );
978 return '' . $this->mPre
. $html . $this->mPost
;
982 * Get HTML attributes for the `<form>` tag.
985 protected function getFormAttributes() {
986 # Use multipart/form-data
987 $encType = $this->mUseMultipart
988 ?
'multipart/form-data'
989 : 'application/x-www-form-urlencoded';
992 'action' => $this->getAction(),
993 'method' => $this->getMethod(),
994 'enctype' => $encType,
996 if ( !empty( $this->mId
) ) {
997 $attribs['id'] = $this->mId
;
1003 * Wrap the form innards in an actual "<form>" element
1005 * @param string $html HTML contents to wrap.
1007 * @return string Wrapped HTML.
1009 function wrapForm( $html ) {
1010 # Include a <fieldset> wrapper for style, if requested.
1011 if ( $this->mWrapperLegend
!== false ) {
1012 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1013 $html = Xml
::fieldset( $legend, $html );
1016 return Html
::rawElement(
1018 $this->getFormAttributes() +
array( 'class' => 'visualClear' ),
1024 * Get the hidden fields that should go inside the form.
1025 * @return string HTML.
1027 function getHiddenFields() {
1029 if ( $this->getMethod() == 'post' ) {
1030 $html .= Html
::hidden(
1032 $this->getUser()->getEditToken( $this->mTokenSalt
),
1033 array( 'id' => 'wpEditToken' )
1035 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1038 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1039 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
1040 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1043 foreach ( $this->mHiddenFields
as $data ) {
1044 list( $value, $attribs ) = $data;
1045 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1052 * Get the submit and (potentially) reset buttons.
1053 * @return string HTML.
1055 function getButtons() {
1057 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1059 if ( $this->mShowSubmit
) {
1062 if ( isset( $this->mSubmitID
) ) {
1063 $attribs['id'] = $this->mSubmitID
;
1066 if ( isset( $this->mSubmitName
) ) {
1067 $attribs['name'] = $this->mSubmitName
;
1070 if ( isset( $this->mSubmitTooltip
) ) {
1071 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1074 $attribs['class'] = array( 'mw-htmlform-submit' );
1076 if ( $useMediaWikiUIEverywhere ) {
1077 foreach ( $this->mSubmitFlags
as $flag ) {
1078 array_push( $attribs['class'], 'mw-ui-' . $flag );
1080 array_push( $attribs['class'], 'mw-ui-button' );
1083 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1086 if ( $this->mShowReset
) {
1087 $buttons .= Html
::element(
1091 'value' => $this->msg( 'htmlform-reset' )->text(),
1092 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
1097 // IE<8 has bugs with <button>, so we'll need to avoid them.
1098 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1100 foreach ( $this->mButtons
as $button ) {
1103 'name' => $button['name'],
1104 'value' => $button['value']
1107 if ( isset( $button['label-message'] ) ) {
1108 $label = $this->msg( $button['label-message'] )->parse();
1109 } elseif ( isset( $button['label'] ) ) {
1110 $label = htmlspecialchars( $button['label'] );
1111 } elseif ( isset( $button['label-raw'] ) ) {
1112 $label = $button['label-raw'];
1114 $label = htmlspecialchars( $button['value'] );
1117 if ( $button['attribs'] ) {
1118 $attrs +
= $button['attribs'];
1121 if ( isset( $button['id'] ) ) {
1122 $attrs['id'] = $button['id'];
1125 if ( $useMediaWikiUIEverywhere ) {
1126 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1127 $attrs['class'][] = 'mw-ui-button';
1131 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1133 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1137 $html = Html
::rawElement( 'span',
1138 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1144 * Get the whole body of the form.
1147 function getBody() {
1148 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1152 * Format and display an error message stack.
1154 * @param string|array|Status $errors
1158 function getErrors( $errors ) {
1159 if ( $errors instanceof Status
) {
1160 if ( $errors->isOK() ) {
1163 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1165 } elseif ( is_array( $errors ) ) {
1166 $errorstr = $this->formatErrors( $errors );
1168 $errorstr = $errors;
1172 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1177 * Format a stack of error messages into a single HTML string
1179 * @param array $errors Array of message keys/values
1181 * @return string HTML, a "<ul>" list of errors
1183 public function formatErrors( $errors ) {
1186 foreach ( $errors as $error ) {
1187 if ( is_array( $error ) ) {
1188 $msg = array_shift( $error );
1194 $errorstr .= Html
::rawElement(
1197 $this->msg( $msg, $error )->parse()
1201 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1207 * Set the text for the submit button
1209 * @param string $t Plaintext
1211 * @return HTMLForm $this for chaining calls (since 1.20)
1213 function setSubmitText( $t ) {
1214 $this->mSubmitText
= $t;
1220 * Identify that the submit button in the form has a destructive action
1223 public function setSubmitDestructive() {
1224 $this->mSubmitFlags
= array( 'destructive', 'primary' );
1228 * Identify that the submit button in the form has a progressive action
1231 public function setSubmitProgressive() {
1232 $this->mSubmitFlags
= array( 'progressive', 'primary' );
1236 * Set the text for the submit button to a message
1239 * @param string|Message $msg Message key or Message object
1241 * @return HTMLForm $this for chaining calls (since 1.20)
1243 public function setSubmitTextMsg( $msg ) {
1244 if ( !$msg instanceof Message
) {
1245 $msg = $this->msg( $msg );
1247 $this->setSubmitText( $msg->text() );
1253 * Get the text for the submit button, either customised or a default.
1256 function getSubmitText() {
1257 return $this->mSubmitText
1258 ?
$this->mSubmitText
1259 : $this->msg( 'htmlform-submit' )->text();
1263 * @param string $name Submit button name
1265 * @return HTMLForm $this for chaining calls (since 1.20)
1267 public function setSubmitName( $name ) {
1268 $this->mSubmitName
= $name;
1274 * @param string $name Tooltip for the submit button
1276 * @return HTMLForm $this for chaining calls (since 1.20)
1278 public function setSubmitTooltip( $name ) {
1279 $this->mSubmitTooltip
= $name;
1285 * Set the id for the submit button.
1289 * @todo FIXME: Integrity of $t is *not* validated
1290 * @return HTMLForm $this for chaining calls (since 1.20)
1292 function setSubmitID( $t ) {
1293 $this->mSubmitID
= $t;
1299 * Stop a default submit button being shown for this form. This implies that an
1300 * alternate submit method must be provided manually.
1304 * @param bool $suppressSubmit Set to false to re-enable the button again
1306 * @return HTMLForm $this for chaining calls
1308 function suppressDefaultSubmit( $suppressSubmit = true ) {
1309 $this->mShowSubmit
= !$suppressSubmit;
1315 * Set the id of the \<table\> or outermost \<div\> element.
1319 * @param string $id New value of the id attribute, or "" to remove
1321 * @return HTMLForm $this for chaining calls
1323 public function setTableId( $id ) {
1324 $this->mTableId
= $id;
1330 * @param string $id DOM id for the form
1332 * @return HTMLForm $this for chaining calls (since 1.20)
1334 public function setId( $id ) {
1341 * Prompt the whole form to be wrapped in a "<fieldset>", with
1342 * this text as its "<legend>" element.
1344 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1345 * If true, a wrapper will be displayed, but no legend.
1346 * If a string, a wrapper will be displayed with that string as a legend.
1347 * The string will be escaped before being output (this doesn't support HTML).
1349 * @return HTMLForm $this for chaining calls (since 1.20)
1351 public function setWrapperLegend( $legend ) {
1352 $this->mWrapperLegend
= $legend;
1358 * Prompt the whole form to be wrapped in a "<fieldset>", with
1359 * this message as its "<legend>" element.
1362 * @param string|Message $msg Message key or Message object
1364 * @return HTMLForm $this for chaining calls (since 1.20)
1366 public function setWrapperLegendMsg( $msg ) {
1367 if ( !$msg instanceof Message
) {
1368 $msg = $this->msg( $msg );
1370 $this->setWrapperLegend( $msg->text() );
1376 * Set the prefix for various default messages
1377 * @todo Currently only used for the "<fieldset>" legend on forms
1378 * with multiple sections; should be used elsewhere?
1382 * @return HTMLForm $this for chaining calls (since 1.20)
1384 function setMessagePrefix( $p ) {
1385 $this->mMessagePrefix
= $p;
1391 * Set the title for form submission
1393 * @param Title $t Title of page the form is on/should be posted to
1395 * @return HTMLForm $this for chaining calls (since 1.20)
1397 function setTitle( $t ) {
1407 function getTitle() {
1408 return $this->mTitle
=== false
1409 ?
$this->getContext()->getTitle()
1414 * Set the method used to submit the form
1416 * @param string $method
1418 * @return HTMLForm $this for chaining calls (since 1.20)
1420 public function setMethod( $method = 'post' ) {
1421 $this->mMethod
= strtolower( $method );
1427 * @return string Always lowercase
1429 public function getMethod() {
1430 return $this->mMethod
;
1434 * Wraps the given $section into an user-visible fieldset.
1436 * @param string $legend Legend text for the fieldset
1437 * @param string $section The section content in plain Html
1438 * @param array $attributes Additional attributes for the fieldset
1439 * @return string The fieldset's Html
1441 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1442 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1448 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1450 * @param string $sectionName ID attribute of the "<table>" tag for this
1451 * section, ignored if empty.
1452 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1453 * each subsection, ignored if empty.
1454 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1458 public function displaySection( $fields,
1460 $fieldsetIDPrefix = '',
1461 &$hasUserVisibleFields = false ) {
1462 $displayFormat = $this->getDisplayFormat();
1465 $subsectionHtml = '';
1468 // Conveniently, PHP method names are case-insensitive.
1469 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1470 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1472 foreach ( $fields as $key => $value ) {
1473 if ( $value instanceof HTMLFormField
) {
1474 $v = empty( $value->mParams
['nodata'] )
1475 ?
$this->mFieldData
[$key]
1476 : $value->getDefault();
1478 $retval = $value->$getFieldHtmlMethod( $v );
1480 // check, if the form field should be added to
1482 if ( $value->hasVisibleOutput() ) {
1485 $labelValue = trim( $value->getLabel() );
1486 if ( $labelValue != ' ' && $labelValue !== '' ) {
1490 $hasUserVisibleFields = true;
1492 } elseif ( is_array( $value ) ) {
1493 $subsectionHasVisibleFields = false;
1495 $this->displaySection( $value,
1497 "$fieldsetIDPrefix$key-",
1498 $subsectionHasVisibleFields );
1501 if ( $subsectionHasVisibleFields === true ) {
1502 // Display the section with various niceties.
1503 $hasUserVisibleFields = true;
1505 $legend = $this->getLegend( $key );
1507 $section = $this->getHeaderText( $key ) .
1509 $this->getFooterText( $key );
1511 $attributes = array();
1512 if ( $fieldsetIDPrefix ) {
1513 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1515 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1517 // Just return the inputs, nothing fancy.
1518 $subsectionHtml .= $section;
1523 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1525 if ( $subsectionHtml ) {
1526 if ( $this->mSubSectionBeforeFields
) {
1527 return $subsectionHtml . "\n" . $html;
1529 return $html . "\n" . $subsectionHtml;
1537 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1538 * @param array $fieldsHtml
1539 * @param string $sectionName
1540 * @param bool $anyFieldHasLabel
1541 * @return string HTML
1543 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1544 $displayFormat = $this->getDisplayFormat();
1545 $html = implode( '', $fieldsHtml );
1547 if ( $displayFormat === 'raw' ) {
1553 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1554 $classes[] = 'mw-htmlform-nolabel';
1558 'class' => implode( ' ', $classes ),
1561 if ( $sectionName ) {
1562 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1565 if ( $displayFormat === 'table' ) {
1566 return Html
::rawElement( 'table',
1568 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1569 } elseif ( $displayFormat === 'inline' ) {
1570 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1572 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1577 * Construct the form fields from the Descriptor array
1579 function loadData() {
1580 $fieldData = array();
1582 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1583 if ( !empty( $field->mParams
['nodata'] ) ) {
1585 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1586 $fieldData[$fieldname] = $field->getDefault();
1588 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1593 foreach ( $fieldData as $name => &$value ) {
1594 $field = $this->mFlatFields
[$name];
1595 $value = $field->filter( $value, $this->mFlatFields
);
1598 $this->mFieldData
= $fieldData;
1602 * Stop a reset button being shown for this form
1604 * @param bool $suppressReset Set to false to re-enable the button again
1606 * @return HTMLForm $this for chaining calls (since 1.20)
1608 function suppressReset( $suppressReset = true ) {
1609 $this->mShowReset
= !$suppressReset;
1615 * Overload this if you want to apply special filtration routines
1616 * to the form as a whole, after it's submitted but before it's
1619 * @param array $data
1623 function filterDataForSubmit( $data ) {
1628 * Get a string to go in the "<legend>" of a section fieldset.
1629 * Override this if you want something more complicated.
1631 * @param string $key
1635 public function getLegend( $key ) {
1636 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1640 * Set the value for the action attribute of the form.
1641 * When set to false (which is the default state), the set title is used.
1645 * @param string|bool $action
1647 * @return HTMLForm $this for chaining calls (since 1.20)
1649 public function setAction( $action ) {
1650 $this->mAction
= $action;
1656 * Get the value for the action attribute of the form.
1662 public function getAction() {
1663 // If an action is alredy provided, return it
1664 if ( $this->mAction
!== false ) {
1665 return $this->mAction
;
1668 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1669 // Check whether we are in GET mode and the ArticlePath contains a "?"
1670 // meaning that getLocalURL() would return something like "index.php?title=...".
1671 // As browser remove the query string before submitting GET forms,
1672 // it means that the title would be lost. In such case use wfScript() instead
1673 // and put title in an hidden field (see getHiddenFields()).
1674 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1678 return $this->getTitle()->getLocalURL();