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' -- varies according to the specific object.
54 * 'label-message' -- message key for a message to use as the label.
55 * can be an array of msg key and then parameters to
57 * 'label' -- alternatively, a raw text message. Overridden by
59 * 'help' -- message text for a message to use as a help text.
60 * 'help-message' -- message key for a message to use as a help text.
61 * can be an array of msg key and then parameters to
63 * Overwrites 'help-messages' and 'help'.
64 * 'help-messages' -- array of message key. As above, each item can
65 * be an array of msg key and then parameters.
67 * 'required' -- passed through to the object, indicating that it
68 * is a required field.
69 * 'size' -- the length of text fields
70 * 'filter-callback -- a function name to give you the chance to
71 * massage the inputted value before it's processed.
72 * @see HTMLForm::filter()
73 * 'validation-callback' -- a function name to give you the chance
74 * to impose extra validation on the field input.
75 * @see HTMLForm::validate()
76 * 'name' -- By default, the 'name' attribute of the input field
77 * is "wp{$fieldname}". If you want a different name
78 * (eg one without the "wp" prefix), specify it here and
79 * it will be used without modification.
81 * Since 1.20, you can chain mutators to ease the form generation:
84 * $form = new HTMLForm( $someFields );
85 * $form->setMethod( 'get' )
86 * ->setWrapperLegendMsg( 'message-key' )
88 * ->displayForm( '' );
90 * Note that you will have prepareForm and displayForm at the end. Other
91 * methods call done after that would simply not be part of the form :(
93 * @todo Document 'section' / 'subsection' stuff
95 class HTMLForm
extends ContextSource
{
96 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
97 public static $typeMappings = array(
98 'api' => 'HTMLApiField',
99 'text' => 'HTMLTextField',
100 'textarea' => 'HTMLTextAreaField',
101 'select' => 'HTMLSelectField',
102 'radio' => 'HTMLRadioField',
103 'multiselect' => 'HTMLMultiSelectField',
104 'check' => 'HTMLCheckField',
105 'toggle' => 'HTMLCheckField',
106 'int' => 'HTMLIntField',
107 'float' => 'HTMLFloatField',
108 'info' => 'HTMLInfoField',
109 'selectorother' => 'HTMLSelectOrOtherField',
110 'selectandother' => 'HTMLSelectAndOtherField',
111 'submit' => 'HTMLSubmitField',
112 'hidden' => 'HTMLHiddenField',
113 'edittools' => 'HTMLEditTools',
114 'checkmatrix' => 'HTMLCheckMatrix',
115 // HTMLTextField will output the correct type="" attribute automagically.
116 // There are about four zillion other HTML5 input types, like url, but
117 // we don't use those at the moment, so no point in adding all of them.
118 'email' => 'HTMLTextField',
119 'password' => 'HTMLTextField',
124 protected $mMessagePrefix;
126 /** @var HTMLFormField[] */
127 protected $mFlatFields;
129 protected $mFieldTree;
130 protected $mShowReset = false;
131 protected $mShowSubmit = true;
133 protected $mSubmitCallback;
134 protected $mValidationErrorMessage;
136 protected $mPre = '';
137 protected $mHeader = '';
138 protected $mFooter = '';
139 protected $mSectionHeaders = array();
140 protected $mSectionFooters = array();
141 protected $mPost = '';
143 protected $mTableId = '';
145 protected $mSubmitID;
146 protected $mSubmitName;
147 protected $mSubmitText;
148 protected $mSubmitTooltip;
151 protected $mMethod = 'post';
154 * Form action URL. false means we will use the URL to set Title
158 protected $mAction = false;
160 protected $mUseMultipart = false;
161 protected $mHiddenFields = array();
162 protected $mButtons = array();
164 protected $mWrapperLegend = false;
167 * If true, sections that contain both fields and subsections will
168 * render their subsections before their fields.
170 * Subclasses may set this to false to render subsections after fields
173 protected $mSubSectionBeforeFields = true;
176 * Format in which to display form. For viable options,
177 * @see $availableDisplayFormats
180 protected $displayFormat = 'table';
183 * Available formats in which to display the form
186 protected $availableDisplayFormats = array(
194 * Build a new HTMLForm from an array of field attributes
196 * @param array $descriptor of Field constructs, as described above
197 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
198 * Obviates the need to call $form->setTitle()
199 * @param string $messagePrefix a prefix to go in front of default messages
201 public function __construct( $descriptor, /*IContextSource*/ $context = null,
204 if ( $context instanceof IContextSource
) {
205 $this->setContext( $context );
206 $this->mTitle
= false; // We don't need them to set a title
207 $this->mMessagePrefix
= $messagePrefix;
208 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
209 $this->mMessagePrefix
= $messagePrefix;
210 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
212 // it's actually $messagePrefix
213 $this->mMessagePrefix
= $context;
216 // Expand out into a tree.
217 $loadedDescriptor = array();
218 $this->mFlatFields
= array();
220 foreach ( $descriptor as $fieldname => $info ) {
221 $section = isset( $info['section'] )
225 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
226 $this->mUseMultipart
= true;
229 $field = self
::loadInputFromParameters( $fieldname, $info );
230 // FIXME During field's construct, the parent form isn't available!
231 // could add a 'parent' name-value to $info, could add a third parameter.
232 $field->mParent
= $this;
234 // vform gets too much space if empty labels generate HTML.
235 if ( $this->isVForm() ) {
236 $field->setShowEmptyLabel( false );
239 $setSection =& $loadedDescriptor;
241 $sectionParts = explode( '/', $section );
243 while ( count( $sectionParts ) ) {
244 $newName = array_shift( $sectionParts );
246 if ( !isset( $setSection[$newName] ) ) {
247 $setSection[$newName] = array();
250 $setSection =& $setSection[$newName];
254 $setSection[$fieldname] = $field;
255 $this->mFlatFields
[$fieldname] = $field;
258 $this->mFieldTree
= $loadedDescriptor;
262 * Set format in which to display the form
264 * @param string $format the name of the format to use, must be one of
265 * $this->availableDisplayFormats
267 * @throws MWException
269 * @return HTMLForm $this for chaining calls (since 1.20)
271 public function setDisplayFormat( $format ) {
272 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
273 throw new MWException( 'Display format must be one of ' .
274 print_r( $this->availableDisplayFormats
, true ) );
276 $this->displayFormat
= $format;
282 * Getter for displayFormat
286 public function getDisplayFormat() {
287 return $this->displayFormat
;
291 * Test if displayFormat is 'vform'
295 public function isVForm() {
296 return $this->displayFormat
=== 'vform';
300 * Add the HTMLForm-specific JavaScript, if it hasn't been
302 * @deprecated since 1.18 load modules with ResourceLoader instead
304 static function addJS() {
305 wfDeprecated( __METHOD__
, '1.18' );
309 * Initialise a new Object for the field
311 * @param $fieldname string
312 * @param string $descriptor input Descriptor, as described above
314 * @throws MWException
315 * @return HTMLFormField subclass
317 static function loadInputFromParameters( $fieldname, $descriptor ) {
318 if ( isset( $descriptor['class'] ) ) {
319 $class = $descriptor['class'];
320 } elseif ( isset( $descriptor['type'] ) ) {
321 $class = self
::$typeMappings[$descriptor['type']];
322 $descriptor['class'] = $class;
328 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
331 $descriptor['fieldname'] = $fieldname;
333 # @todo This will throw a fatal error whenever someone try to use
334 # 'class' to feed a CSS class instead of 'cssclass'. Would be
335 # great to avoid the fatal error and show a nice error.
336 $obj = new $class( $descriptor );
342 * Prepare form for submission.
344 * @attention When doing method chaining, that should be the very last
345 * method call before displayForm().
347 * @throws MWException
348 * @return HTMLForm $this for chaining calls (since 1.20)
350 function prepareForm() {
351 # Check if we have the info we need
352 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
353 throw new MWException( "You must call setTitle() on an HTMLForm" );
356 # Load data from the request.
363 * Try submitting, with edit token check first
364 * @return Status|boolean
366 function tryAuthorizedSubmit() {
370 if ( $this->getMethod() != 'post' ) {
371 $submit = true; // no session check needed
372 } elseif ( $this->getRequest()->wasPosted() ) {
373 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
374 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
375 // Session tokens for logged-out users have no security value.
376 // However, if the user gave one, check it in order to give a nice
377 // "session expired" error instead of "permission denied" or such.
378 $submit = $this->getUser()->matchEditToken( $editToken );
385 $result = $this->trySubmit();
392 * The here's-one-I-made-earlier option: do the submission if
393 * posted, or display the form with or without funky validation
395 * @return Bool or Status whether submission was successful.
398 $this->prepareForm();
400 $result = $this->tryAuthorizedSubmit();
401 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
405 $this->displayForm( $result );
411 * Validate all the fields, and call the submission callback
412 * function if everything is kosher.
413 * @throws MWException
414 * @return Mixed Bool true == Successful submission, Bool false
415 * == No submission attempted, anything else == Error to
418 function trySubmit() {
419 # Check for validation
420 foreach ( $this->mFlatFields
as $fieldname => $field ) {
421 if ( !empty( $field->mParams
['nodata'] ) ) {
424 if ( $field->validate(
425 $this->mFieldData
[$fieldname],
429 return isset( $this->mValidationErrorMessage
)
430 ?
$this->mValidationErrorMessage
431 : array( 'htmlform-invalid-input' );
435 $callback = $this->mSubmitCallback
;
436 if ( !is_callable( $callback ) ) {
437 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
438 'setSubmitCallback() to set one.' );
441 $data = $this->filterDataForSubmit( $this->mFieldData
);
443 $res = call_user_func( $callback, $data, $this );
449 * Set a callback to a function to do something with the form
450 * once it's been successfully validated.
452 * @param string $cb function name. The function will be passed
453 * the output from HTMLForm::filterDataForSubmit, and must
454 * return Bool true on success, Bool false if no submission
455 * was attempted, or String HTML output to display on error.
457 * @return HTMLForm $this for chaining calls (since 1.20)
459 function setSubmitCallback( $cb ) {
460 $this->mSubmitCallback
= $cb;
466 * Set a message to display on a validation error.
468 * @param $msg Mixed String or Array of valid inputs to wfMessage()
469 * (so each entry can be either a String or Array)
471 * @return HTMLForm $this for chaining calls (since 1.20)
473 function setValidationErrorMessage( $msg ) {
474 $this->mValidationErrorMessage
= $msg;
480 * Set the introductory message, overwriting any existing message.
482 * @param string $msg complete text of message to display
484 * @return HTMLForm $this for chaining calls (since 1.20)
486 function setIntro( $msg ) {
487 $this->setPreText( $msg );
493 * Set the introductory message, overwriting any existing message.
496 * @param string $msg complete text of message to display
498 * @return HTMLForm $this for chaining calls (since 1.20)
500 function setPreText( $msg ) {
507 * Add introductory text.
509 * @param string $msg complete text of message to display
511 * @return HTMLForm $this for chaining calls (since 1.20)
513 function addPreText( $msg ) {
520 * Add header text, inside the form.
522 * @param string $msg complete text of message to display
523 * @param string $section The section to add the header to
525 * @return HTMLForm $this for chaining calls (since 1.20)
527 function addHeaderText( $msg, $section = null ) {
528 if ( is_null( $section ) ) {
529 $this->mHeader
.= $msg;
531 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
532 $this->mSectionHeaders
[$section] = '';
534 $this->mSectionHeaders
[$section] .= $msg;
541 * Set header text, inside the form.
544 * @param string $msg complete text of message to display
545 * @param $section The section to add the header to
547 * @return HTMLForm $this for chaining calls (since 1.20)
549 function setHeaderText( $msg, $section = null ) {
550 if ( is_null( $section ) ) {
551 $this->mHeader
= $msg;
553 $this->mSectionHeaders
[$section] = $msg;
560 * Add footer text, inside the form.
562 * @param string $msg complete text of message to display
563 * @param string $section The section to add the footer text to
565 * @return HTMLForm $this for chaining calls (since 1.20)
567 function addFooterText( $msg, $section = null ) {
568 if ( is_null( $section ) ) {
569 $this->mFooter
.= $msg;
571 if ( !isset( $this->mSectionFooters
[$section] ) ) {
572 $this->mSectionFooters
[$section] = '';
574 $this->mSectionFooters
[$section] .= $msg;
581 * Set footer text, inside the form.
584 * @param string $msg complete text of message to display
585 * @param string $section The section to add the footer text to
587 * @return HTMLForm $this for chaining calls (since 1.20)
589 function setFooterText( $msg, $section = null ) {
590 if ( is_null( $section ) ) {
591 $this->mFooter
= $msg;
593 $this->mSectionFooters
[$section] = $msg;
600 * Add text to the end of the display.
602 * @param string $msg complete text of message to display
604 * @return HTMLForm $this for chaining calls (since 1.20)
606 function addPostText( $msg ) {
607 $this->mPost
.= $msg;
613 * Set text at the end of the display.
615 * @param string $msg complete text of message to display
617 * @return HTMLForm $this for chaining calls (since 1.20)
619 function setPostText( $msg ) {
626 * Add a hidden field to the output
628 * @param string $name field name. This will be used exactly as entered
629 * @param string $value field value
630 * @param $attribs Array
632 * @return HTMLForm $this for chaining calls (since 1.20)
634 public function addHiddenField( $name, $value, $attribs = array() ) {
635 $attribs +
= array( 'name' => $name );
636 $this->mHiddenFields
[] = array( $value, $attribs );
642 * Add an array of hidden fields to the output
646 * @param array $fields Associative array of fields to add;
647 * mapping names to their values
649 * @return HTMLForm $this for chaining calls
651 public function addHiddenFields( array $fields ) {
652 foreach ( $fields as $name => $value ) {
653 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
660 * Add a button to the form
662 * @param string $name field name.
663 * @param string $value field value
664 * @param string $id DOM id for the button (default: null)
665 * @param $attribs Array
667 * @return HTMLForm $this for chaining calls (since 1.20)
669 public function addButton( $name, $value, $id = null, $attribs = null ) {
670 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
676 * Display the form (sending to the context's OutputPage object), with an
677 * appropriate error message or stack of messages, and any validation errors, etc.
679 * @attention You should call prepareForm() before calling this function.
680 * Moreover, when doing method chaining this should be the very last method
681 * call just after prepareForm().
683 * @param $submitResult Mixed output from HTMLForm::trySubmit()
685 * @return Nothing, should be last call
687 function displayForm( $submitResult ) {
688 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
692 * Returns the raw HTML generated by the form
694 * @param $submitResult Mixed output from HTMLForm::trySubmit()
698 function getHTML( $submitResult ) {
699 # For good measure (it is the default)
700 $this->getOutput()->preventClickjacking();
701 $this->getOutput()->addModules( 'mediawiki.htmlform' );
702 if ( $this->isVForm() ) {
703 $this->getOutput()->addModuleStyles( 'mediawiki.ui' );
704 // @todo Should vertical form set setWrapperLegend( false )
705 // to hide ugly fieldsets?
709 . $this->getErrors( $submitResult )
712 . $this->getHiddenFields()
713 . $this->getButtons()
716 $html = $this->wrapForm( $html );
718 return '' . $this->mPre
. $html . $this->mPost
;
722 * Wrap the form innards in an actual "<form>" element
724 * @param string $html HTML contents to wrap.
726 * @return String wrapped HTML.
728 function wrapForm( $html ) {
730 # Include a <fieldset> wrapper for style, if requested.
731 if ( $this->mWrapperLegend
!== false ) {
732 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
734 # Use multipart/form-data
735 $encType = $this->mUseMultipart
736 ?
'multipart/form-data'
737 : 'application/x-www-form-urlencoded';
740 'action' => $this->getAction(),
741 'method' => $this->getMethod(),
742 'class' => array( 'visualClear' ),
743 'enctype' => $encType,
745 if ( !empty( $this->mId
) ) {
746 $attribs['id'] = $this->mId
;
749 if ( $this->isVForm() ) {
750 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
753 return Html
::rawElement( 'form', $attribs, $html );
757 * Get the hidden fields that should go inside the form.
758 * @return String HTML.
760 function getHiddenFields() {
761 global $wgArticlePath;
764 if ( $this->getMethod() == 'post' ) {
765 $html .= Html
::hidden(
767 $this->getUser()->getEditToken(),
768 array( 'id' => 'wpEditToken' )
770 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
773 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
774 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
777 foreach ( $this->mHiddenFields
as $data ) {
778 list( $value, $attribs ) = $data;
779 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
786 * Get the submit and (potentially) reset buttons.
787 * @return String HTML.
789 function getButtons() {
790 $html = '<span class="mw-htmlform-submit-buttons">';
792 if ( $this->mShowSubmit
) {
795 if ( isset( $this->mSubmitID
) ) {
796 $attribs['id'] = $this->mSubmitID
;
799 if ( isset( $this->mSubmitName
) ) {
800 $attribs['name'] = $this->mSubmitName
;
803 if ( isset( $this->mSubmitTooltip
) ) {
804 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
807 $attribs['class'] = array( 'mw-htmlform-submit' );
809 if ( $this->isVForm() ) {
810 // mw-ui-block is necessary because the buttons aren't necessarily in an
811 // immediate child div of the vform.
812 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-big', 'mw-ui-primary', 'mw-ui-block' );
815 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
817 // Buttons are top-level form elements in table and div layouts,
818 // but vform wants all elements inside divs to get spaced-out block
820 if ( $this->isVForm() ) {
821 $html = Html
::rawElement( 'div', null, "\n$html\n" );
825 if ( $this->mShowReset
) {
826 $html .= Html
::element(
830 'value' => $this->msg( 'htmlform-reset' )->text()
835 foreach ( $this->mButtons
as $button ) {
838 'name' => $button['name'],
839 'value' => $button['value']
842 if ( $button['attribs'] ) {
843 $attrs +
= $button['attribs'];
846 if ( isset( $button['id'] ) ) {
847 $attrs['id'] = $button['id'];
850 $html .= Html
::element( 'input', $attrs );
859 * Get the whole body of the form.
863 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
867 * Format and display an error message stack.
869 * @param $errors String|Array|Status
873 function getErrors( $errors ) {
874 if ( $errors instanceof Status
) {
875 if ( $errors->isOK() ) {
878 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
880 } elseif ( is_array( $errors ) ) {
881 $errorstr = $this->formatErrors( $errors );
887 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
892 * Format a stack of error messages into a single HTML string
894 * @param array $errors of message keys/values
896 * @return String HTML, a "<ul>" list of errors
898 public static function formatErrors( $errors ) {
901 foreach ( $errors as $error ) {
902 if ( is_array( $error ) ) {
903 $msg = array_shift( $error );
909 $errorstr .= Html
::rawElement(
912 wfMessage( $msg, $error )->parse()
916 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
922 * Set the text for the submit button
924 * @param string $t plaintext.
926 * @return HTMLForm $this for chaining calls (since 1.20)
928 function setSubmitText( $t ) {
929 $this->mSubmitText
= $t;
935 * Set the text for the submit button to a message
938 * @param string $msg message key
940 * @return HTMLForm $this for chaining calls (since 1.20)
942 public function setSubmitTextMsg( $msg ) {
943 $this->setSubmitText( $this->msg( $msg )->text() );
949 * Get the text for the submit button, either customised or a default.
952 function getSubmitText() {
953 return $this->mSubmitText
955 : $this->msg( 'htmlform-submit' )->text();
959 * @param string $name Submit button name
961 * @return HTMLForm $this for chaining calls (since 1.20)
963 public function setSubmitName( $name ) {
964 $this->mSubmitName
= $name;
970 * @param string $name Tooltip for the submit button
972 * @return HTMLForm $this for chaining calls (since 1.20)
974 public function setSubmitTooltip( $name ) {
975 $this->mSubmitTooltip
= $name;
981 * Set the id for the submit button.
985 * @todo FIXME: Integrity of $t is *not* validated
986 * @return HTMLForm $this for chaining calls (since 1.20)
988 function setSubmitID( $t ) {
989 $this->mSubmitID
= $t;
995 * Stop a default submit button being shown for this form. This implies that an
996 * alternate submit method must be provided manually.
1000 * @param bool $suppressSubmit Set to false to re-enable the button again
1002 * @return HTMLForm $this for chaining calls
1004 function suppressDefaultSubmit( $suppressSubmit = true ) {
1005 $this->mShowSubmit
= !$suppressSubmit;
1011 * Set the id of the \<table\> or outermost \<div\> element.
1015 * @param string $id new value of the id attribute, or "" to remove
1017 * @return HTMLForm $this for chaining calls
1019 public function setTableId( $id ) {
1020 $this->mTableId
= $id;
1026 * @param string $id DOM id for the form
1028 * @return HTMLForm $this for chaining calls (since 1.20)
1030 public function setId( $id ) {
1037 * Prompt the whole form to be wrapped in a "<fieldset>", with
1038 * this text as its "<legend>" element.
1040 * @param string|false $legend HTML to go inside the "<legend>" element, or
1041 * false for no <legend>
1044 * @return HTMLForm $this for chaining calls (since 1.20)
1046 public function setWrapperLegend( $legend ) {
1047 $this->mWrapperLegend
= $legend;
1053 * Prompt the whole form to be wrapped in a "<fieldset>", with
1054 * this message as its "<legend>" element.
1057 * @param string $msg message key
1059 * @return HTMLForm $this for chaining calls (since 1.20)
1061 public function setWrapperLegendMsg( $msg ) {
1062 $this->setWrapperLegend( $this->msg( $msg )->text() );
1068 * Set the prefix for various default messages
1069 * @todo Currently only used for the "<fieldset>" legend on forms
1070 * with multiple sections; should be used elsewhere?
1074 * @return HTMLForm $this for chaining calls (since 1.20)
1076 function setMessagePrefix( $p ) {
1077 $this->mMessagePrefix
= $p;
1083 * Set the title for form submission
1085 * @param $t Title of page the form is on/should be posted to
1087 * @return HTMLForm $this for chaining calls (since 1.20)
1089 function setTitle( $t ) {
1099 function getTitle() {
1100 return $this->mTitle
=== false
1101 ?
$this->getContext()->getTitle()
1106 * Set the method used to submit the form
1108 * @param $method String
1110 * @return HTMLForm $this for chaining calls (since 1.20)
1112 public function setMethod( $method = 'post' ) {
1113 $this->mMethod
= $method;
1118 public function getMethod() {
1119 return $this->mMethod
;
1125 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1127 * @param string $sectionName ID attribute of the "<table>" tag for this
1128 * section, ignored if empty.
1129 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1130 * each subsection, ignored if empty.
1131 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields.
1135 public function displaySection( $fields,
1137 $fieldsetIDPrefix = '',
1138 &$hasUserVisibleFields = false ) {
1139 $displayFormat = $this->getDisplayFormat();
1142 $subsectionHtml = '';
1145 switch ( $displayFormat ) {
1147 $getFieldHtmlMethod = 'getTableRow';
1150 // Close enough to a div.
1151 $getFieldHtmlMethod = 'getDiv';
1154 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1157 foreach ( $fields as $key => $value ) {
1158 if ( $value instanceof HTMLFormField
) {
1159 $v = empty( $value->mParams
['nodata'] )
1160 ?
$this->mFieldData
[$key]
1161 : $value->getDefault();
1162 $html .= $value->$getFieldHtmlMethod( $v );
1164 $labelValue = trim( $value->getLabel() );
1165 if ( $labelValue != ' ' && $labelValue !== '' ) {
1169 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1170 get_class( $value ) !== 'HTMLApiField'
1172 $hasUserVisibleFields = true;
1174 } elseif ( is_array( $value ) ) {
1175 $subsectionHasVisibleFields = false;
1177 $this->displaySection( $value,
1179 "$fieldsetIDPrefix$key-",
1180 $subsectionHasVisibleFields );
1183 if ( $subsectionHasVisibleFields === true ) {
1184 // Display the section with various niceties.
1185 $hasUserVisibleFields = true;
1187 $legend = $this->getLegend( $key );
1189 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1190 $section = $this->mSectionHeaders
[$key] . $section;
1192 if ( isset( $this->mSectionFooters
[$key] ) ) {
1193 $section .= $this->mSectionFooters
[$key];
1196 $attributes = array();
1197 if ( $fieldsetIDPrefix ) {
1198 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1200 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1202 // Just return the inputs, nothing fancy.
1203 $subsectionHtml .= $section;
1208 if ( $displayFormat !== 'raw' ) {
1211 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1212 $classes[] = 'mw-htmlform-nolabel';
1216 'class' => implode( ' ', $classes ),
1219 if ( $sectionName ) {
1220 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1223 if ( $displayFormat === 'table' ) {
1224 $html = Html
::rawElement( 'table',
1226 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1227 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1228 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1232 if ( $this->mSubSectionBeforeFields
) {
1233 return $subsectionHtml . "\n" . $html;
1235 return $html . "\n" . $subsectionHtml;
1240 * Construct the form fields from the Descriptor array
1242 function loadData() {
1243 $fieldData = array();
1245 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1246 if ( !empty( $field->mParams
['nodata'] ) ) {
1248 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1249 $fieldData[$fieldname] = $field->getDefault();
1251 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1256 foreach ( $fieldData as $name => &$value ) {
1257 $field = $this->mFlatFields
[$name];
1258 $value = $field->filter( $value, $this->mFlatFields
);
1261 $this->mFieldData
= $fieldData;
1265 * Stop a reset button being shown for this form
1267 * @param bool $suppressReset set to false to re-enable the
1270 * @return HTMLForm $this for chaining calls (since 1.20)
1272 function suppressReset( $suppressReset = true ) {
1273 $this->mShowReset
= !$suppressReset;
1279 * Overload this if you want to apply special filtration routines
1280 * to the form as a whole, after it's submitted but before it's
1287 function filterDataForSubmit( $data ) {
1292 * Get a string to go in the "<legend>" of a section fieldset.
1293 * Override this if you want something more complicated.
1295 * @param $key String
1299 public function getLegend( $key ) {
1300 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1304 * Set the value for the action attribute of the form.
1305 * When set to false (which is the default state), the set title is used.
1309 * @param string|bool $action
1311 * @return HTMLForm $this for chaining calls (since 1.20)
1313 public function setAction( $action ) {
1314 $this->mAction
= $action;
1320 * Get the value for the action attribute of the form.
1326 public function getAction() {
1327 global $wgScript, $wgArticlePath;
1329 // If an action is alredy provided, return it
1330 if ( $this->mAction
!== false ) {
1331 return $this->mAction
;
1334 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1335 // meaning that getLocalURL() would return something like "index.php?title=...".
1336 // As browser remove the query string before submitting GET forms,
1337 // it means that the title would be lost. In such case use $wgScript instead
1338 // and put title in an hidden field (see getHiddenFields()).
1339 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1343 return $this->getTitle()->getLocalURL();