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 HTMLForm::filter()
80 * 'validation-callback' -- a function name to give you the chance
81 * to impose extra validation on the field input.
82 * @see HTMLForm::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.
88 * Since 1.20, you can chain mutators to ease the form generation:
91 * $form = new HTMLForm( $someFields );
92 * $form->setMethod( 'get' )
93 * ->setWrapperLegendMsg( 'message-key' )
95 * ->displayForm( '' );
97 * Note that you will have prepareForm and displayForm at the end. Other
98 * methods call done after that would simply not be part of the form :(
100 * @todo Document 'section' / 'subsection' stuff
102 class HTMLForm
extends ContextSource
{
103 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
104 public static $typeMappings = array(
105 'api' => 'HTMLApiField',
106 'text' => 'HTMLTextField',
107 'textarea' => 'HTMLTextAreaField',
108 'select' => 'HTMLSelectField',
109 'radio' => 'HTMLRadioField',
110 'multiselect' => 'HTMLMultiSelectField',
111 'limitselect' => 'HTMLSelectLimitField',
112 'check' => 'HTMLCheckField',
113 'toggle' => 'HTMLCheckField',
114 'int' => 'HTMLIntField',
115 'float' => 'HTMLFloatField',
116 'info' => 'HTMLInfoField',
117 'selectorother' => 'HTMLSelectOrOtherField',
118 'selectandother' => 'HTMLSelectAndOtherField',
119 'namespaceselect' => 'HTMLSelectNamespace',
120 'tagfilter' => 'HTMLTagFilter',
121 'submit' => 'HTMLSubmitField',
122 'hidden' => 'HTMLHiddenField',
123 'edittools' => 'HTMLEditTools',
124 'checkmatrix' => 'HTMLCheckMatrix',
125 'cloner' => 'HTMLFormFieldCloner',
126 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
127 // HTMLTextField will output the correct type="" attribute automagically.
128 // There are about four zillion other HTML5 input types, like range, but
129 // we don't use those at the moment, so no point in adding all of them.
130 'email' => 'HTMLTextField',
131 'password' => 'HTMLTextField',
132 'url' => 'HTMLTextField',
137 protected $mMessagePrefix;
139 /** @var HTMLFormField[] */
140 protected $mFlatFields;
142 protected $mFieldTree;
143 protected $mShowReset = false;
144 protected $mShowSubmit = true;
145 protected $mSubmitModifierClass = 'mw-ui-constructive';
147 protected $mSubmitCallback;
148 protected $mValidationErrorMessage;
150 protected $mPre = '';
151 protected $mHeader = '';
152 protected $mFooter = '';
153 protected $mSectionHeaders = array();
154 protected $mSectionFooters = array();
155 protected $mPost = '';
157 protected $mTableId = '';
159 protected $mSubmitID;
160 protected $mSubmitName;
161 protected $mSubmitText;
162 protected $mSubmitTooltip;
165 protected $mMethod = 'post';
166 protected $mWasSubmitted = false;
169 * Form action URL. false means we will use the URL to set Title
173 protected $mAction = false;
175 protected $mUseMultipart = false;
176 protected $mHiddenFields = array();
177 protected $mButtons = array();
179 protected $mWrapperLegend = false;
182 * Salt for the edit token.
185 protected $mTokenSalt = '';
188 * If true, sections that contain both fields and subsections will
189 * render their subsections before their fields.
191 * Subclasses may set this to false to render subsections after fields
194 protected $mSubSectionBeforeFields = true;
197 * Format in which to display form. For viable options,
198 * @see $availableDisplayFormats
201 protected $displayFormat = 'table';
204 * Available formats in which to display the form
207 protected $availableDisplayFormats = array(
215 * Available formats in which to display the form
218 protected $availableSubclassDisplayFormats = array(
223 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
225 * @throws MWException When the display format requested is not known
226 * @param string $displayFormat
227 * @param mixed $arguments... Additional arguments to pass to the constructor.
230 public static function factory( $displayFormat/*, $arguments...*/ ) {
231 $arguments = func_get_args();
232 array_shift( $arguments );
234 switch ( $displayFormat ) {
236 $reflector = new ReflectionClass( 'VFormHTMLForm' );
237 return $reflector->newInstanceArgs( $arguments );
239 $reflector = new ReflectionClass( 'HTMLForm' );
240 $form = $reflector->newInstanceArgs( $arguments );
241 $form->setDisplayFormat( $displayFormat );
247 * Build a new HTMLForm from an array of field attributes
249 * @param array $descriptor Array of Field constructs, as described above
250 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
251 * Obviates the need to call $form->setTitle()
252 * @param string $messagePrefix A prefix to go in front of default messages
254 public function __construct( $descriptor, /*IContextSource*/ $context = null,
257 if ( $context instanceof IContextSource
) {
258 $this->setContext( $context );
259 $this->mTitle
= false; // We don't need them to set a title
260 $this->mMessagePrefix
= $messagePrefix;
261 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
262 $this->mMessagePrefix
= $messagePrefix;
263 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
265 // it's actually $messagePrefix
266 $this->mMessagePrefix
= $context;
269 // Evil hack for mobile :(
270 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat
=== 'table' ) {
271 $this->displayFormat
= 'div';
274 // Expand out into a tree.
275 $loadedDescriptor = array();
276 $this->mFlatFields
= array();
278 foreach ( $descriptor as $fieldname => $info ) {
279 $section = isset( $info['section'] )
283 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
284 $this->mUseMultipart
= true;
287 $field = static::loadInputFromParameters( $fieldname, $info, $this );
289 $setSection =& $loadedDescriptor;
291 $sectionParts = explode( '/', $section );
293 while ( count( $sectionParts ) ) {
294 $newName = array_shift( $sectionParts );
296 if ( !isset( $setSection[$newName] ) ) {
297 $setSection[$newName] = array();
300 $setSection =& $setSection[$newName];
304 $setSection[$fieldname] = $field;
305 $this->mFlatFields
[$fieldname] = $field;
308 $this->mFieldTree
= $loadedDescriptor;
312 * Set format in which to display the form
314 * @param string $format The name of the format to use, must be one of
315 * $this->availableDisplayFormats
317 * @throws MWException
319 * @return HTMLForm $this for chaining calls (since 1.20)
321 public function setDisplayFormat( $format ) {
323 in_array( $format, $this->availableSubclassDisplayFormats
) ||
324 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
326 throw new MWException( 'Cannot change display format after creation, ' .
327 'use HTMLForm::factory() instead' );
330 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
331 throw new MWException( 'Display format must be one of ' .
332 print_r( $this->availableDisplayFormats
, true ) );
335 // Evil hack for mobile :(
336 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
340 $this->displayFormat
= $format;
346 * Getter for displayFormat
350 public function getDisplayFormat() {
351 return $this->displayFormat
;
355 * Test if displayFormat is 'vform'
357 * @deprecated since 1.25
360 public function isVForm() {
361 wfDeprecated( __METHOD__
, '1.25' );
366 * Get the HTMLFormField subclass for this descriptor.
368 * The descriptor can be passed either 'class' which is the name of
369 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
370 * This makes sure the 'class' is always set, and also is returned by
371 * this function for ease.
375 * @param string $fieldname Name of the field
376 * @param array $descriptor Input Descriptor, as described above
378 * @throws MWException
379 * @return string Name of a HTMLFormField subclass
381 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
382 if ( isset( $descriptor['class'] ) ) {
383 $class = $descriptor['class'];
384 } elseif ( isset( $descriptor['type'] ) ) {
385 $class = static::$typeMappings[$descriptor['type']];
386 $descriptor['class'] = $class;
392 throw new MWException( "Descriptor with no class for $fieldname: "
393 . print_r( $descriptor, true ) );
400 * Initialise a new Object for the field
402 * @param string $fieldname Name of the field
403 * @param array $descriptor Input Descriptor, as described above
404 * @param HTMLForm|null $parent Parent instance of HTMLForm
406 * @throws MWException
407 * @return HTMLFormField Instance of a subclass of HTMLFormField
409 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm
$parent = null ) {
410 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
412 $descriptor['fieldname'] = $fieldname;
414 $descriptor['parent'] = $parent;
417 # @todo This will throw a fatal error whenever someone try to use
418 # 'class' to feed a CSS class instead of 'cssclass'. Would be
419 # great to avoid the fatal error and show a nice error.
420 $obj = new $class( $descriptor );
426 * Prepare form for submission.
428 * @attention When doing method chaining, that should be the very last
429 * method call before displayForm().
431 * @throws MWException
432 * @return HTMLForm $this for chaining calls (since 1.20)
434 function prepareForm() {
435 # Check if we have the info we need
436 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
437 throw new MWException( "You must call setTitle() on an HTMLForm" );
440 # Load data from the request.
447 * Try submitting, with edit token check first
448 * @return Status|bool
450 function tryAuthorizedSubmit() {
454 if ( $this->getMethod() != 'post' ) {
455 $submit = true; // no session check needed
456 } elseif ( $this->getRequest()->wasPosted() ) {
457 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
458 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
459 // Session tokens for logged-out users have no security value.
460 // However, if the user gave one, check it in order to give a nice
461 // "session expired" error instead of "permission denied" or such.
462 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
469 $this->mWasSubmitted
= true;
470 $result = $this->trySubmit();
477 * The here's-one-I-made-earlier option: do the submission if
478 * posted, or display the form with or without funky validation
480 * @return bool|Status Whether submission was successful.
483 $this->prepareForm();
485 $result = $this->tryAuthorizedSubmit();
486 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
490 $this->displayForm( $result );
496 * Validate all the fields, and call the submission callback
497 * function if everything is kosher.
498 * @throws MWException
499 * @return bool|string|array|Status
500 * - Bool true or a good Status object indicates success,
501 * - Bool false indicates no submission was attempted,
502 * - Anything else indicates failure. The value may be a fatal Status
503 * object, an HTML string, or an array of arrays (message keys and
504 * params) or strings (message keys)
506 function trySubmit() {
507 $this->mWasSubmitted
= true;
509 # Check for cancelled submission
510 foreach ( $this->mFlatFields
as $fieldname => $field ) {
511 if ( !empty( $field->mParams
['nodata'] ) ) {
514 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
515 $this->mWasSubmitted
= false;
520 # Check for validation
521 foreach ( $this->mFlatFields
as $fieldname => $field ) {
522 if ( !empty( $field->mParams
['nodata'] ) ) {
525 if ( $field->isHidden( $this->mFieldData
) ) {
528 if ( $field->validate(
529 $this->mFieldData
[$fieldname],
533 return isset( $this->mValidationErrorMessage
)
534 ?
$this->mValidationErrorMessage
535 : array( 'htmlform-invalid-input' );
539 $callback = $this->mSubmitCallback
;
540 if ( !is_callable( $callback ) ) {
541 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
542 'setSubmitCallback() to set one.' );
545 $data = $this->filterDataForSubmit( $this->mFieldData
);
547 $res = call_user_func( $callback, $data, $this );
548 if ( $res === false ) {
549 $this->mWasSubmitted
= false;
556 * Test whether the form was considered to have been submitted or not, i.e.
557 * whether the last call to tryAuthorizedSubmit or trySubmit returned
560 * This will return false until HTMLForm::tryAuthorizedSubmit or
561 * HTMLForm::trySubmit is called.
566 function wasSubmitted() {
567 return $this->mWasSubmitted
;
571 * Set a callback to a function to do something with the form
572 * once it's been successfully validated.
574 * @param callable $cb The function will be passed the output from
575 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
576 * return as documented for HTMLForm::trySubmit
578 * @return HTMLForm $this for chaining calls (since 1.20)
580 function setSubmitCallback( $cb ) {
581 $this->mSubmitCallback
= $cb;
587 * Set a message to display on a validation error.
589 * @param string|array $msg String or Array of valid inputs to wfMessage()
590 * (so each entry can be either a String or Array)
592 * @return HTMLForm $this for chaining calls (since 1.20)
594 function setValidationErrorMessage( $msg ) {
595 $this->mValidationErrorMessage
= $msg;
601 * Set the introductory message, overwriting any existing message.
603 * @param string $msg Complete text of message to display
605 * @return HTMLForm $this for chaining calls (since 1.20)
607 function setIntro( $msg ) {
608 $this->setPreText( $msg );
614 * Set the introductory message, overwriting any existing message.
617 * @param string $msg Complete text of message to display
619 * @return HTMLForm $this for chaining calls (since 1.20)
621 function setPreText( $msg ) {
628 * Add introductory text.
630 * @param string $msg Complete text of message to display
632 * @return HTMLForm $this for chaining calls (since 1.20)
634 function addPreText( $msg ) {
641 * Add header text, inside the form.
643 * @param string $msg Complete text of message to display
644 * @param string|null $section The section to add the header to
646 * @return HTMLForm $this for chaining calls (since 1.20)
648 function addHeaderText( $msg, $section = null ) {
649 if ( is_null( $section ) ) {
650 $this->mHeader
.= $msg;
652 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
653 $this->mSectionHeaders
[$section] = '';
655 $this->mSectionHeaders
[$section] .= $msg;
662 * Set header text, inside the form.
665 * @param string $msg Complete text of message to display
666 * @param string|null $section The section to add the header to
668 * @return HTMLForm $this for chaining calls (since 1.20)
670 function setHeaderText( $msg, $section = null ) {
671 if ( is_null( $section ) ) {
672 $this->mHeader
= $msg;
674 $this->mSectionHeaders
[$section] = $msg;
681 * Add footer text, inside the form.
683 * @param string $msg Complete text of message to display
684 * @param string|null $section The section to add the footer text to
686 * @return HTMLForm $this for chaining calls (since 1.20)
688 function addFooterText( $msg, $section = null ) {
689 if ( is_null( $section ) ) {
690 $this->mFooter
.= $msg;
692 if ( !isset( $this->mSectionFooters
[$section] ) ) {
693 $this->mSectionFooters
[$section] = '';
695 $this->mSectionFooters
[$section] .= $msg;
702 * Set footer text, inside the form.
705 * @param string $msg Complete text of message to display
706 * @param string|null $section The section to add the footer text to
708 * @return HTMLForm $this for chaining calls (since 1.20)
710 function setFooterText( $msg, $section = null ) {
711 if ( is_null( $section ) ) {
712 $this->mFooter
= $msg;
714 $this->mSectionFooters
[$section] = $msg;
721 * Add text to the end of the display.
723 * @param string $msg Complete text of message to display
725 * @return HTMLForm $this for chaining calls (since 1.20)
727 function addPostText( $msg ) {
728 $this->mPost
.= $msg;
734 * Set text at the end of the display.
736 * @param string $msg Complete text of message to display
738 * @return HTMLForm $this for chaining calls (since 1.20)
740 function setPostText( $msg ) {
747 * Add a hidden field to the output
749 * @param string $name Field name. This will be used exactly as entered
750 * @param string $value Field value
751 * @param array $attribs
753 * @return HTMLForm $this for chaining calls (since 1.20)
755 public function addHiddenField( $name, $value, $attribs = array() ) {
756 $attribs +
= array( 'name' => $name );
757 $this->mHiddenFields
[] = array( $value, $attribs );
763 * Add an array of hidden fields to the output
767 * @param array $fields Associative array of fields to add;
768 * mapping names to their values
770 * @return HTMLForm $this for chaining calls
772 public function addHiddenFields( array $fields ) {
773 foreach ( $fields as $name => $value ) {
774 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
781 * Add a button to the form
783 * @param string $name Field name.
784 * @param string $value Field value
785 * @param string $id DOM id for the button (default: null)
786 * @param array $attribs
788 * @return HTMLForm $this for chaining calls (since 1.20)
790 public function addButton( $name, $value, $id = null, $attribs = null ) {
791 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
797 * Set the salt for the edit token.
799 * Only useful when the method is "post".
802 * @param string|array $salt Salt to use
803 * @return HTMLForm $this For chaining calls
805 public function setTokenSalt( $salt ) {
806 $this->mTokenSalt
= $salt;
812 * Display the form (sending to the context's OutputPage object), with an
813 * appropriate error message or stack of messages, and any validation errors, etc.
815 * @attention You should call prepareForm() before calling this function.
816 * Moreover, when doing method chaining this should be the very last method
817 * call just after prepareForm().
819 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
821 * @return void Nothing, should be last call
823 function displayForm( $submitResult ) {
824 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
828 * Returns the raw HTML generated by the form
830 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
834 function getHTML( $submitResult ) {
835 # For good measure (it is the default)
836 $this->getOutput()->preventClickjacking();
837 $this->getOutput()->addModules( 'mediawiki.htmlform' );
840 . $this->getErrors( $submitResult )
843 . $this->getHiddenFields()
844 . $this->getButtons()
847 $html = $this->wrapForm( $html );
849 return '' . $this->mPre
. $html . $this->mPost
;
853 * Get HTML attributes for the `<form>` tag.
856 protected function getFormAttributes() {
857 # Use multipart/form-data
858 $encType = $this->mUseMultipart
859 ?
'multipart/form-data'
860 : 'application/x-www-form-urlencoded';
863 'action' => $this->getAction(),
864 'method' => $this->getMethod(),
865 'class' => array( 'visualClear' ),
866 'enctype' => $encType,
868 if ( !empty( $this->mId
) ) {
869 $attribs['id'] = $this->mId
;
875 * Wrap the form innards in an actual "<form>" element
877 * @param string $html HTML contents to wrap.
879 * @return string Wrapped HTML.
881 function wrapForm( $html ) {
882 # Include a <fieldset> wrapper for style, if requested.
883 if ( $this->mWrapperLegend
!== false ) {
884 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
887 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
891 * Get the hidden fields that should go inside the form.
892 * @return string HTML.
894 function getHiddenFields() {
896 if ( $this->getMethod() == 'post' ) {
897 $html .= Html
::hidden(
899 $this->getUser()->getEditToken( $this->mTokenSalt
),
900 array( 'id' => 'wpEditToken' )
902 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
905 $articlePath = $this->getConfig()->get( 'ArticlePath' );
906 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
907 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
910 foreach ( $this->mHiddenFields
as $data ) {
911 list( $value, $attribs ) = $data;
912 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
919 * Get the submit and (potentially) reset buttons.
920 * @return string HTML.
922 function getButtons() {
924 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
926 if ( $this->mShowSubmit
) {
929 if ( isset( $this->mSubmitID
) ) {
930 $attribs['id'] = $this->mSubmitID
;
933 if ( isset( $this->mSubmitName
) ) {
934 $attribs['name'] = $this->mSubmitName
;
937 if ( isset( $this->mSubmitTooltip
) ) {
938 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
941 $attribs['class'] = array( 'mw-htmlform-submit' );
943 if ( $useMediaWikiUIEverywhere ) {
944 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
947 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
950 if ( $this->mShowReset
) {
951 $buttons .= Html
::element(
955 'value' => $this->msg( 'htmlform-reset' )->text(),
956 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
961 foreach ( $this->mButtons
as $button ) {
964 'name' => $button['name'],
965 'value' => $button['value']
968 if ( $button['attribs'] ) {
969 $attrs +
= $button['attribs'];
972 if ( isset( $button['id'] ) ) {
973 $attrs['id'] = $button['id'];
976 if ( $useMediaWikiUIEverywhere ) {
977 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
978 $attrs['class'][] = 'mw-ui-button';
981 $buttons .= Html
::element( 'input', $attrs ) . "\n";
984 $html = Html
::rawElement( 'span',
985 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
991 * Get the whole body of the form.
995 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
999 * Format and display an error message stack.
1001 * @param string|array|Status $errors
1005 function getErrors( $errors ) {
1006 if ( $errors instanceof Status
) {
1007 if ( $errors->isOK() ) {
1010 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1012 } elseif ( is_array( $errors ) ) {
1013 $errorstr = $this->formatErrors( $errors );
1015 $errorstr = $errors;
1019 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1024 * Format a stack of error messages into a single HTML string
1026 * @param array $errors Array of message keys/values
1028 * @return string HTML, a "<ul>" list of errors
1030 public function formatErrors( $errors ) {
1033 foreach ( $errors as $error ) {
1034 if ( is_array( $error ) ) {
1035 $msg = array_shift( $error );
1041 $errorstr .= Html
::rawElement(
1044 $this->msg( $msg, $error )->parse()
1048 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1054 * Set the text for the submit button
1056 * @param string $t Plaintext
1058 * @return HTMLForm $this for chaining calls (since 1.20)
1060 function setSubmitText( $t ) {
1061 $this->mSubmitText
= $t;
1067 * Identify that the submit button in the form has a destructive action
1070 public function setSubmitDestructive() {
1071 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1075 * Identify that the submit button in the form has a progressive action
1078 public function setSubmitProgressive() {
1079 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1083 * Set the text for the submit button to a message
1086 * @param string|Message $msg Message key or Message object
1088 * @return HTMLForm $this for chaining calls (since 1.20)
1090 public function setSubmitTextMsg( $msg ) {
1091 if ( !$msg instanceof Message
) {
1092 $msg = $this->msg( $msg );
1094 $this->setSubmitText( $msg->text() );
1100 * Get the text for the submit button, either customised or a default.
1103 function getSubmitText() {
1104 return $this->mSubmitText
1105 ?
$this->mSubmitText
1106 : $this->msg( 'htmlform-submit' )->text();
1110 * @param string $name Submit button name
1112 * @return HTMLForm $this for chaining calls (since 1.20)
1114 public function setSubmitName( $name ) {
1115 $this->mSubmitName
= $name;
1121 * @param string $name Tooltip for the submit button
1123 * @return HTMLForm $this for chaining calls (since 1.20)
1125 public function setSubmitTooltip( $name ) {
1126 $this->mSubmitTooltip
= $name;
1132 * Set the id for the submit button.
1136 * @todo FIXME: Integrity of $t is *not* validated
1137 * @return HTMLForm $this for chaining calls (since 1.20)
1139 function setSubmitID( $t ) {
1140 $this->mSubmitID
= $t;
1146 * Stop a default submit button being shown for this form. This implies that an
1147 * alternate submit method must be provided manually.
1151 * @param bool $suppressSubmit Set to false to re-enable the button again
1153 * @return HTMLForm $this for chaining calls
1155 function suppressDefaultSubmit( $suppressSubmit = true ) {
1156 $this->mShowSubmit
= !$suppressSubmit;
1162 * Set the id of the \<table\> or outermost \<div\> element.
1166 * @param string $id New value of the id attribute, or "" to remove
1168 * @return HTMLForm $this for chaining calls
1170 public function setTableId( $id ) {
1171 $this->mTableId
= $id;
1177 * @param string $id DOM id for the form
1179 * @return HTMLForm $this for chaining calls (since 1.20)
1181 public function setId( $id ) {
1188 * Prompt the whole form to be wrapped in a "<fieldset>", with
1189 * this text as its "<legend>" element.
1191 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1192 * false for no <legend>
1195 * @return HTMLForm $this for chaining calls (since 1.20)
1197 public function setWrapperLegend( $legend ) {
1198 $this->mWrapperLegend
= $legend;
1204 * Prompt the whole form to be wrapped in a "<fieldset>", with
1205 * this message as its "<legend>" element.
1208 * @param string|Message $msg Message key or Message object
1210 * @return HTMLForm $this for chaining calls (since 1.20)
1212 public function setWrapperLegendMsg( $msg ) {
1213 if ( !$msg instanceof Message
) {
1214 $msg = $this->msg( $msg );
1216 $this->setWrapperLegend( $msg->text() );
1222 * Set the prefix for various default messages
1223 * @todo Currently only used for the "<fieldset>" legend on forms
1224 * with multiple sections; should be used elsewhere?
1228 * @return HTMLForm $this for chaining calls (since 1.20)
1230 function setMessagePrefix( $p ) {
1231 $this->mMessagePrefix
= $p;
1237 * Set the title for form submission
1239 * @param Title $t Title of page the form is on/should be posted to
1241 * @return HTMLForm $this for chaining calls (since 1.20)
1243 function setTitle( $t ) {
1253 function getTitle() {
1254 return $this->mTitle
=== false
1255 ?
$this->getContext()->getTitle()
1260 * Set the method used to submit the form
1262 * @param string $method
1264 * @return HTMLForm $this for chaining calls (since 1.20)
1266 public function setMethod( $method = 'post' ) {
1267 $this->mMethod
= $method;
1272 public function getMethod() {
1273 return $this->mMethod
;
1279 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1281 * @param string $sectionName ID attribute of the "<table>" tag for this
1282 * section, ignored if empty.
1283 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1284 * each subsection, ignored if empty.
1285 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1289 public function displaySection( $fields,
1291 $fieldsetIDPrefix = '',
1292 &$hasUserVisibleFields = false ) {
1293 $displayFormat = $this->getDisplayFormat();
1296 $subsectionHtml = '';
1299 // Conveniently, PHP method names are case-insensitive.
1300 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1302 foreach ( $fields as $key => $value ) {
1303 if ( $value instanceof HTMLFormField
) {
1304 $v = empty( $value->mParams
['nodata'] )
1305 ?
$this->mFieldData
[$key]
1306 : $value->getDefault();
1307 $html .= $value->$getFieldHtmlMethod( $v );
1309 $labelValue = trim( $value->getLabel() );
1310 if ( $labelValue != ' ' && $labelValue !== '' ) {
1314 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1315 get_class( $value ) !== 'HTMLApiField'
1317 $hasUserVisibleFields = true;
1319 } elseif ( is_array( $value ) ) {
1320 $subsectionHasVisibleFields = false;
1322 $this->displaySection( $value,
1324 "$fieldsetIDPrefix$key-",
1325 $subsectionHasVisibleFields );
1328 if ( $subsectionHasVisibleFields === true ) {
1329 // Display the section with various niceties.
1330 $hasUserVisibleFields = true;
1332 $legend = $this->getLegend( $key );
1334 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1335 $section = $this->mSectionHeaders
[$key] . $section;
1337 if ( isset( $this->mSectionFooters
[$key] ) ) {
1338 $section .= $this->mSectionFooters
[$key];
1341 $attributes = array();
1342 if ( $fieldsetIDPrefix ) {
1343 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1345 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1347 // Just return the inputs, nothing fancy.
1348 $subsectionHtml .= $section;
1353 if ( $displayFormat !== 'raw' ) {
1356 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1357 $classes[] = 'mw-htmlform-nolabel';
1361 'class' => implode( ' ', $classes ),
1364 if ( $sectionName ) {
1365 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1368 if ( $displayFormat === 'table' ) {
1369 $html = Html
::rawElement( 'table',
1371 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1372 } elseif ( $displayFormat === 'inline' ) {
1373 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1375 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1379 if ( $this->mSubSectionBeforeFields
) {
1380 return $subsectionHtml . "\n" . $html;
1382 return $html . "\n" . $subsectionHtml;
1387 * Construct the form fields from the Descriptor array
1389 function loadData() {
1390 $fieldData = array();
1392 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1393 if ( !empty( $field->mParams
['nodata'] ) ) {
1395 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1396 $fieldData[$fieldname] = $field->getDefault();
1398 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1403 foreach ( $fieldData as $name => &$value ) {
1404 $field = $this->mFlatFields
[$name];
1405 $value = $field->filter( $value, $this->mFlatFields
);
1408 $this->mFieldData
= $fieldData;
1412 * Stop a reset button being shown for this form
1414 * @param bool $suppressReset Set to false to re-enable the button again
1416 * @return HTMLForm $this for chaining calls (since 1.20)
1418 function suppressReset( $suppressReset = true ) {
1419 $this->mShowReset
= !$suppressReset;
1425 * Overload this if you want to apply special filtration routines
1426 * to the form as a whole, after it's submitted but before it's
1429 * @param array $data
1433 function filterDataForSubmit( $data ) {
1438 * Get a string to go in the "<legend>" of a section fieldset.
1439 * Override this if you want something more complicated.
1441 * @param string $key
1445 public function getLegend( $key ) {
1446 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1450 * Set the value for the action attribute of the form.
1451 * When set to false (which is the default state), the set title is used.
1455 * @param string|bool $action
1457 * @return HTMLForm $this for chaining calls (since 1.20)
1459 public function setAction( $action ) {
1460 $this->mAction
= $action;
1466 * Get the value for the action attribute of the form.
1472 public function getAction() {
1473 // If an action is alredy provided, return it
1474 if ( $this->mAction
!== false ) {
1475 return $this->mAction
;
1478 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1479 // Check whether we are in GET mode and the ArticlePath contains a "?"
1480 // meaning that getLocalURL() would return something like "index.php?title=...".
1481 // As browser remove the query string before submitting GET forms,
1482 // it means that the title would be lost. In such case use wfScript() instead
1483 // and put title in an hidden field (see getHiddenFields()).
1484 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1488 return $this->getTitle()->getLocalURL();