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 * '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 range, but
122 // we don't use those at the moment, so no point in adding all of them.
123 'email' => 'HTMLTextField',
124 'password' => 'HTMLTextField',
125 'url' => 'HTMLTextField',
130 protected $mMessagePrefix;
132 /** @var HTMLFormField[] */
133 protected $mFlatFields;
135 protected $mFieldTree;
136 protected $mShowReset = false;
137 protected $mShowSubmit = true;
139 protected $mSubmitCallback;
140 protected $mValidationErrorMessage;
142 protected $mPre = '';
143 protected $mHeader = '';
144 protected $mFooter = '';
145 protected $mSectionHeaders = array();
146 protected $mSectionFooters = array();
147 protected $mPost = '';
149 protected $mTableId = '';
151 protected $mSubmitID;
152 protected $mSubmitName;
153 protected $mSubmitText;
154 protected $mSubmitTooltip;
157 protected $mMethod = 'post';
160 * Form action URL. false means we will use the URL to set Title
164 protected $mAction = false;
166 protected $mUseMultipart = false;
167 protected $mHiddenFields = array();
168 protected $mButtons = array();
170 protected $mWrapperLegend = false;
173 * If true, sections that contain both fields and subsections will
174 * render their subsections before their fields.
176 * Subclasses may set this to false to render subsections after fields
179 protected $mSubSectionBeforeFields = true;
182 * Format in which to display form. For viable options,
183 * @see $availableDisplayFormats
186 protected $displayFormat = 'table';
189 * Available formats in which to display the form
192 protected $availableDisplayFormats = array(
200 * Build a new HTMLForm from an array of field attributes
202 * @param array $descriptor Array of Field constructs, as described above
203 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
204 * Obviates the need to call $form->setTitle()
205 * @param string $messagePrefix A prefix to go in front of default messages
207 public function __construct( $descriptor, /*IContextSource*/ $context = null,
210 if ( $context instanceof IContextSource
) {
211 $this->setContext( $context );
212 $this->mTitle
= false; // We don't need them to set a title
213 $this->mMessagePrefix
= $messagePrefix;
214 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
215 $this->mMessagePrefix
= $messagePrefix;
216 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
218 // it's actually $messagePrefix
219 $this->mMessagePrefix
= $context;
222 // Expand out into a tree.
223 $loadedDescriptor = array();
224 $this->mFlatFields
= array();
226 foreach ( $descriptor as $fieldname => $info ) {
227 $section = isset( $info['section'] )
231 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
232 $this->mUseMultipart
= true;
235 $field = self
::loadInputFromParameters( $fieldname, $info );
236 // FIXME During field's construct, the parent form isn't available!
237 // could add a 'parent' name-value to $info, could add a third parameter.
238 $field->mParent
= $this;
240 // vform gets too much space if empty labels generate HTML.
241 if ( $this->isVForm() ) {
242 $field->setShowEmptyLabel( false );
245 $setSection =& $loadedDescriptor;
247 $sectionParts = explode( '/', $section );
249 while ( count( $sectionParts ) ) {
250 $newName = array_shift( $sectionParts );
252 if ( !isset( $setSection[$newName] ) ) {
253 $setSection[$newName] = array();
256 $setSection =& $setSection[$newName];
260 $setSection[$fieldname] = $field;
261 $this->mFlatFields
[$fieldname] = $field;
264 $this->mFieldTree
= $loadedDescriptor;
268 * Set format in which to display the form
270 * @param string $format The name of the format to use, must be one of
271 * $this->availableDisplayFormats
273 * @throws MWException
275 * @return HTMLForm $this for chaining calls (since 1.20)
277 public function setDisplayFormat( $format ) {
278 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
279 throw new MWException( 'Display format must be one of ' .
280 print_r( $this->availableDisplayFormats
, true ) );
282 $this->displayFormat
= $format;
288 * Getter for displayFormat
292 public function getDisplayFormat() {
293 return $this->displayFormat
;
297 * Test if displayFormat is 'vform'
301 public function isVForm() {
302 return $this->displayFormat
=== 'vform';
306 * Add the HTMLForm-specific JavaScript, if it hasn't been
308 * @deprecated since 1.18 load modules with ResourceLoader instead
310 static function addJS() {
311 wfDeprecated( __METHOD__
, '1.18' );
315 * Get the HTMLFormField subclass for this descriptor.
317 * The descriptor can be passed either 'class' which is the name of
318 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
319 * This makes sure the 'class' is always set, and also is returned by
320 * this function for ease.
324 * @param string $fieldname Name of the field
325 * @param array $descriptor Input Descriptor, as described above
327 * @throws MWException
328 * @return string Name of a HTMLFormField subclass
330 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
331 if ( isset( $descriptor['class'] ) ) {
332 $class = $descriptor['class'];
333 } elseif ( isset( $descriptor['type'] ) ) {
334 $class = self
::$typeMappings[$descriptor['type']];
335 $descriptor['class'] = $class;
341 throw new MWException( "Descriptor with no class for $fieldname: "
342 . print_r( $descriptor, true ) );
349 * Initialise a new Object for the field
351 * @param string $fieldname Name of the field
352 * @param array $descriptor Input Descriptor, as described above
354 * @throws MWException
355 * @return HTMLFormField subclass
357 public static function loadInputFromParameters( $fieldname, $descriptor ) {
358 $class = self
::getClassFromDescriptor( $fieldname, $descriptor );
360 $descriptor['fieldname'] = $fieldname;
362 # @todo This will throw a fatal error whenever someone try to use
363 # 'class' to feed a CSS class instead of 'cssclass'. Would be
364 # great to avoid the fatal error and show a nice error.
365 $obj = new $class( $descriptor );
371 * Prepare form for submission.
373 * @attention When doing method chaining, that should be the very last
374 * method call before displayForm().
376 * @throws MWException
377 * @return HTMLForm $this for chaining calls (since 1.20)
379 function prepareForm() {
380 # Check if we have the info we need
381 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
382 throw new MWException( "You must call setTitle() on an HTMLForm" );
385 # Load data from the request.
392 * Try submitting, with edit token check first
393 * @return Status|bool
395 function tryAuthorizedSubmit() {
399 if ( $this->getMethod() != 'post' ) {
400 $submit = true; // no session check needed
401 } elseif ( $this->getRequest()->wasPosted() ) {
402 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
403 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
404 // Session tokens for logged-out users have no security value.
405 // However, if the user gave one, check it in order to give a nice
406 // "session expired" error instead of "permission denied" or such.
407 $submit = $this->getUser()->matchEditToken( $editToken );
414 $result = $this->trySubmit();
421 * The here's-one-I-made-earlier option: do the submission if
422 * posted, or display the form with or without funky validation
424 * @return bool|Status Whether submission was successful.
427 $this->prepareForm();
429 $result = $this->tryAuthorizedSubmit();
430 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
434 $this->displayForm( $result );
440 * Validate all the fields, and call the submission callback
441 * function if everything is kosher.
442 * @throws MWException
443 * @return mixed Bool true == Successful submission, Bool false
444 * == No submission attempted, anything else == Error to
447 function trySubmit() {
448 # Check for validation
449 foreach ( $this->mFlatFields
as $fieldname => $field ) {
450 if ( !empty( $field->mParams
['nodata'] ) ) {
453 if ( $field->validate(
454 $this->mFieldData
[$fieldname],
458 return isset( $this->mValidationErrorMessage
)
459 ?
$this->mValidationErrorMessage
460 : array( 'htmlform-invalid-input' );
464 $callback = $this->mSubmitCallback
;
465 if ( !is_callable( $callback ) ) {
466 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
467 'setSubmitCallback() to set one.' );
470 $data = $this->filterDataForSubmit( $this->mFieldData
);
472 $res = call_user_func( $callback, $data, $this );
478 * Set a callback to a function to do something with the form
479 * once it's been successfully validated.
481 * @param string $cb Function name. The function will be passed
482 * the output from HTMLForm::filterDataForSubmit, and must
483 * return Bool true on success, Bool false if no submission
484 * was attempted, or String HTML output to display on error.
486 * @return HTMLForm $this for chaining calls (since 1.20)
488 function setSubmitCallback( $cb ) {
489 $this->mSubmitCallback
= $cb;
495 * Set a message to display on a validation error.
497 * @param string|array $msg String or Array of valid inputs to wfMessage()
498 * (so each entry can be either a String or Array)
500 * @return HTMLForm $this for chaining calls (since 1.20)
502 function setValidationErrorMessage( $msg ) {
503 $this->mValidationErrorMessage
= $msg;
509 * Set the introductory message, overwriting any existing message.
511 * @param string $msg Complete text of message to display
513 * @return HTMLForm $this for chaining calls (since 1.20)
515 function setIntro( $msg ) {
516 $this->setPreText( $msg );
522 * Set the introductory message, overwriting any existing message.
525 * @param string $msg Complete text of message to display
527 * @return HTMLForm $this for chaining calls (since 1.20)
529 function setPreText( $msg ) {
536 * Add introductory text.
538 * @param string $msg Complete text of message to display
540 * @return HTMLForm $this for chaining calls (since 1.20)
542 function addPreText( $msg ) {
549 * Add header text, inside the form.
551 * @param string $msg Complete text of message to display
552 * @param string $section The section to add the header to
554 * @return HTMLForm $this for chaining calls (since 1.20)
556 function addHeaderText( $msg, $section = null ) {
557 if ( is_null( $section ) ) {
558 $this->mHeader
.= $msg;
560 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
561 $this->mSectionHeaders
[$section] = '';
563 $this->mSectionHeaders
[$section] .= $msg;
570 * Set header text, inside the form.
573 * @param string $msg Complete text of message to display
574 * @param string $section The section to add the header to
576 * @return HTMLForm $this for chaining calls (since 1.20)
578 function setHeaderText( $msg, $section = null ) {
579 if ( is_null( $section ) ) {
580 $this->mHeader
= $msg;
582 $this->mSectionHeaders
[$section] = $msg;
589 * Add footer text, inside the form.
591 * @param string $msg complete text of message to display
592 * @param string $section The section to add the footer text to
594 * @return HTMLForm $this for chaining calls (since 1.20)
596 function addFooterText( $msg, $section = null ) {
597 if ( is_null( $section ) ) {
598 $this->mFooter
.= $msg;
600 if ( !isset( $this->mSectionFooters
[$section] ) ) {
601 $this->mSectionFooters
[$section] = '';
603 $this->mSectionFooters
[$section] .= $msg;
610 * Set footer text, inside the form.
613 * @param string $msg Complete text of message to display
614 * @param string $section The section to add the footer text to
616 * @return HTMLForm $this for chaining calls (since 1.20)
618 function setFooterText( $msg, $section = null ) {
619 if ( is_null( $section ) ) {
620 $this->mFooter
= $msg;
622 $this->mSectionFooters
[$section] = $msg;
629 * Add text to the end of the display.
631 * @param string $msg Complete text of message to display
633 * @return HTMLForm $this for chaining calls (since 1.20)
635 function addPostText( $msg ) {
636 $this->mPost
.= $msg;
642 * Set text at the end of the display.
644 * @param string $msg Complete text of message to display
646 * @return HTMLForm $this for chaining calls (since 1.20)
648 function setPostText( $msg ) {
655 * Add a hidden field to the output
657 * @param string $name Field name. This will be used exactly as entered
658 * @param string $value Field value
659 * @param array $attribs
661 * @return HTMLForm $this for chaining calls (since 1.20)
663 public function addHiddenField( $name, $value, $attribs = array() ) {
664 $attribs +
= array( 'name' => $name );
665 $this->mHiddenFields
[] = array( $value, $attribs );
671 * Add an array of hidden fields to the output
675 * @param array $fields Associative array of fields to add;
676 * mapping names to their values
678 * @return HTMLForm $this for chaining calls
680 public function addHiddenFields( array $fields ) {
681 foreach ( $fields as $name => $value ) {
682 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
689 * Add a button to the form
691 * @param string $name Field name.
692 * @param string $value Field value
693 * @param string $id DOM id for the button (default: null)
694 * @param array $attribs
696 * @return HTMLForm $this for chaining calls (since 1.20)
698 public function addButton( $name, $value, $id = null, $attribs = null ) {
699 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
705 * Display the form (sending to the context's OutputPage object), with an
706 * appropriate error message or stack of messages, and any validation errors, etc.
708 * @attention You should call prepareForm() before calling this function.
709 * Moreover, when doing method chaining this should be the very last method
710 * call just after prepareForm().
712 * @param mixed $submitResult Mixed output from HTMLForm::trySubmit()
714 * @return Nothing, should be last call
716 function displayForm( $submitResult ) {
717 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
721 * Returns the raw HTML generated by the form
723 * @param mixed $submitResult Mixed output from HTMLForm::trySubmit()
727 function getHTML( $submitResult ) {
728 # For good measure (it is the default)
729 $this->getOutput()->preventClickjacking();
730 $this->getOutput()->addModules( 'mediawiki.htmlform' );
731 if ( $this->isVForm() ) {
732 $this->getOutput()->addModuleStyles( array(
734 'mediawiki.ui.button',
736 // @todo Should vertical form set setWrapperLegend( false )
737 // to hide ugly fieldsets?
741 . $this->getErrors( $submitResult )
744 . $this->getHiddenFields()
745 . $this->getButtons()
748 $html = $this->wrapForm( $html );
750 return '' . $this->mPre
. $html . $this->mPost
;
754 * Wrap the form innards in an actual "<form>" element
756 * @param string $html HTML contents to wrap.
758 * @return string Wrapped HTML.
760 function wrapForm( $html ) {
762 # Include a <fieldset> wrapper for style, if requested.
763 if ( $this->mWrapperLegend
!== false ) {
764 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
766 # Use multipart/form-data
767 $encType = $this->mUseMultipart
768 ?
'multipart/form-data'
769 : 'application/x-www-form-urlencoded';
772 'action' => $this->getAction(),
773 'method' => $this->getMethod(),
774 'class' => array( 'visualClear' ),
775 'enctype' => $encType,
777 if ( !empty( $this->mId
) ) {
778 $attribs['id'] = $this->mId
;
781 if ( $this->isVForm() ) {
782 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
785 return Html
::rawElement( 'form', $attribs, $html );
789 * Get the hidden fields that should go inside the form.
790 * @return string HTML.
792 function getHiddenFields() {
793 global $wgArticlePath;
796 if ( $this->getMethod() == 'post' ) {
797 $html .= Html
::hidden(
799 $this->getUser()->getEditToken(),
800 array( 'id' => 'wpEditToken' )
802 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
805 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
806 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
809 foreach ( $this->mHiddenFields
as $data ) {
810 list( $value, $attribs ) = $data;
811 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
818 * Get the submit and (potentially) reset buttons.
819 * @return string HTML.
821 function getButtons() {
824 if ( $this->mShowSubmit
) {
827 if ( isset( $this->mSubmitID
) ) {
828 $attribs['id'] = $this->mSubmitID
;
831 if ( isset( $this->mSubmitName
) ) {
832 $attribs['name'] = $this->mSubmitName
;
835 if ( isset( $this->mSubmitTooltip
) ) {
836 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
839 $attribs['class'] = array( 'mw-htmlform-submit' );
841 if ( $this->isVForm() ) {
842 // mw-ui-block is necessary because the buttons aren't necessarily in an
843 // immediate child div of the vform.
844 // @todo Let client specify if the primary submit button is progressive or destructive
849 'mw-ui-constructive',
854 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
857 if ( $this->mShowReset
) {
858 $buttons .= Html
::element(
862 'value' => $this->msg( 'htmlform-reset' )->text()
867 foreach ( $this->mButtons
as $button ) {
870 'name' => $button['name'],
871 'value' => $button['value']
874 if ( $button['attribs'] ) {
875 $attrs +
= $button['attribs'];
878 if ( isset( $button['id'] ) ) {
879 $attrs['id'] = $button['id'];
882 $buttons .= Html
::element( 'input', $attrs ) . "\n";
885 $html = Html
::rawElement( 'span',
886 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
888 // Buttons are top-level form elements in table and div layouts,
889 // but vform wants all elements inside divs to get spaced-out block
891 if ( $this->mShowSubmit
&& $this->isVForm() ) {
892 $html = Html
::rawElement( 'div', null, "\n$html" ) . "\n";
899 * Get the whole body of the form.
903 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
907 * Format and display an error message stack.
909 * @param string|array|Status $errors
913 function getErrors( $errors ) {
914 if ( $errors instanceof Status
) {
915 if ( $errors->isOK() ) {
918 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
920 } elseif ( is_array( $errors ) ) {
921 $errorstr = $this->formatErrors( $errors );
927 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
932 * Format a stack of error messages into a single HTML string
934 * @param array $errors of message keys/values
936 * @return string HTML, a "<ul>" list of errors
938 public static function formatErrors( $errors ) {
941 foreach ( $errors as $error ) {
942 if ( is_array( $error ) ) {
943 $msg = array_shift( $error );
949 $errorstr .= Html
::rawElement(
952 wfMessage( $msg, $error )->parse()
956 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
962 * Set the text for the submit button
964 * @param string $t plaintext.
966 * @return HTMLForm $this for chaining calls (since 1.20)
968 function setSubmitText( $t ) {
969 $this->mSubmitText
= $t;
975 * Set the text for the submit button to a message
978 * @param string $msg Message key
980 * @return HTMLForm $this for chaining calls (since 1.20)
982 public function setSubmitTextMsg( $msg ) {
983 $this->setSubmitText( $this->msg( $msg )->text() );
989 * Get the text for the submit button, either customised or a default.
992 function getSubmitText() {
993 return $this->mSubmitText
995 : $this->msg( 'htmlform-submit' )->text();
999 * @param string $name Submit button name
1001 * @return HTMLForm $this for chaining calls (since 1.20)
1003 public function setSubmitName( $name ) {
1004 $this->mSubmitName
= $name;
1010 * @param string $name Tooltip for the submit button
1012 * @return HTMLForm $this for chaining calls (since 1.20)
1014 public function setSubmitTooltip( $name ) {
1015 $this->mSubmitTooltip
= $name;
1021 * Set the id for the submit button.
1025 * @todo FIXME: Integrity of $t is *not* validated
1026 * @return HTMLForm $this for chaining calls (since 1.20)
1028 function setSubmitID( $t ) {
1029 $this->mSubmitID
= $t;
1035 * Stop a default submit button being shown for this form. This implies that an
1036 * alternate submit method must be provided manually.
1040 * @param bool $suppressSubmit Set to false to re-enable the button again
1042 * @return HTMLForm $this for chaining calls
1044 function suppressDefaultSubmit( $suppressSubmit = true ) {
1045 $this->mShowSubmit
= !$suppressSubmit;
1051 * Set the id of the \<table\> or outermost \<div\> element.
1055 * @param string $id New value of the id attribute, or "" to remove
1057 * @return HTMLForm $this for chaining calls
1059 public function setTableId( $id ) {
1060 $this->mTableId
= $id;
1066 * @param string $id DOM id for the form
1068 * @return HTMLForm $this for chaining calls (since 1.20)
1070 public function setId( $id ) {
1077 * Prompt the whole form to be wrapped in a "<fieldset>", with
1078 * this text as its "<legend>" element.
1080 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1081 * false for no <legend>
1084 * @return HTMLForm $this for chaining calls (since 1.20)
1086 public function setWrapperLegend( $legend ) {
1087 $this->mWrapperLegend
= $legend;
1093 * Prompt the whole form to be wrapped in a "<fieldset>", with
1094 * this message as its "<legend>" element.
1097 * @param string $msg Message key
1099 * @return HTMLForm $this for chaining calls (since 1.20)
1101 public function setWrapperLegendMsg( $msg ) {
1102 $this->setWrapperLegend( $this->msg( $msg )->text() );
1108 * Set the prefix for various default messages
1109 * @todo Currently only used for the "<fieldset>" legend on forms
1110 * with multiple sections; should be used elsewhere?
1114 * @return HTMLForm $this for chaining calls (since 1.20)
1116 function setMessagePrefix( $p ) {
1117 $this->mMessagePrefix
= $p;
1123 * Set the title for form submission
1125 * @param Title $t Title of page the form is on/should be posted to
1127 * @return HTMLForm $this for chaining calls (since 1.20)
1129 function setTitle( $t ) {
1139 function getTitle() {
1140 return $this->mTitle
=== false
1141 ?
$this->getContext()->getTitle()
1146 * Set the method used to submit the form
1148 * @param string $method
1150 * @return HTMLForm $this for chaining calls (since 1.20)
1152 public function setMethod( $method = 'post' ) {
1153 $this->mMethod
= $method;
1158 public function getMethod() {
1159 return $this->mMethod
;
1165 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1167 * @param string $sectionName ID attribute of the "<table>" tag for this
1168 * section, ignored if empty.
1169 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1170 * each subsection, ignored if empty.
1171 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1175 public function displaySection( $fields,
1177 $fieldsetIDPrefix = '',
1178 &$hasUserVisibleFields = false ) {
1179 $displayFormat = $this->getDisplayFormat();
1182 $subsectionHtml = '';
1185 switch ( $displayFormat ) {
1187 $getFieldHtmlMethod = 'getTableRow';
1190 // Close enough to a div.
1191 $getFieldHtmlMethod = 'getDiv';
1194 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1197 foreach ( $fields as $key => $value ) {
1198 if ( $value instanceof HTMLFormField
) {
1199 $v = empty( $value->mParams
['nodata'] )
1200 ?
$this->mFieldData
[$key]
1201 : $value->getDefault();
1202 $html .= $value->$getFieldHtmlMethod( $v );
1204 $labelValue = trim( $value->getLabel() );
1205 if ( $labelValue != ' ' && $labelValue !== '' ) {
1209 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1210 get_class( $value ) !== 'HTMLApiField'
1212 $hasUserVisibleFields = true;
1214 } elseif ( is_array( $value ) ) {
1215 $subsectionHasVisibleFields = false;
1217 $this->displaySection( $value,
1219 "$fieldsetIDPrefix$key-",
1220 $subsectionHasVisibleFields );
1223 if ( $subsectionHasVisibleFields === true ) {
1224 // Display the section with various niceties.
1225 $hasUserVisibleFields = true;
1227 $legend = $this->getLegend( $key );
1229 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1230 $section = $this->mSectionHeaders
[$key] . $section;
1232 if ( isset( $this->mSectionFooters
[$key] ) ) {
1233 $section .= $this->mSectionFooters
[$key];
1236 $attributes = array();
1237 if ( $fieldsetIDPrefix ) {
1238 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1240 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1242 // Just return the inputs, nothing fancy.
1243 $subsectionHtml .= $section;
1248 if ( $displayFormat !== 'raw' ) {
1251 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1252 $classes[] = 'mw-htmlform-nolabel';
1256 'class' => implode( ' ', $classes ),
1259 if ( $sectionName ) {
1260 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1263 if ( $displayFormat === 'table' ) {
1264 $html = Html
::rawElement( 'table',
1266 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1267 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1268 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1272 if ( $this->mSubSectionBeforeFields
) {
1273 return $subsectionHtml . "\n" . $html;
1275 return $html . "\n" . $subsectionHtml;
1280 * Construct the form fields from the Descriptor array
1282 function loadData() {
1283 $fieldData = array();
1285 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1286 if ( !empty( $field->mParams
['nodata'] ) ) {
1288 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1289 $fieldData[$fieldname] = $field->getDefault();
1291 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1296 foreach ( $fieldData as $name => &$value ) {
1297 $field = $this->mFlatFields
[$name];
1298 $value = $field->filter( $value, $this->mFlatFields
);
1301 $this->mFieldData
= $fieldData;
1305 * Stop a reset button being shown for this form
1307 * @param bool $suppressReset Set to false to re-enable the button again
1309 * @return HTMLForm $this for chaining calls (since 1.20)
1311 function suppressReset( $suppressReset = true ) {
1312 $this->mShowReset
= !$suppressReset;
1318 * Overload this if you want to apply special filtration routines
1319 * to the form as a whole, after it's submitted but before it's
1322 * @param array $data
1326 function filterDataForSubmit( $data ) {
1331 * Get a string to go in the "<legend>" of a section fieldset.
1332 * Override this if you want something more complicated.
1334 * @param string $key
1338 public function getLegend( $key ) {
1339 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1343 * Set the value for the action attribute of the form.
1344 * When set to false (which is the default state), the set title is used.
1348 * @param string|bool $action
1350 * @return HTMLForm $this for chaining calls (since 1.20)
1352 public function setAction( $action ) {
1353 $this->mAction
= $action;
1359 * Get the value for the action attribute of the form.
1365 public function getAction() {
1366 global $wgScript, $wgArticlePath;
1368 // If an action is alredy provided, return it
1369 if ( $this->mAction
!== false ) {
1370 return $this->mAction
;
1373 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1374 // meaning that getLocalURL() would return something like "index.php?title=...".
1375 // As browser remove the query string before submitting GET forms,
1376 // it means that the title would be lost. In such case use $wgScript instead
1377 // and put title in an hidden field (see getHiddenFields()).
1378 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1382 return $this->getTitle()->getLocalURL();