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;
143 protected $mSubmitCallback;
144 protected $mValidationErrorMessage;
146 protected $mPre = '';
147 protected $mHeader = '';
148 protected $mFooter = '';
149 protected $mSectionHeaders = array();
150 protected $mSectionFooters = array();
151 protected $mPost = '';
153 protected $mTableId = '';
155 protected $mSubmitID;
156 protected $mSubmitName;
157 protected $mSubmitText;
158 protected $mSubmitTooltip;
161 protected $mMethod = 'post';
162 protected $mWasSubmitted = false;
165 * Form action URL. false means we will use the URL to set Title
169 protected $mAction = false;
171 protected $mUseMultipart = false;
172 protected $mHiddenFields = array();
173 protected $mButtons = array();
175 protected $mWrapperLegend = false;
178 * Salt for the edit token.
181 protected $mTokenSalt = '';
184 * If true, sections that contain both fields and subsections will
185 * render their subsections before their fields.
187 * Subclasses may set this to false to render subsections after fields
190 protected $mSubSectionBeforeFields = true;
193 * Format in which to display form. For viable options,
194 * @see $availableDisplayFormats
197 protected $displayFormat = 'table';
200 * Available formats in which to display the form
203 protected $availableDisplayFormats = array(
211 * Build a new HTMLForm from an array of field attributes
213 * @param array $descriptor Array of Field constructs, as described above
214 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
215 * Obviates the need to call $form->setTitle()
216 * @param string $messagePrefix A prefix to go in front of default messages
218 public function __construct( $descriptor, /*IContextSource*/ $context = null,
221 if ( $context instanceof IContextSource
) {
222 $this->setContext( $context );
223 $this->mTitle
= false; // We don't need them to set a title
224 $this->mMessagePrefix
= $messagePrefix;
225 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
226 $this->mMessagePrefix
= $messagePrefix;
227 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
229 // it's actually $messagePrefix
230 $this->mMessagePrefix
= $context;
233 // Expand out into a tree.
234 $loadedDescriptor = array();
235 $this->mFlatFields
= array();
237 foreach ( $descriptor as $fieldname => $info ) {
238 $section = isset( $info['section'] )
242 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
243 $this->mUseMultipart
= true;
246 $field = self
::loadInputFromParameters( $fieldname, $info );
247 // FIXME During field's construct, the parent form isn't available!
248 // could add a 'parent' name-value to $info, could add a third parameter.
249 $field->mParent
= $this;
251 // vform gets too much space if empty labels generate HTML.
252 if ( $this->isVForm() ) {
253 $field->setShowEmptyLabel( false );
256 $setSection =& $loadedDescriptor;
258 $sectionParts = explode( '/', $section );
260 while ( count( $sectionParts ) ) {
261 $newName = array_shift( $sectionParts );
263 if ( !isset( $setSection[$newName] ) ) {
264 $setSection[$newName] = array();
267 $setSection =& $setSection[$newName];
271 $setSection[$fieldname] = $field;
272 $this->mFlatFields
[$fieldname] = $field;
275 $this->mFieldTree
= $loadedDescriptor;
279 * Set format in which to display the form
281 * @param string $format The name of the format to use, must be one of
282 * $this->availableDisplayFormats
284 * @throws MWException
286 * @return HTMLForm $this for chaining calls (since 1.20)
288 public function setDisplayFormat( $format ) {
289 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
290 throw new MWException( 'Display format must be one of ' .
291 print_r( $this->availableDisplayFormats
, true ) );
293 $this->displayFormat
= $format;
299 * Getter for displayFormat
303 public function getDisplayFormat() {
304 $format = $this->displayFormat
;
305 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
312 * Test if displayFormat is 'vform'
316 public function isVForm() {
317 return $this->displayFormat
=== 'vform';
321 * Get the HTMLFormField subclass for this descriptor.
323 * The descriptor can be passed either 'class' which is the name of
324 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
325 * This makes sure the 'class' is always set, and also is returned by
326 * this function for ease.
330 * @param string $fieldname Name of the field
331 * @param array $descriptor Input Descriptor, as described above
333 * @throws MWException
334 * @return string Name of a HTMLFormField subclass
336 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
337 if ( isset( $descriptor['class'] ) ) {
338 $class = $descriptor['class'];
339 } elseif ( isset( $descriptor['type'] ) ) {
340 $class = self
::$typeMappings[$descriptor['type']];
341 $descriptor['class'] = $class;
347 throw new MWException( "Descriptor with no class for $fieldname: "
348 . print_r( $descriptor, true ) );
355 * Initialise a new Object for the field
357 * @param string $fieldname Name of the field
358 * @param array $descriptor Input Descriptor, as described above
360 * @throws MWException
361 * @return HTMLFormField Instance of a subclass of HTMLFormField
363 public static function loadInputFromParameters( $fieldname, $descriptor ) {
364 $class = self
::getClassFromDescriptor( $fieldname, $descriptor );
366 $descriptor['fieldname'] = $fieldname;
368 # @todo This will throw a fatal error whenever someone try to use
369 # 'class' to feed a CSS class instead of 'cssclass'. Would be
370 # great to avoid the fatal error and show a nice error.
371 $obj = new $class( $descriptor );
377 * Prepare form for submission.
379 * @attention When doing method chaining, that should be the very last
380 * method call before displayForm().
382 * @throws MWException
383 * @return HTMLForm $this for chaining calls (since 1.20)
385 function prepareForm() {
386 # Check if we have the info we need
387 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
388 throw new MWException( "You must call setTitle() on an HTMLForm" );
391 # Load data from the request.
398 * Try submitting, with edit token check first
399 * @return Status|bool
401 function tryAuthorizedSubmit() {
405 if ( $this->getMethod() != 'post' ) {
406 $submit = true; // no session check needed
407 } elseif ( $this->getRequest()->wasPosted() ) {
408 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
409 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
410 // Session tokens for logged-out users have no security value.
411 // However, if the user gave one, check it in order to give a nice
412 // "session expired" error instead of "permission denied" or such.
413 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
420 $this->mWasSubmitted
= true;
421 $result = $this->trySubmit();
428 * The here's-one-I-made-earlier option: do the submission if
429 * posted, or display the form with or without funky validation
431 * @return bool|Status Whether submission was successful.
434 $this->prepareForm();
436 $result = $this->tryAuthorizedSubmit();
437 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
441 $this->displayForm( $result );
447 * Validate all the fields, and call the submission callback
448 * function if everything is kosher.
449 * @throws MWException
450 * @return bool|string|array|Status
451 * - Bool true or a good Status object indicates success,
452 * - Bool false indicates no submission was attempted,
453 * - Anything else indicates failure. The value may be a fatal Status
454 * object, an HTML string, or an array of arrays (message keys and
455 * params) or strings (message keys)
457 function trySubmit() {
458 $this->mWasSubmitted
= true;
460 # Check for cancelled submission
461 foreach ( $this->mFlatFields
as $fieldname => $field ) {
462 if ( !empty( $field->mParams
['nodata'] ) ) {
465 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
466 $this->mWasSubmitted
= false;
471 # Check for validation
472 foreach ( $this->mFlatFields
as $fieldname => $field ) {
473 if ( !empty( $field->mParams
['nodata'] ) ) {
476 if ( $field->validate(
477 $this->mFieldData
[$fieldname],
481 return isset( $this->mValidationErrorMessage
)
482 ?
$this->mValidationErrorMessage
483 : array( 'htmlform-invalid-input' );
487 $callback = $this->mSubmitCallback
;
488 if ( !is_callable( $callback ) ) {
489 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
490 'setSubmitCallback() to set one.' );
493 $data = $this->filterDataForSubmit( $this->mFieldData
);
495 $res = call_user_func( $callback, $data, $this );
496 if ( $res === false ) {
497 $this->mWasSubmitted
= false;
504 * Test whether the form was considered to have been submitted or not, i.e.
505 * whether the last call to tryAuthorizedSubmit or trySubmit returned
508 * This will return false until HTMLForm::tryAuthorizedSubmit or
509 * HTMLForm::trySubmit is called.
514 function wasSubmitted() {
515 return $this->mWasSubmitted
;
519 * Set a callback to a function to do something with the form
520 * once it's been successfully validated.
522 * @param callable $cb The function will be passed the output from
523 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
524 * return as documented for HTMLForm::trySubmit
526 * @return HTMLForm $this for chaining calls (since 1.20)
528 function setSubmitCallback( $cb ) {
529 $this->mSubmitCallback
= $cb;
535 * Set a message to display on a validation error.
537 * @param string|array $msg String or Array of valid inputs to wfMessage()
538 * (so each entry can be either a String or Array)
540 * @return HTMLForm $this for chaining calls (since 1.20)
542 function setValidationErrorMessage( $msg ) {
543 $this->mValidationErrorMessage
= $msg;
549 * Set the introductory message, overwriting any existing message.
551 * @param string $msg Complete text of message to display
553 * @return HTMLForm $this for chaining calls (since 1.20)
555 function setIntro( $msg ) {
556 $this->setPreText( $msg );
562 * Set the introductory message, overwriting any existing message.
565 * @param string $msg Complete text of message to display
567 * @return HTMLForm $this for chaining calls (since 1.20)
569 function setPreText( $msg ) {
576 * Add introductory text.
578 * @param string $msg Complete text of message to display
580 * @return HTMLForm $this for chaining calls (since 1.20)
582 function addPreText( $msg ) {
589 * Add header text, inside the form.
591 * @param string $msg Complete text of message to display
592 * @param string|null $section The section to add the header to
594 * @return HTMLForm $this for chaining calls (since 1.20)
596 function addHeaderText( $msg, $section = null ) {
597 if ( is_null( $section ) ) {
598 $this->mHeader
.= $msg;
600 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
601 $this->mSectionHeaders
[$section] = '';
603 $this->mSectionHeaders
[$section] .= $msg;
610 * Set header text, inside the form.
613 * @param string $msg Complete text of message to display
614 * @param string|null $section The section to add the header to
616 * @return HTMLForm $this for chaining calls (since 1.20)
618 function setHeaderText( $msg, $section = null ) {
619 if ( is_null( $section ) ) {
620 $this->mHeader
= $msg;
622 $this->mSectionHeaders
[$section] = $msg;
629 * Add footer text, inside the form.
631 * @param string $msg Complete text of message to display
632 * @param string|null $section The section to add the footer text to
634 * @return HTMLForm $this for chaining calls (since 1.20)
636 function addFooterText( $msg, $section = null ) {
637 if ( is_null( $section ) ) {
638 $this->mFooter
.= $msg;
640 if ( !isset( $this->mSectionFooters
[$section] ) ) {
641 $this->mSectionFooters
[$section] = '';
643 $this->mSectionFooters
[$section] .= $msg;
650 * Set footer text, inside the form.
653 * @param string $msg Complete text of message to display
654 * @param string|null $section The section to add the footer text to
656 * @return HTMLForm $this for chaining calls (since 1.20)
658 function setFooterText( $msg, $section = null ) {
659 if ( is_null( $section ) ) {
660 $this->mFooter
= $msg;
662 $this->mSectionFooters
[$section] = $msg;
669 * Add text to the end of the display.
671 * @param string $msg Complete text of message to display
673 * @return HTMLForm $this for chaining calls (since 1.20)
675 function addPostText( $msg ) {
676 $this->mPost
.= $msg;
682 * Set text at the end of the display.
684 * @param string $msg Complete text of message to display
686 * @return HTMLForm $this for chaining calls (since 1.20)
688 function setPostText( $msg ) {
695 * Add a hidden field to the output
697 * @param string $name Field name. This will be used exactly as entered
698 * @param string $value Field value
699 * @param array $attribs
701 * @return HTMLForm $this for chaining calls (since 1.20)
703 public function addHiddenField( $name, $value, $attribs = array() ) {
704 $attribs +
= array( 'name' => $name );
705 $this->mHiddenFields
[] = array( $value, $attribs );
711 * Add an array of hidden fields to the output
715 * @param array $fields Associative array of fields to add;
716 * mapping names to their values
718 * @return HTMLForm $this for chaining calls
720 public function addHiddenFields( array $fields ) {
721 foreach ( $fields as $name => $value ) {
722 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
729 * Add a button to the form
731 * @param string $name Field name.
732 * @param string $value Field value
733 * @param string $id DOM id for the button (default: null)
734 * @param array $attribs
736 * @return HTMLForm $this for chaining calls (since 1.20)
738 public function addButton( $name, $value, $id = null, $attribs = null ) {
739 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
745 * Set the salt for the edit token.
747 * Only useful when the method is "post".
750 * @param string|array $salt Salt to use
751 * @return HTMLForm $this For chaining calls
753 public function setTokenSalt( $salt ) {
754 $this->mTokenSalt
= $salt;
760 * Display the form (sending to the context's OutputPage object), with an
761 * appropriate error message or stack of messages, and any validation errors, etc.
763 * @attention You should call prepareForm() before calling this function.
764 * Moreover, when doing method chaining this should be the very last method
765 * call just after prepareForm().
767 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
769 * @return void Nothing, should be last call
771 function displayForm( $submitResult ) {
772 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
776 * Returns the raw HTML generated by the form
778 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
782 function getHTML( $submitResult ) {
783 # For good measure (it is the default)
784 $this->getOutput()->preventClickjacking();
785 $this->getOutput()->addModules( 'mediawiki.htmlform' );
786 if ( $this->isVForm() ) {
787 $this->getOutput()->addModuleStyles( array(
789 'mediawiki.ui.button',
791 // @todo Should vertical form set setWrapperLegend( false )
792 // to hide ugly fieldsets?
796 . $this->getErrors( $submitResult )
799 . $this->getHiddenFields()
800 . $this->getButtons()
803 $html = $this->wrapForm( $html );
805 return '' . $this->mPre
. $html . $this->mPost
;
809 * Wrap the form innards in an actual "<form>" element
811 * @param string $html HTML contents to wrap.
813 * @return string Wrapped HTML.
815 function wrapForm( $html ) {
817 # Include a <fieldset> wrapper for style, if requested.
818 if ( $this->mWrapperLegend
!== false ) {
819 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
821 # Use multipart/form-data
822 $encType = $this->mUseMultipart
823 ?
'multipart/form-data'
824 : 'application/x-www-form-urlencoded';
827 'action' => $this->getAction(),
828 'method' => $this->getMethod(),
829 'class' => array( 'visualClear' ),
830 'enctype' => $encType,
832 if ( !empty( $this->mId
) ) {
833 $attribs['id'] = $this->mId
;
836 if ( $this->isVForm() ) {
837 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
840 return Html
::rawElement( 'form', $attribs, $html );
844 * Get the hidden fields that should go inside the form.
845 * @return string HTML.
847 function getHiddenFields() {
849 if ( $this->getMethod() == 'post' ) {
850 $html .= Html
::hidden(
852 $this->getUser()->getEditToken( $this->mTokenSalt
),
853 array( 'id' => 'wpEditToken' )
855 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
858 $articlePath = $this->getConfig()->get( 'ArticlePath' );
859 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
860 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
863 foreach ( $this->mHiddenFields
as $data ) {
864 list( $value, $attribs ) = $data;
865 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
872 * Get the submit and (potentially) reset buttons.
873 * @return string HTML.
875 function getButtons() {
877 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
879 if ( $this->mShowSubmit
) {
882 if ( isset( $this->mSubmitID
) ) {
883 $attribs['id'] = $this->mSubmitID
;
886 if ( isset( $this->mSubmitName
) ) {
887 $attribs['name'] = $this->mSubmitName
;
890 if ( isset( $this->mSubmitTooltip
) ) {
891 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
894 $attribs['class'] = array( 'mw-htmlform-submit' );
896 if ( $this->isVForm() ||
$useMediaWikiUIEverywhere ) {
897 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-constructive' );
900 if ( $this->isVForm() ) {
901 // mw-ui-block is necessary because the buttons aren't necessarily in an
902 // immediate child div of the vform.
903 // @todo Let client specify if the primary submit button is progressive or destructive
911 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
914 if ( $this->mShowReset
) {
915 $buttons .= Html
::element(
919 'value' => $this->msg( 'htmlform-reset' )->text()
924 foreach ( $this->mButtons
as $button ) {
927 'name' => $button['name'],
928 'value' => $button['value']
931 if ( $button['attribs'] ) {
932 $attrs +
= $button['attribs'];
935 if ( isset( $button['id'] ) ) {
936 $attrs['id'] = $button['id'];
939 if ( $useMediaWikiUIEverywhere ) {
940 if ( isset( $attrs['class'] ) ) {
941 $attrs['class'] .= ' mw-ui-button';
943 $attrs['class'] = 'mw-ui-button';
947 $buttons .= Html
::element( 'input', $attrs ) . "\n";
950 $html = Html
::rawElement( 'span',
951 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
953 // Buttons are top-level form elements in table and div layouts,
954 // but vform wants all elements inside divs to get spaced-out block
956 if ( $this->mShowSubmit
&& $this->isVForm() ) {
957 $html = Html
::rawElement( 'div', null, "\n$html" ) . "\n";
964 * Get the whole body of the form.
968 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
972 * Format and display an error message stack.
974 * @param string|array|Status $errors
978 function getErrors( $errors ) {
979 if ( $errors instanceof Status
) {
980 if ( $errors->isOK() ) {
983 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
985 } elseif ( is_array( $errors ) ) {
986 $errorstr = $this->formatErrors( $errors );
992 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
997 * Format a stack of error messages into a single HTML string
999 * @param array $errors Array of message keys/values
1001 * @return string HTML, a "<ul>" list of errors
1003 public static function formatErrors( $errors ) {
1006 foreach ( $errors as $error ) {
1007 if ( is_array( $error ) ) {
1008 $msg = array_shift( $error );
1014 $errorstr .= Html
::rawElement(
1017 wfMessage( $msg, $error )->parse()
1021 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1027 * Set the text for the submit button
1029 * @param string $t Plaintext
1031 * @return HTMLForm $this for chaining calls (since 1.20)
1033 function setSubmitText( $t ) {
1034 $this->mSubmitText
= $t;
1040 * Set the text for the submit button to a message
1043 * @param string|Message $msg Message key or Message object
1045 * @return HTMLForm $this for chaining calls (since 1.20)
1047 public function setSubmitTextMsg( $msg ) {
1048 if ( !$msg instanceof Message
) {
1049 $msg = $this->msg( $msg );
1051 $this->setSubmitText( $msg->text() );
1057 * Get the text for the submit button, either customised or a default.
1060 function getSubmitText() {
1061 return $this->mSubmitText
1062 ?
$this->mSubmitText
1063 : $this->msg( 'htmlform-submit' )->text();
1067 * @param string $name Submit button name
1069 * @return HTMLForm $this for chaining calls (since 1.20)
1071 public function setSubmitName( $name ) {
1072 $this->mSubmitName
= $name;
1078 * @param string $name Tooltip for the submit button
1080 * @return HTMLForm $this for chaining calls (since 1.20)
1082 public function setSubmitTooltip( $name ) {
1083 $this->mSubmitTooltip
= $name;
1089 * Set the id for the submit button.
1093 * @todo FIXME: Integrity of $t is *not* validated
1094 * @return HTMLForm $this for chaining calls (since 1.20)
1096 function setSubmitID( $t ) {
1097 $this->mSubmitID
= $t;
1103 * Stop a default submit button being shown for this form. This implies that an
1104 * alternate submit method must be provided manually.
1108 * @param bool $suppressSubmit Set to false to re-enable the button again
1110 * @return HTMLForm $this for chaining calls
1112 function suppressDefaultSubmit( $suppressSubmit = true ) {
1113 $this->mShowSubmit
= !$suppressSubmit;
1119 * Set the id of the \<table\> or outermost \<div\> element.
1123 * @param string $id New value of the id attribute, or "" to remove
1125 * @return HTMLForm $this for chaining calls
1127 public function setTableId( $id ) {
1128 $this->mTableId
= $id;
1134 * @param string $id DOM id for the form
1136 * @return HTMLForm $this for chaining calls (since 1.20)
1138 public function setId( $id ) {
1145 * Prompt the whole form to be wrapped in a "<fieldset>", with
1146 * this text as its "<legend>" element.
1148 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1149 * false for no <legend>
1152 * @return HTMLForm $this for chaining calls (since 1.20)
1154 public function setWrapperLegend( $legend ) {
1155 $this->mWrapperLegend
= $legend;
1161 * Prompt the whole form to be wrapped in a "<fieldset>", with
1162 * this message as its "<legend>" element.
1165 * @param string|Message $msg Message key or Message object
1167 * @return HTMLForm $this for chaining calls (since 1.20)
1169 public function setWrapperLegendMsg( $msg ) {
1170 if ( !$msg instanceof Message
) {
1171 $msg = $this->msg( $msg );
1173 $this->setWrapperLegend( $msg->text() );
1179 * Set the prefix for various default messages
1180 * @todo Currently only used for the "<fieldset>" legend on forms
1181 * with multiple sections; should be used elsewhere?
1185 * @return HTMLForm $this for chaining calls (since 1.20)
1187 function setMessagePrefix( $p ) {
1188 $this->mMessagePrefix
= $p;
1194 * Set the title for form submission
1196 * @param Title $t Title of page the form is on/should be posted to
1198 * @return HTMLForm $this for chaining calls (since 1.20)
1200 function setTitle( $t ) {
1210 function getTitle() {
1211 return $this->mTitle
=== false
1212 ?
$this->getContext()->getTitle()
1217 * Set the method used to submit the form
1219 * @param string $method
1221 * @return HTMLForm $this for chaining calls (since 1.20)
1223 public function setMethod( $method = 'post' ) {
1224 $this->mMethod
= $method;
1229 public function getMethod() {
1230 return $this->mMethod
;
1236 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1238 * @param string $sectionName ID attribute of the "<table>" tag for this
1239 * section, ignored if empty.
1240 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1241 * each subsection, ignored if empty.
1242 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1246 public function displaySection( $fields,
1248 $fieldsetIDPrefix = '',
1249 &$hasUserVisibleFields = false ) {
1250 $displayFormat = $this->getDisplayFormat();
1253 $subsectionHtml = '';
1256 switch ( $displayFormat ) {
1258 $getFieldHtmlMethod = 'getTableRow';
1261 // Close enough to a div.
1262 $getFieldHtmlMethod = 'getDiv';
1265 $getFieldHtmlMethod = 'getDiv';
1268 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1271 foreach ( $fields as $key => $value ) {
1272 if ( $value instanceof HTMLFormField
) {
1273 $v = empty( $value->mParams
['nodata'] )
1274 ?
$this->mFieldData
[$key]
1275 : $value->getDefault();
1276 $html .= $value->$getFieldHtmlMethod( $v );
1278 $labelValue = trim( $value->getLabel() );
1279 if ( $labelValue != ' ' && $labelValue !== '' ) {
1283 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1284 get_class( $value ) !== 'HTMLApiField'
1286 $hasUserVisibleFields = true;
1288 } elseif ( is_array( $value ) ) {
1289 $subsectionHasVisibleFields = false;
1291 $this->displaySection( $value,
1293 "$fieldsetIDPrefix$key-",
1294 $subsectionHasVisibleFields );
1297 if ( $subsectionHasVisibleFields === true ) {
1298 // Display the section with various niceties.
1299 $hasUserVisibleFields = true;
1301 $legend = $this->getLegend( $key );
1303 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1304 $section = $this->mSectionHeaders
[$key] . $section;
1306 if ( isset( $this->mSectionFooters
[$key] ) ) {
1307 $section .= $this->mSectionFooters
[$key];
1310 $attributes = array();
1311 if ( $fieldsetIDPrefix ) {
1312 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1314 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1316 // Just return the inputs, nothing fancy.
1317 $subsectionHtml .= $section;
1322 if ( $displayFormat !== 'raw' ) {
1325 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1326 $classes[] = 'mw-htmlform-nolabel';
1330 'class' => implode( ' ', $classes ),
1333 if ( $sectionName ) {
1334 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1337 if ( $displayFormat === 'table' ) {
1338 $html = Html
::rawElement( 'table',
1340 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1341 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1342 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1346 if ( $this->mSubSectionBeforeFields
) {
1347 return $subsectionHtml . "\n" . $html;
1349 return $html . "\n" . $subsectionHtml;
1354 * Construct the form fields from the Descriptor array
1356 function loadData() {
1357 $fieldData = array();
1359 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1360 if ( !empty( $field->mParams
['nodata'] ) ) {
1362 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1363 $fieldData[$fieldname] = $field->getDefault();
1365 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1370 foreach ( $fieldData as $name => &$value ) {
1371 $field = $this->mFlatFields
[$name];
1372 $value = $field->filter( $value, $this->mFlatFields
);
1375 $this->mFieldData
= $fieldData;
1379 * Stop a reset button being shown for this form
1381 * @param bool $suppressReset Set to false to re-enable the button again
1383 * @return HTMLForm $this for chaining calls (since 1.20)
1385 function suppressReset( $suppressReset = true ) {
1386 $this->mShowReset
= !$suppressReset;
1392 * Overload this if you want to apply special filtration routines
1393 * to the form as a whole, after it's submitted but before it's
1396 * @param array $data
1400 function filterDataForSubmit( $data ) {
1405 * Get a string to go in the "<legend>" of a section fieldset.
1406 * Override this if you want something more complicated.
1408 * @param string $key
1412 public function getLegend( $key ) {
1413 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1417 * Set the value for the action attribute of the form.
1418 * When set to false (which is the default state), the set title is used.
1422 * @param string|bool $action
1424 * @return HTMLForm $this for chaining calls (since 1.20)
1426 public function setAction( $action ) {
1427 $this->mAction
= $action;
1433 * Get the value for the action attribute of the form.
1439 public function getAction() {
1440 // If an action is alredy provided, return it
1441 if ( $this->mAction
!== false ) {
1442 return $this->mAction
;
1445 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1446 // Check whether we are in GET mode and the ArticlePath contains a "?"
1447 // meaning that getLocalURL() would return something like "index.php?title=...".
1448 // As browser remove the query string before submitting GET forms,
1449 // it means that the title would be lost. In such case use wfScript() instead
1450 // and put title in an hidden field (see getHiddenFields()).
1451 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1455 return $this->getTitle()->getLocalURL();