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 * - http://www.mediawiki.org/wiki/HTMLForm
40 * - http://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 * 'options' -- associative array mapping labels to values.
54 * Some field types support multi-level arrays.
55 * 'options-messages' -- associative array mapping message keys to values.
56 * Some field types support multi-level arrays.
57 * 'options-message' -- message key to be parsed to extract the list of
58 * options (like 'ipbreason-dropdown').
59 * 'label-message' -- message key for a message to use as the label.
60 * can be an array of msg key and then parameters to
62 * 'label' -- alternatively, a raw text message. Overridden by
64 * 'help' -- message text for a message to use as a help text.
65 * 'help-message' -- message key for a message to use as a help text.
66 * can be an array of msg key and then parameters to
68 * Overwrites 'help-messages' and 'help'.
69 * 'help-messages' -- array of message key. As above, each item can
70 * be an array of msg key and then parameters.
72 * 'required' -- passed through to the object, indicating that it
73 * is a required field.
74 * 'size' -- the length of text fields
75 * 'filter-callback -- a function name to give you the chance to
76 * massage the inputted value before it's processed.
77 * @see HTMLForm::filter()
78 * 'validation-callback' -- a function name to give you the chance
79 * to impose extra validation on the field input.
80 * @see HTMLForm::validate()
81 * 'name' -- By default, the 'name' attribute of the input field
82 * is "wp{$fieldname}". If you want a different name
83 * (eg one without the "wp" prefix), specify it here and
84 * it will be used without modification.
86 * Since 1.20, you can chain mutators to ease the form generation:
89 * $form = new HTMLForm( $someFields );
90 * $form->setMethod( 'get' )
91 * ->setWrapperLegendMsg( 'message-key' )
93 * ->displayForm( '' );
95 * Note that you will have prepareForm and displayForm at the end. Other
96 * methods call done after that would simply not be part of the form :(
98 * @todo Document 'section' / 'subsection' stuff
100 class HTMLForm
extends ContextSource
{
101 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
102 public static $typeMappings = array(
103 'api' => 'HTMLApiField',
104 'text' => 'HTMLTextField',
105 'textarea' => 'HTMLTextAreaField',
106 'select' => 'HTMLSelectField',
107 'radio' => 'HTMLRadioField',
108 'multiselect' => 'HTMLMultiSelectField',
109 'check' => 'HTMLCheckField',
110 'toggle' => 'HTMLCheckField',
111 'int' => 'HTMLIntField',
112 'float' => 'HTMLFloatField',
113 'info' => 'HTMLInfoField',
114 'selectorother' => 'HTMLSelectOrOtherField',
115 'selectandother' => 'HTMLSelectAndOtherField',
116 'submit' => 'HTMLSubmitField',
117 'hidden' => 'HTMLHiddenField',
118 'edittools' => 'HTMLEditTools',
119 'checkmatrix' => 'HTMLCheckMatrix',
120 // HTMLTextField will output the correct type="" attribute automagically.
121 // There are about four zillion other HTML5 input types, like url, but
122 // we don't use those at the moment, so no point in adding all of them.
123 'email' => 'HTMLTextField',
124 'password' => 'HTMLTextField',
129 protected $mMessagePrefix;
131 /** @var HTMLFormField[] */
132 protected $mFlatFields;
134 protected $mFieldTree;
135 protected $mShowReset = false;
136 protected $mShowSubmit = true;
138 protected $mSubmitCallback;
139 protected $mValidationErrorMessage;
141 protected $mPre = '';
142 protected $mHeader = '';
143 protected $mFooter = '';
144 protected $mSectionHeaders = array();
145 protected $mSectionFooters = array();
146 protected $mPost = '';
148 protected $mTableId = '';
150 protected $mSubmitID;
151 protected $mSubmitName;
152 protected $mSubmitText;
153 protected $mSubmitTooltip;
156 protected $mMethod = 'post';
159 * Form action URL. false means we will use the URL to set Title
163 protected $mAction = false;
165 protected $mUseMultipart = false;
166 protected $mHiddenFields = array();
167 protected $mButtons = array();
169 protected $mWrapperLegend = false;
172 * If true, sections that contain both fields and subsections will
173 * render their subsections before their fields.
175 * Subclasses may set this to false to render subsections after fields
178 protected $mSubSectionBeforeFields = true;
181 * Format in which to display form. For viable options,
182 * @see $availableDisplayFormats
185 protected $displayFormat = 'table';
188 * Available formats in which to display the form
191 protected $availableDisplayFormats = array(
199 * Build a new HTMLForm from an array of field attributes
201 * @param array $descriptor of Field constructs, as described above
202 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
203 * Obviates the need to call $form->setTitle()
204 * @param string $messagePrefix a prefix to go in front of default messages
206 public function __construct( $descriptor, /*IContextSource*/ $context = null,
209 if ( $context instanceof IContextSource
) {
210 $this->setContext( $context );
211 $this->mTitle
= false; // We don't need them to set a title
212 $this->mMessagePrefix
= $messagePrefix;
213 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
214 $this->mMessagePrefix
= $messagePrefix;
215 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
217 // it's actually $messagePrefix
218 $this->mMessagePrefix
= $context;
221 // Expand out into a tree.
222 $loadedDescriptor = array();
223 $this->mFlatFields
= array();
225 foreach ( $descriptor as $fieldname => $info ) {
226 $section = isset( $info['section'] )
230 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
231 $this->mUseMultipart
= true;
234 $field = self
::loadInputFromParameters( $fieldname, $info );
235 // FIXME During field's construct, the parent form isn't available!
236 // could add a 'parent' name-value to $info, could add a third parameter.
237 $field->mParent
= $this;
239 // vform gets too much space if empty labels generate HTML.
240 if ( $this->isVForm() ) {
241 $field->setShowEmptyLabel( false );
244 $setSection =& $loadedDescriptor;
246 $sectionParts = explode( '/', $section );
248 while ( count( $sectionParts ) ) {
249 $newName = array_shift( $sectionParts );
251 if ( !isset( $setSection[$newName] ) ) {
252 $setSection[$newName] = array();
255 $setSection =& $setSection[$newName];
259 $setSection[$fieldname] = $field;
260 $this->mFlatFields
[$fieldname] = $field;
263 $this->mFieldTree
= $loadedDescriptor;
267 * Set format in which to display the form
269 * @param string $format the name of the format to use, must be one of
270 * $this->availableDisplayFormats
272 * @throws MWException
274 * @return HTMLForm $this for chaining calls (since 1.20)
276 public function setDisplayFormat( $format ) {
277 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
278 throw new MWException( 'Display format must be one of ' .
279 print_r( $this->availableDisplayFormats
, true ) );
281 $this->displayFormat
= $format;
287 * Getter for displayFormat
291 public function getDisplayFormat() {
292 return $this->displayFormat
;
296 * Test if displayFormat is 'vform'
300 public function isVForm() {
301 return $this->displayFormat
=== 'vform';
305 * Add the HTMLForm-specific JavaScript, if it hasn't been
307 * @deprecated since 1.18 load modules with ResourceLoader instead
309 static function addJS() {
310 wfDeprecated( __METHOD__
, '1.18' );
314 * Get the HTMLFormField subclass for this descriptor.
316 * The descriptor can be passed either 'class' which is the name of
317 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
318 * This makes sure the 'class' is always set, and also is returned by
319 * this function for ease.
323 * @param string $fieldname Name of the field
324 * @param array $descriptor Input Descriptor, as described above
326 * @throws MWException
327 * @return string Name of a HTMLFormField subclass
329 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
330 if ( isset( $descriptor['class'] ) ) {
331 $class = $descriptor['class'];
332 } elseif ( isset( $descriptor['type'] ) ) {
333 $class = self
::$typeMappings[$descriptor['type']];
334 $descriptor['class'] = $class;
340 throw new MWException( "Descriptor with no class for $fieldname: " . print_r( $descriptor, true ) );
346 * Initialise a new Object for the field
348 * @param string $fieldname Name of the field
349 * @param array $descriptor Input Descriptor, as described above
351 * @throws MWException
352 * @return HTMLFormField subclass
354 public static function loadInputFromParameters( $fieldname, $descriptor ) {
355 $class = self
::getClassFromDescriptor( $fieldname, $descriptor );
357 $descriptor['fieldname'] = $fieldname;
359 # @todo This will throw a fatal error whenever someone try to use
360 # 'class' to feed a CSS class instead of 'cssclass'. Would be
361 # great to avoid the fatal error and show a nice error.
362 $obj = new $class( $descriptor );
368 * Prepare form for submission.
370 * @attention When doing method chaining, that should be the very last
371 * method call before displayForm().
373 * @throws MWException
374 * @return HTMLForm $this for chaining calls (since 1.20)
376 function prepareForm() {
377 # Check if we have the info we need
378 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
379 throw new MWException( "You must call setTitle() on an HTMLForm" );
382 # Load data from the request.
389 * Try submitting, with edit token check first
390 * @return Status|boolean
392 function tryAuthorizedSubmit() {
396 if ( $this->getMethod() != 'post' ) {
397 $submit = true; // no session check needed
398 } elseif ( $this->getRequest()->wasPosted() ) {
399 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
400 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
401 // Session tokens for logged-out users have no security value.
402 // However, if the user gave one, check it in order to give a nice
403 // "session expired" error instead of "permission denied" or such.
404 $submit = $this->getUser()->matchEditToken( $editToken );
411 $result = $this->trySubmit();
418 * The here's-one-I-made-earlier option: do the submission if
419 * posted, or display the form with or without funky validation
421 * @return Bool or Status whether submission was successful.
424 $this->prepareForm();
426 $result = $this->tryAuthorizedSubmit();
427 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
431 $this->displayForm( $result );
437 * Validate all the fields, and call the submission callback
438 * function if everything is kosher.
439 * @throws MWException
440 * @return Mixed Bool true == Successful submission, Bool false
441 * == No submission attempted, anything else == Error to
444 function trySubmit() {
445 # Check for validation
446 foreach ( $this->mFlatFields
as $fieldname => $field ) {
447 if ( !empty( $field->mParams
['nodata'] ) ) {
450 if ( $field->validate(
451 $this->mFieldData
[$fieldname],
455 return isset( $this->mValidationErrorMessage
)
456 ?
$this->mValidationErrorMessage
457 : array( 'htmlform-invalid-input' );
461 $callback = $this->mSubmitCallback
;
462 if ( !is_callable( $callback ) ) {
463 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
464 'setSubmitCallback() to set one.' );
467 $data = $this->filterDataForSubmit( $this->mFieldData
);
469 $res = call_user_func( $callback, $data, $this );
475 * Set a callback to a function to do something with the form
476 * once it's been successfully validated.
478 * @param string $cb function name. The function will be passed
479 * the output from HTMLForm::filterDataForSubmit, and must
480 * return Bool true on success, Bool false if no submission
481 * was attempted, or String HTML output to display on error.
483 * @return HTMLForm $this for chaining calls (since 1.20)
485 function setSubmitCallback( $cb ) {
486 $this->mSubmitCallback
= $cb;
492 * Set a message to display on a validation error.
494 * @param $msg Mixed String or Array of valid inputs to wfMessage()
495 * (so each entry can be either a String or Array)
497 * @return HTMLForm $this for chaining calls (since 1.20)
499 function setValidationErrorMessage( $msg ) {
500 $this->mValidationErrorMessage
= $msg;
506 * Set the introductory message, overwriting any existing message.
508 * @param string $msg complete text of message to display
510 * @return HTMLForm $this for chaining calls (since 1.20)
512 function setIntro( $msg ) {
513 $this->setPreText( $msg );
519 * Set the introductory message, overwriting any existing message.
522 * @param string $msg complete text of message to display
524 * @return HTMLForm $this for chaining calls (since 1.20)
526 function setPreText( $msg ) {
533 * Add introductory text.
535 * @param string $msg complete text of message to display
537 * @return HTMLForm $this for chaining calls (since 1.20)
539 function addPreText( $msg ) {
546 * Add header text, inside the form.
548 * @param string $msg complete text of message to display
549 * @param string $section The section to add the header to
551 * @return HTMLForm $this for chaining calls (since 1.20)
553 function addHeaderText( $msg, $section = null ) {
554 if ( is_null( $section ) ) {
555 $this->mHeader
.= $msg;
557 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
558 $this->mSectionHeaders
[$section] = '';
560 $this->mSectionHeaders
[$section] .= $msg;
567 * Set header text, inside the form.
570 * @param string $msg complete text of message to display
571 * @param $section The section to add the header to
573 * @return HTMLForm $this for chaining calls (since 1.20)
575 function setHeaderText( $msg, $section = null ) {
576 if ( is_null( $section ) ) {
577 $this->mHeader
= $msg;
579 $this->mSectionHeaders
[$section] = $msg;
586 * Add footer text, inside the form.
588 * @param string $msg complete text of message to display
589 * @param string $section The section to add the footer text to
591 * @return HTMLForm $this for chaining calls (since 1.20)
593 function addFooterText( $msg, $section = null ) {
594 if ( is_null( $section ) ) {
595 $this->mFooter
.= $msg;
597 if ( !isset( $this->mSectionFooters
[$section] ) ) {
598 $this->mSectionFooters
[$section] = '';
600 $this->mSectionFooters
[$section] .= $msg;
607 * Set footer text, inside the form.
610 * @param string $msg complete text of message to display
611 * @param string $section The section to add the footer text to
613 * @return HTMLForm $this for chaining calls (since 1.20)
615 function setFooterText( $msg, $section = null ) {
616 if ( is_null( $section ) ) {
617 $this->mFooter
= $msg;
619 $this->mSectionFooters
[$section] = $msg;
626 * Add text to the end of the display.
628 * @param string $msg complete text of message to display
630 * @return HTMLForm $this for chaining calls (since 1.20)
632 function addPostText( $msg ) {
633 $this->mPost
.= $msg;
639 * Set text at the end of the display.
641 * @param string $msg complete text of message to display
643 * @return HTMLForm $this for chaining calls (since 1.20)
645 function setPostText( $msg ) {
652 * Add a hidden field to the output
654 * @param string $name field name. This will be used exactly as entered
655 * @param string $value field value
656 * @param $attribs Array
658 * @return HTMLForm $this for chaining calls (since 1.20)
660 public function addHiddenField( $name, $value, $attribs = array() ) {
661 $attribs +
= array( 'name' => $name );
662 $this->mHiddenFields
[] = array( $value, $attribs );
668 * Add an array of hidden fields to the output
672 * @param array $fields Associative array of fields to add;
673 * mapping names to their values
675 * @return HTMLForm $this for chaining calls
677 public function addHiddenFields( array $fields ) {
678 foreach ( $fields as $name => $value ) {
679 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
686 * Add a button to the form
688 * @param string $name field name.
689 * @param string $value field value
690 * @param string $id DOM id for the button (default: null)
691 * @param $attribs Array
693 * @return HTMLForm $this for chaining calls (since 1.20)
695 public function addButton( $name, $value, $id = null, $attribs = null ) {
696 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
702 * Display the form (sending to the context's OutputPage object), with an
703 * appropriate error message or stack of messages, and any validation errors, etc.
705 * @attention You should call prepareForm() before calling this function.
706 * Moreover, when doing method chaining this should be the very last method
707 * call just after prepareForm().
709 * @param $submitResult Mixed output from HTMLForm::trySubmit()
711 * @return Nothing, should be last call
713 function displayForm( $submitResult ) {
714 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
718 * Returns the raw HTML generated by the form
720 * @param $submitResult Mixed output from HTMLForm::trySubmit()
724 function getHTML( $submitResult ) {
725 # For good measure (it is the default)
726 $this->getOutput()->preventClickjacking();
727 $this->getOutput()->addModules( 'mediawiki.htmlform' );
728 if ( $this->isVForm() ) {
729 $this->getOutput()->addModuleStyles( array(
731 'mediawiki.ui.button',
733 // @todo Should vertical form set setWrapperLegend( false )
734 // to hide ugly fieldsets?
738 . $this->getErrors( $submitResult )
741 . $this->getHiddenFields()
742 . $this->getButtons()
745 $html = $this->wrapForm( $html );
747 return '' . $this->mPre
. $html . $this->mPost
;
751 * Wrap the form innards in an actual "<form>" element
753 * @param string $html HTML contents to wrap.
755 * @return String wrapped HTML.
757 function wrapForm( $html ) {
759 # Include a <fieldset> wrapper for style, if requested.
760 if ( $this->mWrapperLegend
!== false ) {
761 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
763 # Use multipart/form-data
764 $encType = $this->mUseMultipart
765 ?
'multipart/form-data'
766 : 'application/x-www-form-urlencoded';
769 'action' => $this->getAction(),
770 'method' => $this->getMethod(),
771 'class' => array( 'visualClear' ),
772 'enctype' => $encType,
774 if ( !empty( $this->mId
) ) {
775 $attribs['id'] = $this->mId
;
778 if ( $this->isVForm() ) {
779 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
782 return Html
::rawElement( 'form', $attribs, $html );
786 * Get the hidden fields that should go inside the form.
787 * @return String HTML.
789 function getHiddenFields() {
790 global $wgArticlePath;
793 if ( $this->getMethod() == 'post' ) {
794 $html .= Html
::hidden(
796 $this->getUser()->getEditToken(),
797 array( 'id' => 'wpEditToken' )
799 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
802 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
803 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
806 foreach ( $this->mHiddenFields
as $data ) {
807 list( $value, $attribs ) = $data;
808 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
815 * Get the submit and (potentially) reset buttons.
816 * @return String HTML.
818 function getButtons() {
821 if ( $this->mShowSubmit
) {
824 if ( isset( $this->mSubmitID
) ) {
825 $attribs['id'] = $this->mSubmitID
;
828 if ( isset( $this->mSubmitName
) ) {
829 $attribs['name'] = $this->mSubmitName
;
832 if ( isset( $this->mSubmitTooltip
) ) {
833 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
836 $attribs['class'] = array( 'mw-htmlform-submit' );
838 if ( $this->isVForm() ) {
839 // mw-ui-block is necessary because the buttons aren't necessarily in an
840 // immediate child div of the vform.
841 // @todo Let client specify if the primary submit button is progressive or destructive
846 'mw-ui-constructive',
851 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
854 if ( $this->mShowReset
) {
855 $buttons .= Html
::element(
859 'value' => $this->msg( 'htmlform-reset' )->text()
864 foreach ( $this->mButtons
as $button ) {
867 'name' => $button['name'],
868 'value' => $button['value']
871 if ( $button['attribs'] ) {
872 $attrs +
= $button['attribs'];
875 if ( isset( $button['id'] ) ) {
876 $attrs['id'] = $button['id'];
879 $buttons .= Html
::element( 'input', $attrs ) . "\n";
882 $html = Html
::rawElement( 'span',
883 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
885 // Buttons are top-level form elements in table and div layouts,
886 // but vform wants all elements inside divs to get spaced-out block
888 if ( $this->mShowSubmit
&& $this->isVForm() ) {
889 $html = Html
::rawElement( 'div', null, "\n$html" ) . "\n";
896 * Get the whole body of the form.
900 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
904 * Format and display an error message stack.
906 * @param $errors String|Array|Status
910 function getErrors( $errors ) {
911 if ( $errors instanceof Status
) {
912 if ( $errors->isOK() ) {
915 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
917 } elseif ( is_array( $errors ) ) {
918 $errorstr = $this->formatErrors( $errors );
924 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
929 * Format a stack of error messages into a single HTML string
931 * @param array $errors of message keys/values
933 * @return String HTML, a "<ul>" list of errors
935 public static function formatErrors( $errors ) {
938 foreach ( $errors as $error ) {
939 if ( is_array( $error ) ) {
940 $msg = array_shift( $error );
946 $errorstr .= Html
::rawElement(
949 wfMessage( $msg, $error )->parse()
953 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
959 * Set the text for the submit button
961 * @param string $t plaintext.
963 * @return HTMLForm $this for chaining calls (since 1.20)
965 function setSubmitText( $t ) {
966 $this->mSubmitText
= $t;
972 * Set the text for the submit button to a message
975 * @param string $msg message key
977 * @return HTMLForm $this for chaining calls (since 1.20)
979 public function setSubmitTextMsg( $msg ) {
980 $this->setSubmitText( $this->msg( $msg )->text() );
986 * Get the text for the submit button, either customised or a default.
989 function getSubmitText() {
990 return $this->mSubmitText
992 : $this->msg( 'htmlform-submit' )->text();
996 * @param string $name Submit button name
998 * @return HTMLForm $this for chaining calls (since 1.20)
1000 public function setSubmitName( $name ) {
1001 $this->mSubmitName
= $name;
1007 * @param string $name Tooltip for the submit button
1009 * @return HTMLForm $this for chaining calls (since 1.20)
1011 public function setSubmitTooltip( $name ) {
1012 $this->mSubmitTooltip
= $name;
1018 * Set the id for the submit button.
1022 * @todo FIXME: Integrity of $t is *not* validated
1023 * @return HTMLForm $this for chaining calls (since 1.20)
1025 function setSubmitID( $t ) {
1026 $this->mSubmitID
= $t;
1032 * Stop a default submit button being shown for this form. This implies that an
1033 * alternate submit method must be provided manually.
1037 * @param bool $suppressSubmit Set to false to re-enable the button again
1039 * @return HTMLForm $this for chaining calls
1041 function suppressDefaultSubmit( $suppressSubmit = true ) {
1042 $this->mShowSubmit
= !$suppressSubmit;
1048 * Set the id of the \<table\> or outermost \<div\> element.
1052 * @param string $id new value of the id attribute, or "" to remove
1054 * @return HTMLForm $this for chaining calls
1056 public function setTableId( $id ) {
1057 $this->mTableId
= $id;
1063 * @param string $id DOM id for the form
1065 * @return HTMLForm $this for chaining calls (since 1.20)
1067 public function setId( $id ) {
1074 * Prompt the whole form to be wrapped in a "<fieldset>", with
1075 * this text as its "<legend>" element.
1077 * @param string|false $legend HTML to go inside the "<legend>" element, or
1078 * false for no <legend>
1081 * @return HTMLForm $this for chaining calls (since 1.20)
1083 public function setWrapperLegend( $legend ) {
1084 $this->mWrapperLegend
= $legend;
1090 * Prompt the whole form to be wrapped in a "<fieldset>", with
1091 * this message as its "<legend>" element.
1094 * @param string $msg message key
1096 * @return HTMLForm $this for chaining calls (since 1.20)
1098 public function setWrapperLegendMsg( $msg ) {
1099 $this->setWrapperLegend( $this->msg( $msg )->text() );
1105 * Set the prefix for various default messages
1106 * @todo Currently only used for the "<fieldset>" legend on forms
1107 * with multiple sections; should be used elsewhere?
1111 * @return HTMLForm $this for chaining calls (since 1.20)
1113 function setMessagePrefix( $p ) {
1114 $this->mMessagePrefix
= $p;
1120 * Set the title for form submission
1122 * @param $t Title of page the form is on/should be posted to
1124 * @return HTMLForm $this for chaining calls (since 1.20)
1126 function setTitle( $t ) {
1136 function getTitle() {
1137 return $this->mTitle
=== false
1138 ?
$this->getContext()->getTitle()
1143 * Set the method used to submit the form
1145 * @param $method String
1147 * @return HTMLForm $this for chaining calls (since 1.20)
1149 public function setMethod( $method = 'post' ) {
1150 $this->mMethod
= $method;
1155 public function getMethod() {
1156 return $this->mMethod
;
1162 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1164 * @param string $sectionName ID attribute of the "<table>" tag for this
1165 * section, ignored if empty.
1166 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1167 * each subsection, ignored if empty.
1168 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields.
1172 public function displaySection( $fields,
1174 $fieldsetIDPrefix = '',
1175 &$hasUserVisibleFields = false ) {
1176 $displayFormat = $this->getDisplayFormat();
1179 $subsectionHtml = '';
1182 switch ( $displayFormat ) {
1184 $getFieldHtmlMethod = 'getTableRow';
1187 // Close enough to a div.
1188 $getFieldHtmlMethod = 'getDiv';
1191 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1194 foreach ( $fields as $key => $value ) {
1195 if ( $value instanceof HTMLFormField
) {
1196 $v = empty( $value->mParams
['nodata'] )
1197 ?
$this->mFieldData
[$key]
1198 : $value->getDefault();
1199 $html .= $value->$getFieldHtmlMethod( $v );
1201 $labelValue = trim( $value->getLabel() );
1202 if ( $labelValue != ' ' && $labelValue !== '' ) {
1206 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1207 get_class( $value ) !== 'HTMLApiField'
1209 $hasUserVisibleFields = true;
1211 } elseif ( is_array( $value ) ) {
1212 $subsectionHasVisibleFields = false;
1214 $this->displaySection( $value,
1216 "$fieldsetIDPrefix$key-",
1217 $subsectionHasVisibleFields );
1220 if ( $subsectionHasVisibleFields === true ) {
1221 // Display the section with various niceties.
1222 $hasUserVisibleFields = true;
1224 $legend = $this->getLegend( $key );
1226 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1227 $section = $this->mSectionHeaders
[$key] . $section;
1229 if ( isset( $this->mSectionFooters
[$key] ) ) {
1230 $section .= $this->mSectionFooters
[$key];
1233 $attributes = array();
1234 if ( $fieldsetIDPrefix ) {
1235 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1237 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1239 // Just return the inputs, nothing fancy.
1240 $subsectionHtml .= $section;
1245 if ( $displayFormat !== 'raw' ) {
1248 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1249 $classes[] = 'mw-htmlform-nolabel';
1253 'class' => implode( ' ', $classes ),
1256 if ( $sectionName ) {
1257 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1260 if ( $displayFormat === 'table' ) {
1261 $html = Html
::rawElement( 'table',
1263 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1264 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1265 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1269 if ( $this->mSubSectionBeforeFields
) {
1270 return $subsectionHtml . "\n" . $html;
1272 return $html . "\n" . $subsectionHtml;
1277 * Construct the form fields from the Descriptor array
1279 function loadData() {
1280 $fieldData = array();
1282 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1283 if ( !empty( $field->mParams
['nodata'] ) ) {
1285 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1286 $fieldData[$fieldname] = $field->getDefault();
1288 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1293 foreach ( $fieldData as $name => &$value ) {
1294 $field = $this->mFlatFields
[$name];
1295 $value = $field->filter( $value, $this->mFlatFields
);
1298 $this->mFieldData
= $fieldData;
1302 * Stop a reset button being shown for this form
1304 * @param bool $suppressReset set to false to re-enable the
1307 * @return HTMLForm $this for chaining calls (since 1.20)
1309 function suppressReset( $suppressReset = true ) {
1310 $this->mShowReset
= !$suppressReset;
1316 * Overload this if you want to apply special filtration routines
1317 * to the form as a whole, after it's submitted but before it's
1324 function filterDataForSubmit( $data ) {
1329 * Get a string to go in the "<legend>" of a section fieldset.
1330 * Override this if you want something more complicated.
1332 * @param $key String
1336 public function getLegend( $key ) {
1337 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1341 * Set the value for the action attribute of the form.
1342 * When set to false (which is the default state), the set title is used.
1346 * @param string|bool $action
1348 * @return HTMLForm $this for chaining calls (since 1.20)
1350 public function setAction( $action ) {
1351 $this->mAction
= $action;
1357 * Get the value for the action attribute of the form.
1363 public function getAction() {
1364 global $wgScript, $wgArticlePath;
1366 // If an action is alredy provided, return it
1367 if ( $this->mAction
!== false ) {
1368 return $this->mAction
;
1371 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1372 // meaning that getLocalURL() would return something like "index.php?title=...".
1373 // As browser remove the query string before submitting GET forms,
1374 // it means that the title would be lost. In such case use $wgScript instead
1375 // and put title in an hidden field (see getHiddenFields()).
1376 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1380 return $this->getTitle()->getLocalURL();