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 * 'options' -- associative array mapping labels to values.
55 * Some field types support multi-level arrays.
56 * 'options-messages' -- associative array mapping message keys to values.
57 * Some field types support multi-level arrays.
58 * 'options-message' -- message key to be parsed to extract the list of
59 * options (like 'ipbreason-dropdown').
60 * 'label-message' -- message key for a message to use as the label.
61 * can be an array of msg key and then parameters to
63 * 'label' -- alternatively, a raw text message. Overridden by
65 * 'help' -- message text for a message to use as a help text.
66 * 'help-message' -- message key for a message to use as a help text.
67 * can be an array of msg key and then parameters to
69 * Overwrites 'help-messages' and 'help'.
70 * 'help-messages' -- array of message key. As above, each item can
71 * be an array of msg key and then parameters.
73 * 'required' -- passed through to the object, indicating that it
74 * is a required field.
75 * 'size' -- the length of text fields
76 * 'filter-callback -- a function name to give you the chance to
77 * massage the inputted value before it's processed.
78 * @see HTMLForm::filter()
79 * 'validation-callback' -- a function name to give you the chance
80 * to impose extra validation on the field input.
81 * @see HTMLForm::validate()
82 * 'name' -- By default, the 'name' attribute of the input field
83 * is "wp{$fieldname}". If you want a different name
84 * (eg one without the "wp" prefix), specify it here and
85 * it will be used without modification.
87 * Since 1.20, you can chain mutators to ease the form generation:
90 * $form = new HTMLForm( $someFields );
91 * $form->setMethod( 'get' )
92 * ->setWrapperLegendMsg( 'message-key' )
94 * ->displayForm( '' );
96 * Note that you will have prepareForm and displayForm at the end. Other
97 * methods call done after that would simply not be part of the form :(
99 * @todo Document 'section' / 'subsection' stuff
101 class HTMLForm
extends ContextSource
{
102 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
103 public static $typeMappings = array(
104 'api' => 'HTMLApiField',
105 'text' => 'HTMLTextField',
106 'textarea' => 'HTMLTextAreaField',
107 'select' => 'HTMLSelectField',
108 'radio' => 'HTMLRadioField',
109 'multiselect' => 'HTMLMultiSelectField',
110 'limitselect' => 'HTMLSelectLimitField',
111 'check' => 'HTMLCheckField',
112 'toggle' => 'HTMLCheckField',
113 'int' => 'HTMLIntField',
114 'float' => 'HTMLFloatField',
115 'info' => 'HTMLInfoField',
116 'selectorother' => 'HTMLSelectOrOtherField',
117 'selectandother' => 'HTMLSelectAndOtherField',
118 'submit' => 'HTMLSubmitField',
119 'hidden' => 'HTMLHiddenField',
120 'edittools' => 'HTMLEditTools',
121 'checkmatrix' => 'HTMLCheckMatrix',
122 'cloner' => 'HTMLFormFieldCloner',
123 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
124 // HTMLTextField will output the correct type="" attribute automagically.
125 // There are about four zillion other HTML5 input types, like range, but
126 // we don't use those at the moment, so no point in adding all of them.
127 'email' => 'HTMLTextField',
128 'password' => 'HTMLTextField',
129 'url' => 'HTMLTextField',
134 protected $mMessagePrefix;
136 /** @var HTMLFormField[] */
137 protected $mFlatFields;
139 protected $mFieldTree;
140 protected $mShowReset = false;
141 protected $mShowSubmit = true;
142 protected $mSubmitModifierClass = 'mw-ui-constructive';
144 protected $mSubmitCallback;
145 protected $mValidationErrorMessage;
147 protected $mPre = '';
148 protected $mHeader = '';
149 protected $mFooter = '';
150 protected $mSectionHeaders = array();
151 protected $mSectionFooters = array();
152 protected $mPost = '';
154 protected $mTableId = '';
156 protected $mSubmitID;
157 protected $mSubmitName;
158 protected $mSubmitText;
159 protected $mSubmitTooltip;
162 protected $mMethod = 'post';
163 protected $mWasSubmitted = false;
166 * Form action URL. false means we will use the URL to set Title
170 protected $mAction = false;
172 protected $mUseMultipart = false;
173 protected $mHiddenFields = array();
174 protected $mButtons = array();
176 protected $mWrapperLegend = false;
179 * Salt for the edit token.
182 protected $mTokenSalt = '';
185 * If true, sections that contain both fields and subsections will
186 * render their subsections before their fields.
188 * Subclasses may set this to false to render subsections after fields
191 protected $mSubSectionBeforeFields = true;
194 * Format in which to display form. For viable options,
195 * @see $availableDisplayFormats
198 protected $displayFormat = 'table';
201 * Available formats in which to display the form
204 protected $availableDisplayFormats = array(
212 * Build a new HTMLForm from an array of field attributes
214 * @param array $descriptor Array of Field constructs, as described above
215 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
216 * Obviates the need to call $form->setTitle()
217 * @param string $messagePrefix A prefix to go in front of default messages
219 public function __construct( $descriptor, /*IContextSource*/ $context = null,
222 if ( $context instanceof IContextSource
) {
223 $this->setContext( $context );
224 $this->mTitle
= false; // We don't need them to set a title
225 $this->mMessagePrefix
= $messagePrefix;
226 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
227 $this->mMessagePrefix
= $messagePrefix;
228 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
230 // it's actually $messagePrefix
231 $this->mMessagePrefix
= $context;
234 // Expand out into a tree.
235 $loadedDescriptor = array();
236 $this->mFlatFields
= array();
238 foreach ( $descriptor as $fieldname => $info ) {
239 $section = isset( $info['section'] )
243 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
244 $this->mUseMultipart
= true;
247 $field = self
::loadInputFromParameters( $fieldname, $info );
248 // FIXME During field's construct, the parent form isn't available!
249 // could add a 'parent' name-value to $info, could add a third parameter.
250 $field->mParent
= $this;
252 // vform gets too much space if empty labels generate HTML.
253 if ( $this->isVForm() ) {
254 $field->setShowEmptyLabel( false );
257 $setSection =& $loadedDescriptor;
259 $sectionParts = explode( '/', $section );
261 while ( count( $sectionParts ) ) {
262 $newName = array_shift( $sectionParts );
264 if ( !isset( $setSection[$newName] ) ) {
265 $setSection[$newName] = array();
268 $setSection =& $setSection[$newName];
272 $setSection[$fieldname] = $field;
273 $this->mFlatFields
[$fieldname] = $field;
276 $this->mFieldTree
= $loadedDescriptor;
280 * Set format in which to display the form
282 * @param string $format The name of the format to use, must be one of
283 * $this->availableDisplayFormats
285 * @throws MWException
287 * @return HTMLForm $this for chaining calls (since 1.20)
289 public function setDisplayFormat( $format ) {
290 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
291 throw new MWException( 'Display format must be one of ' .
292 print_r( $this->availableDisplayFormats
, true ) );
294 $this->displayFormat
= $format;
300 * Getter for displayFormat
304 public function getDisplayFormat() {
305 $format = $this->displayFormat
;
306 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
313 * Test if displayFormat is 'vform'
317 public function isVForm() {
318 return $this->displayFormat
=== 'vform';
322 * Get the HTMLFormField subclass for this descriptor.
324 * The descriptor can be passed either 'class' which is the name of
325 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
326 * This makes sure the 'class' is always set, and also is returned by
327 * this function for ease.
331 * @param string $fieldname Name of the field
332 * @param array $descriptor Input Descriptor, as described above
334 * @throws MWException
335 * @return string Name of a HTMLFormField subclass
337 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
338 if ( isset( $descriptor['class'] ) ) {
339 $class = $descriptor['class'];
340 } elseif ( isset( $descriptor['type'] ) ) {
341 $class = self
::$typeMappings[$descriptor['type']];
342 $descriptor['class'] = $class;
348 throw new MWException( "Descriptor with no class for $fieldname: "
349 . print_r( $descriptor, true ) );
356 * Initialise a new Object for the field
358 * @param string $fieldname Name of the field
359 * @param array $descriptor Input Descriptor, as described above
361 * @throws MWException
362 * @return HTMLFormField Instance of a subclass of HTMLFormField
364 public static function loadInputFromParameters( $fieldname, $descriptor ) {
365 $class = self
::getClassFromDescriptor( $fieldname, $descriptor );
367 $descriptor['fieldname'] = $fieldname;
369 # @todo This will throw a fatal error whenever someone try to use
370 # 'class' to feed a CSS class instead of 'cssclass'. Would be
371 # great to avoid the fatal error and show a nice error.
372 $obj = new $class( $descriptor );
378 * Prepare form for submission.
380 * @attention When doing method chaining, that should be the very last
381 * method call before displayForm().
383 * @throws MWException
384 * @return HTMLForm $this for chaining calls (since 1.20)
386 function prepareForm() {
387 # Check if we have the info we need
388 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
389 throw new MWException( "You must call setTitle() on an HTMLForm" );
392 # Load data from the request.
399 * Try submitting, with edit token check first
400 * @return Status|bool
402 function tryAuthorizedSubmit() {
406 if ( $this->getMethod() != 'post' ) {
407 $submit = true; // no session check needed
408 } elseif ( $this->getRequest()->wasPosted() ) {
409 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
410 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
411 // Session tokens for logged-out users have no security value.
412 // However, if the user gave one, check it in order to give a nice
413 // "session expired" error instead of "permission denied" or such.
414 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
421 $this->mWasSubmitted
= true;
422 $result = $this->trySubmit();
429 * The here's-one-I-made-earlier option: do the submission if
430 * posted, or display the form with or without funky validation
432 * @return bool|Status Whether submission was successful.
435 $this->prepareForm();
437 $result = $this->tryAuthorizedSubmit();
438 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
442 $this->displayForm( $result );
448 * Validate all the fields, and call the submission callback
449 * function if everything is kosher.
450 * @throws MWException
451 * @return bool|string|array|Status
452 * - Bool true or a good Status object indicates success,
453 * - Bool false indicates no submission was attempted,
454 * - Anything else indicates failure. The value may be a fatal Status
455 * object, an HTML string, or an array of arrays (message keys and
456 * params) or strings (message keys)
458 function trySubmit() {
459 $this->mWasSubmitted
= true;
461 # Check for cancelled submission
462 foreach ( $this->mFlatFields
as $fieldname => $field ) {
463 if ( !empty( $field->mParams
['nodata'] ) ) {
466 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
467 $this->mWasSubmitted
= false;
472 # Check for validation
473 foreach ( $this->mFlatFields
as $fieldname => $field ) {
474 if ( !empty( $field->mParams
['nodata'] ) ) {
477 if ( $field->isHidden( $this->mFieldData
) ) {
480 if ( $field->validate(
481 $this->mFieldData
[$fieldname],
485 return isset( $this->mValidationErrorMessage
)
486 ?
$this->mValidationErrorMessage
487 : array( 'htmlform-invalid-input' );
491 $callback = $this->mSubmitCallback
;
492 if ( !is_callable( $callback ) ) {
493 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
494 'setSubmitCallback() to set one.' );
497 $data = $this->filterDataForSubmit( $this->mFieldData
);
499 $res = call_user_func( $callback, $data, $this );
500 if ( $res === false ) {
501 $this->mWasSubmitted
= false;
508 * Test whether the form was considered to have been submitted or not, i.e.
509 * whether the last call to tryAuthorizedSubmit or trySubmit returned
512 * This will return false until HTMLForm::tryAuthorizedSubmit or
513 * HTMLForm::trySubmit is called.
518 function wasSubmitted() {
519 return $this->mWasSubmitted
;
523 * Set a callback to a function to do something with the form
524 * once it's been successfully validated.
526 * @param callable $cb The function will be passed the output from
527 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
528 * return as documented for HTMLForm::trySubmit
530 * @return HTMLForm $this for chaining calls (since 1.20)
532 function setSubmitCallback( $cb ) {
533 $this->mSubmitCallback
= $cb;
539 * Set a message to display on a validation error.
541 * @param string|array $msg String or Array of valid inputs to wfMessage()
542 * (so each entry can be either a String or Array)
544 * @return HTMLForm $this for chaining calls (since 1.20)
546 function setValidationErrorMessage( $msg ) {
547 $this->mValidationErrorMessage
= $msg;
553 * Set the introductory message, overwriting any existing message.
555 * @param string $msg Complete text of message to display
557 * @return HTMLForm $this for chaining calls (since 1.20)
559 function setIntro( $msg ) {
560 $this->setPreText( $msg );
566 * Set the introductory message, overwriting any existing message.
569 * @param string $msg Complete text of message to display
571 * @return HTMLForm $this for chaining calls (since 1.20)
573 function setPreText( $msg ) {
580 * Add introductory text.
582 * @param string $msg Complete text of message to display
584 * @return HTMLForm $this for chaining calls (since 1.20)
586 function addPreText( $msg ) {
593 * Add header text, inside the form.
595 * @param string $msg Complete text of message to display
596 * @param string|null $section The section to add the header to
598 * @return HTMLForm $this for chaining calls (since 1.20)
600 function addHeaderText( $msg, $section = null ) {
601 if ( is_null( $section ) ) {
602 $this->mHeader
.= $msg;
604 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
605 $this->mSectionHeaders
[$section] = '';
607 $this->mSectionHeaders
[$section] .= $msg;
614 * Set header text, inside the form.
617 * @param string $msg Complete text of message to display
618 * @param string|null $section The section to add the header to
620 * @return HTMLForm $this for chaining calls (since 1.20)
622 function setHeaderText( $msg, $section = null ) {
623 if ( is_null( $section ) ) {
624 $this->mHeader
= $msg;
626 $this->mSectionHeaders
[$section] = $msg;
633 * Add footer text, inside the form.
635 * @param string $msg Complete text of message to display
636 * @param string|null $section The section to add the footer text to
638 * @return HTMLForm $this for chaining calls (since 1.20)
640 function addFooterText( $msg, $section = null ) {
641 if ( is_null( $section ) ) {
642 $this->mFooter
.= $msg;
644 if ( !isset( $this->mSectionFooters
[$section] ) ) {
645 $this->mSectionFooters
[$section] = '';
647 $this->mSectionFooters
[$section] .= $msg;
654 * Set footer text, inside the form.
657 * @param string $msg Complete text of message to display
658 * @param string|null $section The section to add the footer text to
660 * @return HTMLForm $this for chaining calls (since 1.20)
662 function setFooterText( $msg, $section = null ) {
663 if ( is_null( $section ) ) {
664 $this->mFooter
= $msg;
666 $this->mSectionFooters
[$section] = $msg;
673 * Add text to the end of the display.
675 * @param string $msg Complete text of message to display
677 * @return HTMLForm $this for chaining calls (since 1.20)
679 function addPostText( $msg ) {
680 $this->mPost
.= $msg;
686 * Set text at the end of the display.
688 * @param string $msg Complete text of message to display
690 * @return HTMLForm $this for chaining calls (since 1.20)
692 function setPostText( $msg ) {
699 * Add a hidden field to the output
701 * @param string $name Field name. This will be used exactly as entered
702 * @param string $value Field value
703 * @param array $attribs
705 * @return HTMLForm $this for chaining calls (since 1.20)
707 public function addHiddenField( $name, $value, $attribs = array() ) {
708 $attribs +
= array( 'name' => $name );
709 $this->mHiddenFields
[] = array( $value, $attribs );
715 * Add an array of hidden fields to the output
719 * @param array $fields Associative array of fields to add;
720 * mapping names to their values
722 * @return HTMLForm $this for chaining calls
724 public function addHiddenFields( array $fields ) {
725 foreach ( $fields as $name => $value ) {
726 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
733 * Add a button to the form
735 * @param string $name Field name.
736 * @param string $value Field value
737 * @param string $id DOM id for the button (default: null)
738 * @param array $attribs
740 * @return HTMLForm $this for chaining calls (since 1.20)
742 public function addButton( $name, $value, $id = null, $attribs = null ) {
743 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
749 * Set the salt for the edit token.
751 * Only useful when the method is "post".
754 * @param string|array $salt Salt to use
755 * @return HTMLForm $this For chaining calls
757 public function setTokenSalt( $salt ) {
758 $this->mTokenSalt
= $salt;
764 * Display the form (sending to the context's OutputPage object), with an
765 * appropriate error message or stack of messages, and any validation errors, etc.
767 * @attention You should call prepareForm() before calling this function.
768 * Moreover, when doing method chaining this should be the very last method
769 * call just after prepareForm().
771 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
773 * @return void Nothing, should be last call
775 function displayForm( $submitResult ) {
776 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
780 * Returns the raw HTML generated by the form
782 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
786 function getHTML( $submitResult ) {
787 # For good measure (it is the default)
788 $this->getOutput()->preventClickjacking();
789 $this->getOutput()->addModules( 'mediawiki.htmlform' );
790 if ( $this->isVForm() ) {
791 $this->getOutput()->addModuleStyles( array(
793 'mediawiki.ui.button',
795 // @todo Should vertical form set setWrapperLegend( false )
796 // to hide ugly fieldsets?
800 . $this->getErrors( $submitResult )
803 . $this->getHiddenFields()
804 . $this->getButtons()
807 $html = $this->wrapForm( $html );
809 return '' . $this->mPre
. $html . $this->mPost
;
813 * Wrap the form innards in an actual "<form>" element
815 * @param string $html HTML contents to wrap.
817 * @return string Wrapped HTML.
819 function wrapForm( $html ) {
821 # Include a <fieldset> wrapper for style, if requested.
822 if ( $this->mWrapperLegend
!== false ) {
823 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
825 # Use multipart/form-data
826 $encType = $this->mUseMultipart
827 ?
'multipart/form-data'
828 : 'application/x-www-form-urlencoded';
831 'action' => $this->getAction(),
832 'method' => $this->getMethod(),
833 'class' => array( 'visualClear' ),
834 'enctype' => $encType,
836 if ( !empty( $this->mId
) ) {
837 $attribs['id'] = $this->mId
;
840 if ( $this->isVForm() ) {
841 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
844 return Html
::rawElement( 'form', $attribs, $html );
848 * Get the hidden fields that should go inside the form.
849 * @return string HTML.
851 function getHiddenFields() {
853 if ( $this->getMethod() == 'post' ) {
854 $html .= Html
::hidden(
856 $this->getUser()->getEditToken( $this->mTokenSalt
),
857 array( 'id' => 'wpEditToken' )
859 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
862 $articlePath = $this->getConfig()->get( 'ArticlePath' );
863 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
864 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
867 foreach ( $this->mHiddenFields
as $data ) {
868 list( $value, $attribs ) = $data;
869 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
876 * Get the submit and (potentially) reset buttons.
877 * @return string HTML.
879 function getButtons() {
881 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
883 if ( $this->mShowSubmit
) {
886 if ( isset( $this->mSubmitID
) ) {
887 $attribs['id'] = $this->mSubmitID
;
890 if ( isset( $this->mSubmitName
) ) {
891 $attribs['name'] = $this->mSubmitName
;
894 if ( isset( $this->mSubmitTooltip
) ) {
895 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
898 $attribs['class'] = array( 'mw-htmlform-submit' );
900 if ( $this->isVForm() ||
$useMediaWikiUIEverywhere ) {
901 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
904 if ( $this->isVForm() ) {
905 // mw-ui-block is necessary because the buttons aren't necessarily in an
906 // immediate child div of the vform.
907 // @todo Let client specify if the primary submit button is progressive or destructive
915 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
918 if ( $this->mShowReset
) {
919 $buttons .= Html
::element(
923 'value' => $this->msg( 'htmlform-reset' )->text()
928 foreach ( $this->mButtons
as $button ) {
931 'name' => $button['name'],
932 'value' => $button['value']
935 if ( $button['attribs'] ) {
936 $attrs +
= $button['attribs'];
939 if ( isset( $button['id'] ) ) {
940 $attrs['id'] = $button['id'];
943 if ( $this->isVForm() ||
$useMediaWikiUIEverywhere ) {
944 if ( isset( $attrs['class'] ) ) {
945 $attrs['class'] .= ' mw-ui-button';
947 $attrs['class'] = 'mw-ui-button';
949 if ( $this->isVForm() ) {
950 $attrs['class'] .= ' mw-ui-big mw-ui-block';
954 $buttons .= Html
::element( 'input', $attrs ) . "\n";
957 $html = Html
::rawElement( 'span',
958 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
960 // Buttons are top-level form elements in table and div layouts,
961 // but vform wants all elements inside divs to get spaced-out block
963 if ( $this->mShowSubmit
&& $this->isVForm() ) {
964 $html = Html
::rawElement( 'div', null, "\n$html" ) . "\n";
971 * Get the whole body of the form.
975 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
979 * Format and display an error message stack.
981 * @param string|array|Status $errors
985 function getErrors( $errors ) {
986 if ( $errors instanceof Status
) {
987 if ( $errors->isOK() ) {
990 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
992 } elseif ( is_array( $errors ) ) {
993 $errorstr = $this->formatErrors( $errors );
999 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1004 * Format a stack of error messages into a single HTML string
1006 * @param array $errors Array of message keys/values
1008 * @return string HTML, a "<ul>" list of errors
1010 public static function formatErrors( $errors ) {
1013 foreach ( $errors as $error ) {
1014 if ( is_array( $error ) ) {
1015 $msg = array_shift( $error );
1021 $errorstr .= Html
::rawElement(
1024 wfMessage( $msg, $error )->parse()
1028 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1034 * Set the text for the submit button
1036 * @param string $t Plaintext
1038 * @return HTMLForm $this for chaining calls (since 1.20)
1040 function setSubmitText( $t ) {
1041 $this->mSubmitText
= $t;
1047 * Identify that the submit button in the form has a destructive action
1050 public function setSubmitDestructive() {
1051 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1055 * Identify that the submit button in the form has a progressive action
1058 public function setSubmitProgressive() {
1059 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1063 * Set the text for the submit button to a message
1066 * @param string|Message $msg Message key or Message object
1068 * @return HTMLForm $this for chaining calls (since 1.20)
1070 public function setSubmitTextMsg( $msg ) {
1071 if ( !$msg instanceof Message
) {
1072 $msg = $this->msg( $msg );
1074 $this->setSubmitText( $msg->text() );
1080 * Get the text for the submit button, either customised or a default.
1083 function getSubmitText() {
1084 return $this->mSubmitText
1085 ?
$this->mSubmitText
1086 : $this->msg( 'htmlform-submit' )->text();
1090 * @param string $name Submit button name
1092 * @return HTMLForm $this for chaining calls (since 1.20)
1094 public function setSubmitName( $name ) {
1095 $this->mSubmitName
= $name;
1101 * @param string $name Tooltip for the submit button
1103 * @return HTMLForm $this for chaining calls (since 1.20)
1105 public function setSubmitTooltip( $name ) {
1106 $this->mSubmitTooltip
= $name;
1112 * Set the id for the submit button.
1116 * @todo FIXME: Integrity of $t is *not* validated
1117 * @return HTMLForm $this for chaining calls (since 1.20)
1119 function setSubmitID( $t ) {
1120 $this->mSubmitID
= $t;
1126 * Stop a default submit button being shown for this form. This implies that an
1127 * alternate submit method must be provided manually.
1131 * @param bool $suppressSubmit Set to false to re-enable the button again
1133 * @return HTMLForm $this for chaining calls
1135 function suppressDefaultSubmit( $suppressSubmit = true ) {
1136 $this->mShowSubmit
= !$suppressSubmit;
1142 * Set the id of the \<table\> or outermost \<div\> element.
1146 * @param string $id New value of the id attribute, or "" to remove
1148 * @return HTMLForm $this for chaining calls
1150 public function setTableId( $id ) {
1151 $this->mTableId
= $id;
1157 * @param string $id DOM id for the form
1159 * @return HTMLForm $this for chaining calls (since 1.20)
1161 public function setId( $id ) {
1168 * Prompt the whole form to be wrapped in a "<fieldset>", with
1169 * this text as its "<legend>" element.
1171 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1172 * false for no <legend>
1175 * @return HTMLForm $this for chaining calls (since 1.20)
1177 public function setWrapperLegend( $legend ) {
1178 $this->mWrapperLegend
= $legend;
1184 * Prompt the whole form to be wrapped in a "<fieldset>", with
1185 * this message as its "<legend>" element.
1188 * @param string|Message $msg Message key or Message object
1190 * @return HTMLForm $this for chaining calls (since 1.20)
1192 public function setWrapperLegendMsg( $msg ) {
1193 if ( !$msg instanceof Message
) {
1194 $msg = $this->msg( $msg );
1196 $this->setWrapperLegend( $msg->text() );
1202 * Set the prefix for various default messages
1203 * @todo Currently only used for the "<fieldset>" legend on forms
1204 * with multiple sections; should be used elsewhere?
1208 * @return HTMLForm $this for chaining calls (since 1.20)
1210 function setMessagePrefix( $p ) {
1211 $this->mMessagePrefix
= $p;
1217 * Set the title for form submission
1219 * @param Title $t Title of page the form is on/should be posted to
1221 * @return HTMLForm $this for chaining calls (since 1.20)
1223 function setTitle( $t ) {
1233 function getTitle() {
1234 return $this->mTitle
=== false
1235 ?
$this->getContext()->getTitle()
1240 * Set the method used to submit the form
1242 * @param string $method
1244 * @return HTMLForm $this for chaining calls (since 1.20)
1246 public function setMethod( $method = 'post' ) {
1247 $this->mMethod
= $method;
1252 public function getMethod() {
1253 return $this->mMethod
;
1259 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1261 * @param string $sectionName ID attribute of the "<table>" tag for this
1262 * section, ignored if empty.
1263 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1264 * each subsection, ignored if empty.
1265 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1269 public function displaySection( $fields,
1271 $fieldsetIDPrefix = '',
1272 &$hasUserVisibleFields = false ) {
1273 $displayFormat = $this->getDisplayFormat();
1276 $subsectionHtml = '';
1279 switch ( $displayFormat ) {
1281 $getFieldHtmlMethod = 'getTableRow';
1284 // Close enough to a div.
1285 $getFieldHtmlMethod = 'getDiv';
1288 $getFieldHtmlMethod = 'getDiv';
1291 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1294 foreach ( $fields as $key => $value ) {
1295 if ( $value instanceof HTMLFormField
) {
1296 $v = empty( $value->mParams
['nodata'] )
1297 ?
$this->mFieldData
[$key]
1298 : $value->getDefault();
1299 $html .= $value->$getFieldHtmlMethod( $v );
1301 $labelValue = trim( $value->getLabel() );
1302 if ( $labelValue != ' ' && $labelValue !== '' ) {
1306 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1307 get_class( $value ) !== 'HTMLApiField'
1309 $hasUserVisibleFields = true;
1311 } elseif ( is_array( $value ) ) {
1312 $subsectionHasVisibleFields = false;
1314 $this->displaySection( $value,
1316 "$fieldsetIDPrefix$key-",
1317 $subsectionHasVisibleFields );
1320 if ( $subsectionHasVisibleFields === true ) {
1321 // Display the section with various niceties.
1322 $hasUserVisibleFields = true;
1324 $legend = $this->getLegend( $key );
1326 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1327 $section = $this->mSectionHeaders
[$key] . $section;
1329 if ( isset( $this->mSectionFooters
[$key] ) ) {
1330 $section .= $this->mSectionFooters
[$key];
1333 $attributes = array();
1334 if ( $fieldsetIDPrefix ) {
1335 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1337 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1339 // Just return the inputs, nothing fancy.
1340 $subsectionHtml .= $section;
1345 if ( $displayFormat !== 'raw' ) {
1348 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1349 $classes[] = 'mw-htmlform-nolabel';
1353 'class' => implode( ' ', $classes ),
1356 if ( $sectionName ) {
1357 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1360 if ( $displayFormat === 'table' ) {
1361 $html = Html
::rawElement( 'table',
1363 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1364 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1365 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1369 if ( $this->mSubSectionBeforeFields
) {
1370 return $subsectionHtml . "\n" . $html;
1372 return $html . "\n" . $subsectionHtml;
1377 * Construct the form fields from the Descriptor array
1379 function loadData() {
1380 $fieldData = array();
1382 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1383 if ( !empty( $field->mParams
['nodata'] ) ) {
1385 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1386 $fieldData[$fieldname] = $field->getDefault();
1388 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1393 foreach ( $fieldData as $name => &$value ) {
1394 $field = $this->mFlatFields
[$name];
1395 $value = $field->filter( $value, $this->mFlatFields
);
1398 $this->mFieldData
= $fieldData;
1402 * Stop a reset button being shown for this form
1404 * @param bool $suppressReset Set to false to re-enable the button again
1406 * @return HTMLForm $this for chaining calls (since 1.20)
1408 function suppressReset( $suppressReset = true ) {
1409 $this->mShowReset
= !$suppressReset;
1415 * Overload this if you want to apply special filtration routines
1416 * to the form as a whole, after it's submitted but before it's
1419 * @param array $data
1423 function filterDataForSubmit( $data ) {
1428 * Get a string to go in the "<legend>" of a section fieldset.
1429 * Override this if you want something more complicated.
1431 * @param string $key
1435 public function getLegend( $key ) {
1436 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1440 * Set the value for the action attribute of the form.
1441 * When set to false (which is the default state), the set title is used.
1445 * @param string|bool $action
1447 * @return HTMLForm $this for chaining calls (since 1.20)
1449 public function setAction( $action ) {
1450 $this->mAction
= $action;
1456 * Get the value for the action attribute of the form.
1462 public function getAction() {
1463 // If an action is alredy provided, return it
1464 if ( $this->mAction
!== false ) {
1465 return $this->mAction
;
1468 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1469 // Check whether we are in GET mode and the ArticlePath contains a "?"
1470 // meaning that getLocalURL() would return something like "index.php?title=...".
1471 // As browser remove the query string before submitting GET forms,
1472 // it means that the title would be lost. In such case use wfScript() instead
1473 // and put title in an hidden field (see getHiddenFields()).
1474 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1478 return $this->getTitle()->getLocalURL();