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, overwriting any existing message.
677 * @param string $msg Complete text of message to display
679 * @return HTMLForm $this for chaining calls (since 1.20)
681 function setPreText( $msg ) {
688 * Add introductory text.
690 * @param string $msg Complete text of message to display
692 * @return HTMLForm $this for chaining calls (since 1.20)
694 function addPreText( $msg ) {
701 * Add header text, inside the form.
703 * @param string $msg Complete text of message to display
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 text of message 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
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 * @param string $name Field name.
874 * @param string $value Field value
875 * @param string $id DOM id for the button (default: null)
876 * @param array $attribs
878 * @return HTMLForm $this for chaining calls (since 1.20)
880 public function addButton( $name, $value, $id = null, $attribs = null ) {
881 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
887 * Set the salt for the edit token.
889 * Only useful when the method is "post".
892 * @param string|array $salt Salt to use
893 * @return HTMLForm $this For chaining calls
895 public function setTokenSalt( $salt ) {
896 $this->mTokenSalt
= $salt;
902 * Display the form (sending to the context's OutputPage object), with an
903 * appropriate error message or stack of messages, and any validation errors, etc.
905 * @attention You should call prepareForm() before calling this function.
906 * Moreover, when doing method chaining this should be the very last method
907 * call just after prepareForm().
909 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
911 * @return void Nothing, should be last call
913 function displayForm( $submitResult ) {
914 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
918 * Returns the raw HTML generated by the form
920 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
924 function getHTML( $submitResult ) {
925 # For good measure (it is the default)
926 $this->getOutput()->preventClickjacking();
927 $this->getOutput()->addModules( 'mediawiki.htmlform' );
928 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
931 . $this->getErrors( $submitResult )
932 . $this->getHeaderText()
934 . $this->getHiddenFields()
935 . $this->getButtons()
936 . $this->getFooterText();
938 $html = $this->wrapForm( $html );
940 return '' . $this->mPre
. $html . $this->mPost
;
944 * Get HTML attributes for the `<form>` tag.
947 protected function getFormAttributes() {
948 # Use multipart/form-data
949 $encType = $this->mUseMultipart
950 ?
'multipart/form-data'
951 : 'application/x-www-form-urlencoded';
954 'action' => $this->getAction(),
955 'method' => $this->getMethod(),
956 'enctype' => $encType,
958 if ( !empty( $this->mId
) ) {
959 $attribs['id'] = $this->mId
;
965 * Wrap the form innards in an actual "<form>" element
967 * @param string $html HTML contents to wrap.
969 * @return string Wrapped HTML.
971 function wrapForm( $html ) {
972 # Include a <fieldset> wrapper for style, if requested.
973 if ( $this->mWrapperLegend
!== false ) {
974 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
975 $html = Xml
::fieldset( $legend, $html );
978 return Html
::rawElement(
980 $this->getFormAttributes() +
array( 'class' => 'visualClear' ),
986 * Get the hidden fields that should go inside the form.
987 * @return string HTML.
989 function getHiddenFields() {
991 if ( $this->getMethod() == 'post' ) {
992 $html .= Html
::hidden(
994 $this->getUser()->getEditToken( $this->mTokenSalt
),
995 array( 'id' => 'wpEditToken' )
997 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1000 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1001 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
1002 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1005 foreach ( $this->mHiddenFields
as $data ) {
1006 list( $value, $attribs ) = $data;
1007 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1014 * Get the submit and (potentially) reset buttons.
1015 * @return string HTML.
1017 function getButtons() {
1019 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1021 if ( $this->mShowSubmit
) {
1024 if ( isset( $this->mSubmitID
) ) {
1025 $attribs['id'] = $this->mSubmitID
;
1028 if ( isset( $this->mSubmitName
) ) {
1029 $attribs['name'] = $this->mSubmitName
;
1032 if ( isset( $this->mSubmitTooltip
) ) {
1033 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1036 $attribs['class'] = array( 'mw-htmlform-submit' );
1038 if ( $useMediaWikiUIEverywhere ) {
1039 foreach ( $this->mSubmitFlags
as $flag ) {
1040 array_push( $attribs['class'], 'mw-ui-' . $flag );
1042 array_push( $attribs['class'], 'mw-ui-button' );
1045 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1048 if ( $this->mShowReset
) {
1049 $buttons .= Html
::element(
1053 'value' => $this->msg( 'htmlform-reset' )->text(),
1054 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
1059 foreach ( $this->mButtons
as $button ) {
1062 'name' => $button['name'],
1063 'value' => $button['value']
1066 if ( $button['attribs'] ) {
1067 $attrs +
= $button['attribs'];
1070 if ( isset( $button['id'] ) ) {
1071 $attrs['id'] = $button['id'];
1074 if ( $useMediaWikiUIEverywhere ) {
1075 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1076 $attrs['class'][] = 'mw-ui-button';
1079 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1082 $html = Html
::rawElement( 'span',
1083 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1089 * Get the whole body of the form.
1092 function getBody() {
1093 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1097 * Format and display an error message stack.
1099 * @param string|array|Status $errors
1103 function getErrors( $errors ) {
1104 if ( $errors instanceof Status
) {
1105 if ( $errors->isOK() ) {
1108 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1110 } elseif ( is_array( $errors ) ) {
1111 $errorstr = $this->formatErrors( $errors );
1113 $errorstr = $errors;
1117 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1122 * Format a stack of error messages into a single HTML string
1124 * @param array $errors Array of message keys/values
1126 * @return string HTML, a "<ul>" list of errors
1128 public function formatErrors( $errors ) {
1131 foreach ( $errors as $error ) {
1132 if ( is_array( $error ) ) {
1133 $msg = array_shift( $error );
1139 $errorstr .= Html
::rawElement(
1142 $this->msg( $msg, $error )->parse()
1146 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1152 * Set the text for the submit button
1154 * @param string $t Plaintext
1156 * @return HTMLForm $this for chaining calls (since 1.20)
1158 function setSubmitText( $t ) {
1159 $this->mSubmitText
= $t;
1165 * Identify that the submit button in the form has a destructive action
1168 public function setSubmitDestructive() {
1169 $this->mSubmitFlags
= array( 'destructive', 'primary' );
1175 * Identify that the submit button in the form has a progressive action
1178 public function setSubmitProgressive() {
1179 $this->mSubmitFlags
= array( 'progressive', 'primary' );
1185 * Set the text for the submit button to a message
1188 * @param string|Message $msg Message key or Message object
1190 * @return HTMLForm $this for chaining calls (since 1.20)
1192 public function setSubmitTextMsg( $msg ) {
1193 if ( !$msg instanceof Message
) {
1194 $msg = $this->msg( $msg );
1196 $this->setSubmitText( $msg->text() );
1202 * Get the text for the submit button, either customised or a default.
1205 function getSubmitText() {
1206 return $this->mSubmitText
1207 ?
$this->mSubmitText
1208 : $this->msg( 'htmlform-submit' )->text();
1212 * @param string $name Submit button name
1214 * @return HTMLForm $this for chaining calls (since 1.20)
1216 public function setSubmitName( $name ) {
1217 $this->mSubmitName
= $name;
1223 * @param string $name Tooltip for the submit button
1225 * @return HTMLForm $this for chaining calls (since 1.20)
1227 public function setSubmitTooltip( $name ) {
1228 $this->mSubmitTooltip
= $name;
1234 * Set the id for the submit button.
1238 * @todo FIXME: Integrity of $t is *not* validated
1239 * @return HTMLForm $this for chaining calls (since 1.20)
1241 function setSubmitID( $t ) {
1242 $this->mSubmitID
= $t;
1248 * Stop a default submit button being shown for this form. This implies that an
1249 * alternate submit method must be provided manually.
1253 * @param bool $suppressSubmit Set to false to re-enable the button again
1255 * @return HTMLForm $this for chaining calls
1257 function suppressDefaultSubmit( $suppressSubmit = true ) {
1258 $this->mShowSubmit
= !$suppressSubmit;
1264 * Set the id of the \<table\> or outermost \<div\> element.
1268 * @param string $id New value of the id attribute, or "" to remove
1270 * @return HTMLForm $this for chaining calls
1272 public function setTableId( $id ) {
1273 $this->mTableId
= $id;
1279 * @param string $id DOM id for the form
1281 * @return HTMLForm $this for chaining calls (since 1.20)
1283 public function setId( $id ) {
1290 * Prompt the whole form to be wrapped in a "<fieldset>", with
1291 * this text as its "<legend>" element.
1293 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1294 * If true, a wrapper will be displayed, but no legend.
1295 * If a string, a wrapper will be displayed with that string as a legend.
1296 * The string will be escaped before being output (this doesn't support HTML).
1298 * @return HTMLForm $this for chaining calls (since 1.20)
1300 public function setWrapperLegend( $legend ) {
1301 $this->mWrapperLegend
= $legend;
1307 * Prompt the whole form to be wrapped in a "<fieldset>", with
1308 * this message as its "<legend>" element.
1311 * @param string|Message $msg Message key or Message object
1313 * @return HTMLForm $this for chaining calls (since 1.20)
1315 public function setWrapperLegendMsg( $msg ) {
1316 if ( !$msg instanceof Message
) {
1317 $msg = $this->msg( $msg );
1319 $this->setWrapperLegend( $msg->text() );
1325 * Set the prefix for various default messages
1326 * @todo Currently only used for the "<fieldset>" legend on forms
1327 * with multiple sections; should be used elsewhere?
1331 * @return HTMLForm $this for chaining calls (since 1.20)
1333 function setMessagePrefix( $p ) {
1334 $this->mMessagePrefix
= $p;
1340 * Set the title for form submission
1342 * @param Title $t Title of page the form is on/should be posted to
1344 * @return HTMLForm $this for chaining calls (since 1.20)
1346 function setTitle( $t ) {
1356 function getTitle() {
1357 return $this->mTitle
=== false
1358 ?
$this->getContext()->getTitle()
1363 * Set the method used to submit the form
1365 * @param string $method
1367 * @return HTMLForm $this for chaining calls (since 1.20)
1369 public function setMethod( $method = 'post' ) {
1370 $this->mMethod
= strtolower( $method );
1376 * @return string Always lowercase
1378 public function getMethod() {
1379 return $this->mMethod
;
1383 * Wraps the given $section into an user-visible fieldset.
1385 * @param string $legend Legend text for the fieldset
1386 * @param string $section The section content in plain Html
1387 * @param array $attributes Additional attributes for the fieldset
1388 * @return string The fieldset's Html
1390 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1391 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1397 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1399 * @param string $sectionName ID attribute of the "<table>" tag for this
1400 * section, ignored if empty.
1401 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1402 * each subsection, ignored if empty.
1403 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1407 public function displaySection( $fields,
1409 $fieldsetIDPrefix = '',
1410 &$hasUserVisibleFields = false ) {
1411 $displayFormat = $this->getDisplayFormat();
1414 $subsectionHtml = '';
1417 // Conveniently, PHP method names are case-insensitive.
1418 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1419 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1421 foreach ( $fields as $key => $value ) {
1422 if ( $value instanceof HTMLFormField
) {
1423 $v = empty( $value->mParams
['nodata'] )
1424 ?
$this->mFieldData
[$key]
1425 : $value->getDefault();
1427 $retval = $value->$getFieldHtmlMethod( $v );
1429 // check, if the form field should be added to
1431 if ( $value->hasVisibleOutput() ) {
1434 $labelValue = trim( $value->getLabel() );
1435 if ( $labelValue != ' ' && $labelValue !== '' ) {
1439 $hasUserVisibleFields = true;
1441 } elseif ( is_array( $value ) ) {
1442 $subsectionHasVisibleFields = false;
1444 $this->displaySection( $value,
1446 "$fieldsetIDPrefix$key-",
1447 $subsectionHasVisibleFields );
1450 if ( $subsectionHasVisibleFields === true ) {
1451 // Display the section with various niceties.
1452 $hasUserVisibleFields = true;
1454 $legend = $this->getLegend( $key );
1456 $section = $this->getHeaderText( $key ) .
1458 $this->getFooterText( $key );
1460 $attributes = array();
1461 if ( $fieldsetIDPrefix ) {
1462 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1464 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1466 // Just return the inputs, nothing fancy.
1467 $subsectionHtml .= $section;
1472 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1474 if ( $subsectionHtml ) {
1475 if ( $this->mSubSectionBeforeFields
) {
1476 return $subsectionHtml . "\n" . $html;
1478 return $html . "\n" . $subsectionHtml;
1486 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1487 * @param array $fieldsHtml
1488 * @param string $sectionName
1489 * @param bool $anyFieldHasLabel
1490 * @return string HTML
1492 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1493 $displayFormat = $this->getDisplayFormat();
1494 $html = implode( '', $fieldsHtml );
1496 if ( $displayFormat === 'raw' ) {
1502 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1503 $classes[] = 'mw-htmlform-nolabel';
1507 'class' => implode( ' ', $classes ),
1510 if ( $sectionName ) {
1511 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1514 if ( $displayFormat === 'table' ) {
1515 return Html
::rawElement( 'table',
1517 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1518 } elseif ( $displayFormat === 'inline' ) {
1519 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1521 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1526 * Construct the form fields from the Descriptor array
1528 function loadData() {
1529 $fieldData = array();
1531 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1532 if ( !empty( $field->mParams
['nodata'] ) ) {
1534 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1535 $fieldData[$fieldname] = $field->getDefault();
1537 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1542 foreach ( $fieldData as $name => &$value ) {
1543 $field = $this->mFlatFields
[$name];
1544 $value = $field->filter( $value, $this->mFlatFields
);
1547 $this->mFieldData
= $fieldData;
1551 * Stop a reset button being shown for this form
1553 * @param bool $suppressReset Set to false to re-enable the button again
1555 * @return HTMLForm $this for chaining calls (since 1.20)
1557 function suppressReset( $suppressReset = true ) {
1558 $this->mShowReset
= !$suppressReset;
1564 * Overload this if you want to apply special filtration routines
1565 * to the form as a whole, after it's submitted but before it's
1568 * @param array $data
1572 function filterDataForSubmit( $data ) {
1577 * Get a string to go in the "<legend>" of a section fieldset.
1578 * Override this if you want something more complicated.
1580 * @param string $key
1584 public function getLegend( $key ) {
1585 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1589 * Set the value for the action attribute of the form.
1590 * When set to false (which is the default state), the set title is used.
1594 * @param string|bool $action
1596 * @return HTMLForm $this for chaining calls (since 1.20)
1598 public function setAction( $action ) {
1599 $this->mAction
= $action;
1605 * Get the value for the action attribute of the form.
1611 public function getAction() {
1612 // If an action is alredy provided, return it
1613 if ( $this->mAction
!== false ) {
1614 return $this->mAction
;
1617 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1618 // Check whether we are in GET mode and the ArticlePath contains a "?"
1619 // meaning that getLocalURL() would return something like "index.php?title=...".
1620 // As browser remove the query string before submitting GET forms,
1621 // it means that the title would be lost. In such case use wfScript() instead
1622 // and put title in an hidden field (see getHiddenFields()).
1623 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1627 return $this->getTitle()->getLocalURL();