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() {
365 * Get the HTMLFormField subclass for this descriptor.
367 * The descriptor can be passed either 'class' which is the name of
368 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
369 * This makes sure the 'class' is always set, and also is returned by
370 * this function for ease.
374 * @param string $fieldname Name of the field
375 * @param array $descriptor Input Descriptor, as described above
377 * @throws MWException
378 * @return string Name of a HTMLFormField subclass
380 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
381 if ( isset( $descriptor['class'] ) ) {
382 $class = $descriptor['class'];
383 } elseif ( isset( $descriptor['type'] ) ) {
384 $class = static::$typeMappings[$descriptor['type']];
385 $descriptor['class'] = $class;
391 throw new MWException( "Descriptor with no class for $fieldname: "
392 . print_r( $descriptor, true ) );
399 * Initialise a new Object for the field
401 * @param string $fieldname Name of the field
402 * @param array $descriptor Input Descriptor, as described above
403 * @param HTMLForm|null $parent Parent instance of HTMLForm
405 * @throws MWException
406 * @return HTMLFormField Instance of a subclass of HTMLFormField
408 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm
$parent = null ) {
409 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
411 $descriptor['fieldname'] = $fieldname;
413 $descriptor['parent'] = $parent;
416 # @todo This will throw a fatal error whenever someone try to use
417 # 'class' to feed a CSS class instead of 'cssclass'. Would be
418 # great to avoid the fatal error and show a nice error.
419 $obj = new $class( $descriptor );
425 * Prepare form for submission.
427 * @attention When doing method chaining, that should be the very last
428 * method call before displayForm().
430 * @throws MWException
431 * @return HTMLForm $this for chaining calls (since 1.20)
433 function prepareForm() {
434 # Check if we have the info we need
435 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
436 throw new MWException( "You must call setTitle() on an HTMLForm" );
439 # Load data from the request.
446 * Try submitting, with edit token check first
447 * @return Status|bool
449 function tryAuthorizedSubmit() {
453 if ( $this->getMethod() != 'post' ) {
454 $submit = true; // no session check needed
455 } elseif ( $this->getRequest()->wasPosted() ) {
456 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
457 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
458 // Session tokens for logged-out users have no security value.
459 // However, if the user gave one, check it in order to give a nice
460 // "session expired" error instead of "permission denied" or such.
461 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
468 $this->mWasSubmitted
= true;
469 $result = $this->trySubmit();
476 * The here's-one-I-made-earlier option: do the submission if
477 * posted, or display the form with or without funky validation
479 * @return bool|Status Whether submission was successful.
482 $this->prepareForm();
484 $result = $this->tryAuthorizedSubmit();
485 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
489 $this->displayForm( $result );
495 * Validate all the fields, and call the submission callback
496 * function if everything is kosher.
497 * @throws MWException
498 * @return bool|string|array|Status
499 * - Bool true or a good Status object indicates success,
500 * - Bool false indicates no submission was attempted,
501 * - Anything else indicates failure. The value may be a fatal Status
502 * object, an HTML string, or an array of arrays (message keys and
503 * params) or strings (message keys)
505 function trySubmit() {
506 $this->mWasSubmitted
= true;
508 # Check for cancelled submission
509 foreach ( $this->mFlatFields
as $fieldname => $field ) {
510 if ( !empty( $field->mParams
['nodata'] ) ) {
513 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
514 $this->mWasSubmitted
= false;
519 # Check for validation
520 foreach ( $this->mFlatFields
as $fieldname => $field ) {
521 if ( !empty( $field->mParams
['nodata'] ) ) {
524 if ( $field->isHidden( $this->mFieldData
) ) {
527 if ( $field->validate(
528 $this->mFieldData
[$fieldname],
532 return isset( $this->mValidationErrorMessage
)
533 ?
$this->mValidationErrorMessage
534 : array( 'htmlform-invalid-input' );
538 $callback = $this->mSubmitCallback
;
539 if ( !is_callable( $callback ) ) {
540 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
541 'setSubmitCallback() to set one.' );
544 $data = $this->filterDataForSubmit( $this->mFieldData
);
546 $res = call_user_func( $callback, $data, $this );
547 if ( $res === false ) {
548 $this->mWasSubmitted
= false;
555 * Test whether the form was considered to have been submitted or not, i.e.
556 * whether the last call to tryAuthorizedSubmit or trySubmit returned
559 * This will return false until HTMLForm::tryAuthorizedSubmit or
560 * HTMLForm::trySubmit is called.
565 function wasSubmitted() {
566 return $this->mWasSubmitted
;
570 * Set a callback to a function to do something with the form
571 * once it's been successfully validated.
573 * @param callable $cb The function will be passed the output from
574 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
575 * return as documented for HTMLForm::trySubmit
577 * @return HTMLForm $this for chaining calls (since 1.20)
579 function setSubmitCallback( $cb ) {
580 $this->mSubmitCallback
= $cb;
586 * Set a message to display on a validation error.
588 * @param string|array $msg String or Array of valid inputs to wfMessage()
589 * (so each entry can be either a String or Array)
591 * @return HTMLForm $this for chaining calls (since 1.20)
593 function setValidationErrorMessage( $msg ) {
594 $this->mValidationErrorMessage
= $msg;
600 * Set the introductory message, overwriting any existing message.
602 * @param string $msg Complete text of message to display
604 * @return HTMLForm $this for chaining calls (since 1.20)
606 function setIntro( $msg ) {
607 $this->setPreText( $msg );
613 * Set the introductory message, overwriting any existing message.
616 * @param string $msg Complete text of message to display
618 * @return HTMLForm $this for chaining calls (since 1.20)
620 function setPreText( $msg ) {
627 * Add introductory text.
629 * @param string $msg Complete text of message to display
631 * @return HTMLForm $this for chaining calls (since 1.20)
633 function addPreText( $msg ) {
640 * Add header text, inside the form.
642 * @param string $msg Complete text of message to display
643 * @param string|null $section The section to add the header to
645 * @return HTMLForm $this for chaining calls (since 1.20)
647 function addHeaderText( $msg, $section = null ) {
648 if ( is_null( $section ) ) {
649 $this->mHeader
.= $msg;
651 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
652 $this->mSectionHeaders
[$section] = '';
654 $this->mSectionHeaders
[$section] .= $msg;
661 * Set header text, inside the form.
664 * @param string $msg Complete text of message to display
665 * @param string|null $section The section to add the header to
667 * @return HTMLForm $this for chaining calls (since 1.20)
669 function setHeaderText( $msg, $section = null ) {
670 if ( is_null( $section ) ) {
671 $this->mHeader
= $msg;
673 $this->mSectionHeaders
[$section] = $msg;
680 * Add footer text, inside the form.
682 * @param string $msg Complete text of message to display
683 * @param string|null $section The section to add the footer text to
685 * @return HTMLForm $this for chaining calls (since 1.20)
687 function addFooterText( $msg, $section = null ) {
688 if ( is_null( $section ) ) {
689 $this->mFooter
.= $msg;
691 if ( !isset( $this->mSectionFooters
[$section] ) ) {
692 $this->mSectionFooters
[$section] = '';
694 $this->mSectionFooters
[$section] .= $msg;
701 * Set footer text, inside the form.
704 * @param string $msg Complete text of message to display
705 * @param string|null $section The section to add the footer text to
707 * @return HTMLForm $this for chaining calls (since 1.20)
709 function setFooterText( $msg, $section = null ) {
710 if ( is_null( $section ) ) {
711 $this->mFooter
= $msg;
713 $this->mSectionFooters
[$section] = $msg;
720 * Add text to the end of the display.
722 * @param string $msg Complete text of message to display
724 * @return HTMLForm $this for chaining calls (since 1.20)
726 function addPostText( $msg ) {
727 $this->mPost
.= $msg;
733 * Set text at the end of the display.
735 * @param string $msg Complete text of message to display
737 * @return HTMLForm $this for chaining calls (since 1.20)
739 function setPostText( $msg ) {
746 * Add a hidden field to the output
748 * @param string $name Field name. This will be used exactly as entered
749 * @param string $value Field value
750 * @param array $attribs
752 * @return HTMLForm $this for chaining calls (since 1.20)
754 public function addHiddenField( $name, $value, $attribs = array() ) {
755 $attribs +
= array( 'name' => $name );
756 $this->mHiddenFields
[] = array( $value, $attribs );
762 * Add an array of hidden fields to the output
766 * @param array $fields Associative array of fields to add;
767 * mapping names to their values
769 * @return HTMLForm $this for chaining calls
771 public function addHiddenFields( array $fields ) {
772 foreach ( $fields as $name => $value ) {
773 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
780 * Add a button to the form
782 * @param string $name Field name.
783 * @param string $value Field value
784 * @param string $id DOM id for the button (default: null)
785 * @param array $attribs
787 * @return HTMLForm $this for chaining calls (since 1.20)
789 public function addButton( $name, $value, $id = null, $attribs = null ) {
790 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
796 * Set the salt for the edit token.
798 * Only useful when the method is "post".
801 * @param string|array $salt Salt to use
802 * @return HTMLForm $this For chaining calls
804 public function setTokenSalt( $salt ) {
805 $this->mTokenSalt
= $salt;
811 * Display the form (sending to the context's OutputPage object), with an
812 * appropriate error message or stack of messages, and any validation errors, etc.
814 * @attention You should call prepareForm() before calling this function.
815 * Moreover, when doing method chaining this should be the very last method
816 * call just after prepareForm().
818 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
820 * @return void Nothing, should be last call
822 function displayForm( $submitResult ) {
823 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
827 * Returns the raw HTML generated by the form
829 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
833 function getHTML( $submitResult ) {
834 # For good measure (it is the default)
835 $this->getOutput()->preventClickjacking();
836 $this->getOutput()->addModules( 'mediawiki.htmlform' );
839 . $this->getErrors( $submitResult )
842 . $this->getHiddenFields()
843 . $this->getButtons()
846 $html = $this->wrapForm( $html );
848 return '' . $this->mPre
. $html . $this->mPost
;
852 * Get HTML attributes for the `<form>` tag.
855 protected function getFormAttributes() {
856 # Use multipart/form-data
857 $encType = $this->mUseMultipart
858 ?
'multipart/form-data'
859 : 'application/x-www-form-urlencoded';
862 'action' => $this->getAction(),
863 'method' => $this->getMethod(),
864 'class' => array( 'visualClear' ),
865 'enctype' => $encType,
867 if ( !empty( $this->mId
) ) {
868 $attribs['id'] = $this->mId
;
874 * Wrap the form innards in an actual "<form>" element
876 * @param string $html HTML contents to wrap.
878 * @return string Wrapped HTML.
880 function wrapForm( $html ) {
881 # Include a <fieldset> wrapper for style, if requested.
882 if ( $this->mWrapperLegend
!== false ) {
883 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
886 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
890 * Get the hidden fields that should go inside the form.
891 * @return string HTML.
893 function getHiddenFields() {
895 if ( $this->getMethod() == 'post' ) {
896 $html .= Html
::hidden(
898 $this->getUser()->getEditToken( $this->mTokenSalt
),
899 array( 'id' => 'wpEditToken' )
901 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
904 $articlePath = $this->getConfig()->get( 'ArticlePath' );
905 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
906 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
909 foreach ( $this->mHiddenFields
as $data ) {
910 list( $value, $attribs ) = $data;
911 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
918 * Get the submit and (potentially) reset buttons.
919 * @return string HTML.
921 function getButtons() {
923 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
925 if ( $this->mShowSubmit
) {
928 if ( isset( $this->mSubmitID
) ) {
929 $attribs['id'] = $this->mSubmitID
;
932 if ( isset( $this->mSubmitName
) ) {
933 $attribs['name'] = $this->mSubmitName
;
936 if ( isset( $this->mSubmitTooltip
) ) {
937 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
940 $attribs['class'] = array( 'mw-htmlform-submit' );
942 if ( $useMediaWikiUIEverywhere ) {
943 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
946 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
949 if ( $this->mShowReset
) {
950 $buttons .= Html
::element(
954 'value' => $this->msg( 'htmlform-reset' )->text(),
955 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
960 foreach ( $this->mButtons
as $button ) {
963 'name' => $button['name'],
964 'value' => $button['value']
967 if ( $button['attribs'] ) {
968 $attrs +
= $button['attribs'];
971 if ( isset( $button['id'] ) ) {
972 $attrs['id'] = $button['id'];
975 if ( $useMediaWikiUIEverywhere ) {
976 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
977 $attrs['class'][] = 'mw-ui-button';
980 $buttons .= Html
::element( 'input', $attrs ) . "\n";
983 $html = Html
::rawElement( 'span',
984 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
990 * Get the whole body of the form.
994 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
998 * Format and display an error message stack.
1000 * @param string|array|Status $errors
1004 function getErrors( $errors ) {
1005 if ( $errors instanceof Status
) {
1006 if ( $errors->isOK() ) {
1009 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1011 } elseif ( is_array( $errors ) ) {
1012 $errorstr = $this->formatErrors( $errors );
1014 $errorstr = $errors;
1018 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1023 * Format a stack of error messages into a single HTML string
1025 * @param array $errors Array of message keys/values
1027 * @return string HTML, a "<ul>" list of errors
1029 public function formatErrors( $errors ) {
1032 foreach ( $errors as $error ) {
1033 if ( is_array( $error ) ) {
1034 $msg = array_shift( $error );
1040 $errorstr .= Html
::rawElement(
1043 $this->msg( $msg, $error )->parse()
1047 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1053 * Set the text for the submit button
1055 * @param string $t Plaintext
1057 * @return HTMLForm $this for chaining calls (since 1.20)
1059 function setSubmitText( $t ) {
1060 $this->mSubmitText
= $t;
1066 * Identify that the submit button in the form has a destructive action
1069 public function setSubmitDestructive() {
1070 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1074 * Identify that the submit button in the form has a progressive action
1077 public function setSubmitProgressive() {
1078 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1082 * Set the text for the submit button to a message
1085 * @param string|Message $msg Message key or Message object
1087 * @return HTMLForm $this for chaining calls (since 1.20)
1089 public function setSubmitTextMsg( $msg ) {
1090 if ( !$msg instanceof Message
) {
1091 $msg = $this->msg( $msg );
1093 $this->setSubmitText( $msg->text() );
1099 * Get the text for the submit button, either customised or a default.
1102 function getSubmitText() {
1103 return $this->mSubmitText
1104 ?
$this->mSubmitText
1105 : $this->msg( 'htmlform-submit' )->text();
1109 * @param string $name Submit button name
1111 * @return HTMLForm $this for chaining calls (since 1.20)
1113 public function setSubmitName( $name ) {
1114 $this->mSubmitName
= $name;
1120 * @param string $name Tooltip for the submit button
1122 * @return HTMLForm $this for chaining calls (since 1.20)
1124 public function setSubmitTooltip( $name ) {
1125 $this->mSubmitTooltip
= $name;
1131 * Set the id for the submit button.
1135 * @todo FIXME: Integrity of $t is *not* validated
1136 * @return HTMLForm $this for chaining calls (since 1.20)
1138 function setSubmitID( $t ) {
1139 $this->mSubmitID
= $t;
1145 * Stop a default submit button being shown for this form. This implies that an
1146 * alternate submit method must be provided manually.
1150 * @param bool $suppressSubmit Set to false to re-enable the button again
1152 * @return HTMLForm $this for chaining calls
1154 function suppressDefaultSubmit( $suppressSubmit = true ) {
1155 $this->mShowSubmit
= !$suppressSubmit;
1161 * Set the id of the \<table\> or outermost \<div\> element.
1165 * @param string $id New value of the id attribute, or "" to remove
1167 * @return HTMLForm $this for chaining calls
1169 public function setTableId( $id ) {
1170 $this->mTableId
= $id;
1176 * @param string $id DOM id for the form
1178 * @return HTMLForm $this for chaining calls (since 1.20)
1180 public function setId( $id ) {
1187 * Prompt the whole form to be wrapped in a "<fieldset>", with
1188 * this text as its "<legend>" element.
1190 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1191 * false for no <legend>
1194 * @return HTMLForm $this for chaining calls (since 1.20)
1196 public function setWrapperLegend( $legend ) {
1197 $this->mWrapperLegend
= $legend;
1203 * Prompt the whole form to be wrapped in a "<fieldset>", with
1204 * this message as its "<legend>" element.
1207 * @param string|Message $msg Message key or Message object
1209 * @return HTMLForm $this for chaining calls (since 1.20)
1211 public function setWrapperLegendMsg( $msg ) {
1212 if ( !$msg instanceof Message
) {
1213 $msg = $this->msg( $msg );
1215 $this->setWrapperLegend( $msg->text() );
1221 * Set the prefix for various default messages
1222 * @todo Currently only used for the "<fieldset>" legend on forms
1223 * with multiple sections; should be used elsewhere?
1227 * @return HTMLForm $this for chaining calls (since 1.20)
1229 function setMessagePrefix( $p ) {
1230 $this->mMessagePrefix
= $p;
1236 * Set the title for form submission
1238 * @param Title $t Title of page the form is on/should be posted to
1240 * @return HTMLForm $this for chaining calls (since 1.20)
1242 function setTitle( $t ) {
1252 function getTitle() {
1253 return $this->mTitle
=== false
1254 ?
$this->getContext()->getTitle()
1259 * Set the method used to submit the form
1261 * @param string $method
1263 * @return HTMLForm $this for chaining calls (since 1.20)
1265 public function setMethod( $method = 'post' ) {
1266 $this->mMethod
= $method;
1271 public function getMethod() {
1272 return $this->mMethod
;
1278 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1280 * @param string $sectionName ID attribute of the "<table>" tag for this
1281 * section, ignored if empty.
1282 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1283 * each subsection, ignored if empty.
1284 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1288 public function displaySection( $fields,
1290 $fieldsetIDPrefix = '',
1291 &$hasUserVisibleFields = false ) {
1292 $displayFormat = $this->getDisplayFormat();
1295 $subsectionHtml = '';
1298 // Conveniently, PHP method names are case-insensitive.
1299 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1301 foreach ( $fields as $key => $value ) {
1302 if ( $value instanceof HTMLFormField
) {
1303 $v = empty( $value->mParams
['nodata'] )
1304 ?
$this->mFieldData
[$key]
1305 : $value->getDefault();
1306 $html .= $value->$getFieldHtmlMethod( $v );
1308 $labelValue = trim( $value->getLabel() );
1309 if ( $labelValue != ' ' && $labelValue !== '' ) {
1313 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1314 get_class( $value ) !== 'HTMLApiField'
1316 $hasUserVisibleFields = true;
1318 } elseif ( is_array( $value ) ) {
1319 $subsectionHasVisibleFields = false;
1321 $this->displaySection( $value,
1323 "$fieldsetIDPrefix$key-",
1324 $subsectionHasVisibleFields );
1327 if ( $subsectionHasVisibleFields === true ) {
1328 // Display the section with various niceties.
1329 $hasUserVisibleFields = true;
1331 $legend = $this->getLegend( $key );
1333 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1334 $section = $this->mSectionHeaders
[$key] . $section;
1336 if ( isset( $this->mSectionFooters
[$key] ) ) {
1337 $section .= $this->mSectionFooters
[$key];
1340 $attributes = array();
1341 if ( $fieldsetIDPrefix ) {
1342 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1344 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1346 // Just return the inputs, nothing fancy.
1347 $subsectionHtml .= $section;
1352 if ( $displayFormat !== 'raw' ) {
1355 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1356 $classes[] = 'mw-htmlform-nolabel';
1360 'class' => implode( ' ', $classes ),
1363 if ( $sectionName ) {
1364 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1367 if ( $displayFormat === 'table' ) {
1368 $html = Html
::rawElement( 'table',
1370 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1371 } elseif ( $displayFormat === 'inline' ) {
1372 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1374 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1378 if ( $this->mSubSectionBeforeFields
) {
1379 return $subsectionHtml . "\n" . $html;
1381 return $html . "\n" . $subsectionHtml;
1386 * Construct the form fields from the Descriptor array
1388 function loadData() {
1389 $fieldData = array();
1391 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1392 if ( !empty( $field->mParams
['nodata'] ) ) {
1394 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1395 $fieldData[$fieldname] = $field->getDefault();
1397 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1402 foreach ( $fieldData as $name => &$value ) {
1403 $field = $this->mFlatFields
[$name];
1404 $value = $field->filter( $value, $this->mFlatFields
);
1407 $this->mFieldData
= $fieldData;
1411 * Stop a reset button being shown for this form
1413 * @param bool $suppressReset Set to false to re-enable the button again
1415 * @return HTMLForm $this for chaining calls (since 1.20)
1417 function suppressReset( $suppressReset = true ) {
1418 $this->mShowReset
= !$suppressReset;
1424 * Overload this if you want to apply special filtration routines
1425 * to the form as a whole, after it's submitted but before it's
1428 * @param array $data
1432 function filterDataForSubmit( $data ) {
1437 * Get a string to go in the "<legend>" of a section fieldset.
1438 * Override this if you want something more complicated.
1440 * @param string $key
1444 public function getLegend( $key ) {
1445 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1449 * Set the value for the action attribute of the form.
1450 * When set to false (which is the default state), the set title is used.
1454 * @param string|bool $action
1456 * @return HTMLForm $this for chaining calls (since 1.20)
1458 public function setAction( $action ) {
1459 $this->mAction
= $action;
1465 * Get the value for the action attribute of the form.
1471 public function getAction() {
1472 // If an action is alredy provided, return it
1473 if ( $this->mAction
!== false ) {
1474 return $this->mAction
;
1477 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1478 // Check whether we are in GET mode and the ArticlePath contains a "?"
1479 // meaning that getLocalURL() would return something like "index.php?title=...".
1480 // As browser remove the query string before submitting GET forms,
1481 // it means that the title would be lost. In such case use wfScript() instead
1482 // and put title in an hidden field (see getHiddenFields()).
1483 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1487 return $this->getTitle()->getLocalURL();