3 * HTML form generation and submission handling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
27 * In order to generate the form, the HTMLForm object takes an array
28 * structure detailing the form fields available. Each element of the
29 * array is a basic property-list, including the type of field, the
30 * label it is to be given in the form, callbacks for validation and
31 * 'filtering', and other pertinent information.
33 * Field types are implemented as subclasses of the generic HTMLFormField
34 * object, and typically implement at least getInputHTML, which generates
35 * the HTML for the input field to be placed in the table.
37 * You can find extensive documentation on the www.mediawiki.org wiki:
38 * - http://www.mediawiki.org/wiki/HTMLForm
39 * - http://www.mediawiki.org/wiki/HTMLForm/tutorial
41 * The constructor input is an associative array of $fieldname => $info,
42 * where $info is an Associative Array with any of the following:
44 * 'class' -- the subclass of HTMLFormField that will be used
45 * to create the object. *NOT* the CSS class!
46 * 'type' -- roughly translates into the <select> type attribute.
47 * if 'class' is not specified, this is used as a map
48 * through HTMLForm::$typeMappings to get the class name.
49 * 'default' -- default value when the form is displayed
50 * 'id' -- HTML id attribute
51 * 'cssclass' -- CSS class
52 * 'options' -- varies according to the specific object.
53 * 'label-message' -- message key for a message to use as the label.
54 * can be an array of msg key and then parameters to
56 * 'label' -- alternatively, a raw text message. Overridden by
58 * 'help' -- message text for a message to use as a help text.
59 * 'help-message' -- message key for a message to use as a help text.
60 * can be an array of msg key and then parameters to
62 * Overwrites 'help-messages' and 'help'.
63 * 'help-messages' -- array of message key. As above, each item can
64 * be an array of msg key and then parameters.
66 * 'required' -- passed through to the object, indicating that it
67 * is a required field.
68 * 'size' -- the length of text fields
69 * 'filter-callback -- a function name to give you the chance to
70 * massage the inputted value before it's processed.
71 * @see HTMLForm::filter()
72 * 'validation-callback' -- a function name to give you the chance
73 * to impose extra validation on the field input.
74 * @see HTMLForm::validate()
75 * 'name' -- By default, the 'name' attribute of the input field
76 * is "wp{$fieldname}". If you want a different name
77 * (eg one without the "wp" prefix), specify it here and
78 * it will be used without modification.
80 * Since 1.20, you can chain mutators to ease the form generation:
83 * $form = new HTMLForm( $someFields );
84 * $form->setMethod( 'get' )
85 * ->setWrapperLegendMsg( 'message-key' )
87 * ->displayForm( '' );
89 * Note that you will have prepareForm and displayForm at the end. Other
90 * methods call done after that would simply not be part of the form :(
92 * TODO: Document 'section' / 'subsection' stuff
94 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',
116 // HTMLTextField will output the correct type="" attribute automagically.
117 // There are about four zillion other HTML5 input types, like url, but
118 // we don't use those at the moment, so no point in adding all of them.
119 'email' => 'HTMLTextField',
120 'password' => 'HTMLTextField',
123 protected $mMessagePrefix;
125 /** @var HTMLFormField[] */
126 protected $mFlatFields;
128 protected $mFieldTree;
129 protected $mShowReset = false;
130 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
195 * @param array $descriptor of Field constructs, as described above
196 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
197 * Obviates the need to call $form->setTitle()
198 * @param string $messagePrefix a prefix to go in front of default messages
200 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
201 if ( $context instanceof IContextSource
) {
202 $this->setContext( $context );
203 $this->mTitle
= false; // We don't need them to set a title
204 $this->mMessagePrefix
= $messagePrefix;
205 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
206 $this->mMessagePrefix
= $messagePrefix;
207 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
209 // it's actually $messagePrefix
210 $this->mMessagePrefix
= $context;
213 // Expand out into a tree.
214 $loadedDescriptor = array();
215 $this->mFlatFields
= array();
217 foreach ( $descriptor as $fieldname => $info ) {
218 $section = isset( $info['section'] )
222 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
223 $this->mUseMultipart
= true;
226 $field = self
::loadInputFromParameters( $fieldname, $info );
227 // FIXME During field's construct, the parent form isn't available!
228 // could add a 'parent' name-value to $info, could add a third parameter.
229 $field->mParent
= $this;
231 // vform gets too much space if empty labels generate HTML.
232 if ( $this->isVForm() ) {
233 $field->setShowEmptyLabel( false );
236 $setSection =& $loadedDescriptor;
238 $sectionParts = explode( '/', $section );
240 while ( count( $sectionParts ) ) {
241 $newName = array_shift( $sectionParts );
243 if ( !isset( $setSection[$newName] ) ) {
244 $setSection[$newName] = array();
247 $setSection =& $setSection[$newName];
251 $setSection[$fieldname] = $field;
252 $this->mFlatFields
[$fieldname] = $field;
255 $this->mFieldTree
= $loadedDescriptor;
259 * Set format in which to display the form
260 * @param string $format the name of the format to use, must be one of
261 * $this->availableDisplayFormats
262 * @throws MWException
264 * @return HTMLForm $this for chaining calls (since 1.20)
266 public function setDisplayFormat( $format ) {
267 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
268 throw new MWException( 'Display format must be one of ' . print_r( $this->availableDisplayFormats
, true ) );
270 $this->displayFormat
= $format;
275 * Getter for displayFormat
279 public function getDisplayFormat() {
280 return $this->displayFormat
;
284 * Test if displayFormat is 'vform'
288 public function isVForm() {
289 return $this->displayFormat
=== 'vform';
293 * Add the HTMLForm-specific JavaScript, if it hasn't been
295 * @deprecated since 1.18 load modules with ResourceLoader instead
297 static function addJS() {
298 wfDeprecated( __METHOD__
, '1.18' );
302 * Initialise a new Object for the field
303 * @param $fieldname string
304 * @param string $descriptor input Descriptor, as described above
305 * @throws MWException
306 * @return HTMLFormField subclass
308 static function loadInputFromParameters( $fieldname, $descriptor ) {
309 if ( isset( $descriptor['class'] ) ) {
310 $class = $descriptor['class'];
311 } elseif ( isset( $descriptor['type'] ) ) {
312 $class = self
::$typeMappings[$descriptor['type']];
313 $descriptor['class'] = $class;
319 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
322 $descriptor['fieldname'] = $fieldname;
325 # This will throw a fatal error whenever someone try to use
326 # 'class' to feed a CSS class instead of 'cssclass'. Would be
327 # great to avoid the fatal error and show a nice error.
328 $obj = new $class( $descriptor );
334 * Prepare form for submission.
336 * @attention When doing method chaining, that should be the very last
337 * method call before displayForm().
339 * @throws MWException
340 * @return HTMLForm $this for chaining calls (since 1.20)
342 function prepareForm() {
343 # Check if we have the info we need
344 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
345 throw new MWException( "You must call setTitle() on an HTMLForm" );
348 # Load data from the request.
354 * Try submitting, with edit token check first
355 * @return Status|boolean
357 function tryAuthorizedSubmit() {
361 if ( $this->getMethod() != 'post' ) {
362 $submit = true; // no session check needed
363 } elseif ( $this->getRequest()->wasPosted() ) {
364 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
365 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
366 // Session tokens for logged-out users have no security value.
367 // However, if the user gave one, check it in order to give a nice
368 // "session expired" error instead of "permission denied" or such.
369 $submit = $this->getUser()->matchEditToken( $editToken );
376 $result = $this->trySubmit();
383 * The here's-one-I-made-earlier option: do the submission if
384 * posted, or display the form with or without funky validation
386 * @return Bool or Status whether submission was successful.
389 $this->prepareForm();
391 $result = $this->tryAuthorizedSubmit();
392 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
396 $this->displayForm( $result );
401 * Validate all the fields, and call the submission callback
402 * function if everything is kosher.
403 * @throws MWException
404 * @return Mixed Bool true == Successful submission, Bool false
405 * == No submission attempted, anything else == Error to
408 function trySubmit() {
409 # Check for validation
410 foreach ( $this->mFlatFields
as $fieldname => $field ) {
411 if ( !empty( $field->mParams
['nodata'] ) ) {
414 if ( $field->validate(
415 $this->mFieldData
[$fieldname],
419 return isset( $this->mValidationErrorMessage
)
420 ?
$this->mValidationErrorMessage
421 : array( 'htmlform-invalid-input' );
425 $callback = $this->mSubmitCallback
;
426 if ( !is_callable( $callback ) ) {
427 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
430 $data = $this->filterDataForSubmit( $this->mFieldData
);
432 $res = call_user_func( $callback, $data, $this );
438 * Set a callback to a function to do something with the form
439 * once it's been successfully validated.
440 * @param string $cb function name. The function will be passed
441 * the output from HTMLForm::filterDataForSubmit, and must
442 * return Bool true on success, Bool false if no submission
443 * was attempted, or String HTML output to display on error.
444 * @return HTMLForm $this for chaining calls (since 1.20)
446 function setSubmitCallback( $cb ) {
447 $this->mSubmitCallback
= $cb;
452 * Set a message to display on a validation error.
453 * @param $msg Mixed String or Array of valid inputs to wfMessage()
454 * (so each entry can be either a String or Array)
455 * @return HTMLForm $this for chaining calls (since 1.20)
457 function setValidationErrorMessage( $msg ) {
458 $this->mValidationErrorMessage
= $msg;
463 * Set the introductory message, overwriting any existing message.
464 * @param string $msg complete text of message to display
465 * @return HTMLForm $this for chaining calls (since 1.20)
467 function setIntro( $msg ) {
468 $this->setPreText( $msg );
473 * Set the introductory message, overwriting any existing message.
475 * @param string $msg complete text of message to display
476 * @return HTMLForm $this for chaining calls (since 1.20)
478 function setPreText( $msg ) {
484 * Add introductory text.
485 * @param string $msg complete text of message to display
486 * @return HTMLForm $this for chaining calls (since 1.20)
488 function addPreText( $msg ) {
494 * Add header text, inside the form.
495 * @param string $msg complete text of message to display
496 * @param string $section The section to add the header to
497 * @return HTMLForm $this for chaining calls (since 1.20)
499 function addHeaderText( $msg, $section = null ) {
500 if ( is_null( $section ) ) {
501 $this->mHeader
.= $msg;
503 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
504 $this->mSectionHeaders
[$section] = '';
506 $this->mSectionHeaders
[$section] .= $msg;
512 * Set header text, inside the form.
514 * @param string $msg complete text of message to display
515 * @param $section The section to add the header to
516 * @return HTMLForm $this for chaining calls (since 1.20)
518 function setHeaderText( $msg, $section = null ) {
519 if ( is_null( $section ) ) {
520 $this->mHeader
= $msg;
522 $this->mSectionHeaders
[$section] = $msg;
528 * Add footer text, inside the form.
529 * @param string $msg complete text of message to display
530 * @param string $section The section to add the footer text to
531 * @return HTMLForm $this for chaining calls (since 1.20)
533 function addFooterText( $msg, $section = null ) {
534 if ( is_null( $section ) ) {
535 $this->mFooter
.= $msg;
537 if ( !isset( $this->mSectionFooters
[$section] ) ) {
538 $this->mSectionFooters
[$section] = '';
540 $this->mSectionFooters
[$section] .= $msg;
546 * Set footer text, inside the form.
548 * @param string $msg complete text of message to display
549 * @param string $section The section to add the footer text to
550 * @return HTMLForm $this for chaining calls (since 1.20)
552 function setFooterText( $msg, $section = null ) {
553 if ( is_null( $section ) ) {
554 $this->mFooter
= $msg;
556 $this->mSectionFooters
[$section] = $msg;
562 * Add text to the end of the display.
563 * @param string $msg complete text of message to display
564 * @return HTMLForm $this for chaining calls (since 1.20)
566 function addPostText( $msg ) {
567 $this->mPost
.= $msg;
572 * Set text at the end of the display.
573 * @param string $msg complete text of message to display
574 * @return HTMLForm $this for chaining calls (since 1.20)
576 function setPostText( $msg ) {
582 * Add a hidden field to the output
583 * @param string $name field name. This will be used exactly as entered
584 * @param string $value field value
585 * @param $attribs Array
586 * @return HTMLForm $this for chaining calls (since 1.20)
588 public function addHiddenField( $name, $value, $attribs = array() ) {
589 $attribs +
= array( 'name' => $name );
590 $this->mHiddenFields
[] = array( $value, $attribs );
595 * Add an array of hidden fields to the output
598 * @param array $fields Associative array of fields to add;
599 * mapping names to their values
600 * @return HTMLForm $this for chaining calls
602 public function addHiddenFields( array $fields ) {
603 foreach ( $fields as $name => $value ) {
604 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
610 * Add a button to the form
611 * @param string $name field name.
612 * @param string $value field value
613 * @param string $id DOM id for the button (default: null)
614 * @param $attribs Array
615 * @return HTMLForm $this for chaining calls (since 1.20)
617 public function addButton( $name, $value, $id = null, $attribs = null ) {
618 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
623 * Display the form (sending to the context's OutputPage object), with an
624 * appropriate error message or stack of messages, and any validation errors, etc.
626 * @attention You should call prepareForm() before calling this function.
627 * Moreover, when doing method chaining this should be the very last method
628 * call just after prepareForm().
630 * @param $submitResult Mixed output from HTMLForm::trySubmit()
631 * @return Nothing, should be last call
633 function displayForm( $submitResult ) {
634 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
638 * Returns the raw HTML generated by the form
639 * @param $submitResult Mixed output from HTMLForm::trySubmit()
642 function getHTML( $submitResult ) {
643 # For good measure (it is the default)
644 $this->getOutput()->preventClickjacking();
645 $this->getOutput()->addModules( 'mediawiki.htmlform' );
646 if ( $this->isVForm() ) {
647 $this->getOutput()->addModuleStyles( 'mediawiki.ui' );
648 // TODO should vertical form set setWrapperLegend( false )
649 // to hide ugly fieldsets?
653 . $this->getErrors( $submitResult )
656 . $this->getHiddenFields()
657 . $this->getButtons()
660 $html = $this->wrapForm( $html );
662 return '' . $this->mPre
. $html . $this->mPost
;
666 * Wrap the form innards in an actual "<form>" element
667 * @param string $html HTML contents to wrap.
668 * @return String wrapped HTML.
670 function wrapForm( $html ) {
672 # Include a <fieldset> wrapper for style, if requested.
673 if ( $this->mWrapperLegend
!== false ) {
674 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
676 # Use multipart/form-data
677 $encType = $this->mUseMultipart
678 ?
'multipart/form-data'
679 : 'application/x-www-form-urlencoded';
682 'action' => $this->getAction(),
683 'method' => $this->getMethod(),
684 'class' => array( 'visualClear' ),
685 'enctype' => $encType,
687 if ( !empty( $this->mId
) ) {
688 $attribs['id'] = $this->mId
;
691 if ( $this->isVForm() ) {
692 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
694 return Html
::rawElement( 'form', $attribs, $html );
698 * Get the hidden fields that should go inside the form.
699 * @return String HTML.
701 function getHiddenFields() {
702 global $wgArticlePath;
705 if ( $this->getMethod() == 'post' ) {
706 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
707 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
710 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
711 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
714 foreach ( $this->mHiddenFields
as $data ) {
715 list( $value, $attribs ) = $data;
716 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
723 * Get the submit and (potentially) reset buttons.
724 * @return String HTML.
726 function getButtons() {
727 $html = '<span class="mw-htmlform-submit-buttons">';
729 if ( $this->mShowSubmit
) {
732 if ( isset( $this->mSubmitID
) ) {
733 $attribs['id'] = $this->mSubmitID
;
736 if ( isset( $this->mSubmitName
) ) {
737 $attribs['name'] = $this->mSubmitName
;
740 if ( isset( $this->mSubmitTooltip
) ) {
741 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
744 $attribs['class'] = array( 'mw-htmlform-submit' );
746 if ( $this->isVForm() ) {
747 // mw-ui-block is necessary because the buttons aren't necessarily in an
748 // immediate child div of the vform.
749 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-big', 'mw-ui-primary', 'mw-ui-block' );
752 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
754 // Buttons are top-level form elements in table and div layouts,
755 // but vform wants all elements inside divs to get spaced-out block
757 if ( $this->isVForm() ) {
758 $html = Html
::rawElement( 'div', null, "\n$html\n" );
762 if ( $this->mShowReset
) {
763 $html .= Html
::element(
767 'value' => $this->msg( 'htmlform-reset' )->text()
772 foreach ( $this->mButtons
as $button ) {
775 'name' => $button['name'],
776 'value' => $button['value']
779 if ( $button['attribs'] ) {
780 $attrs +
= $button['attribs'];
783 if ( isset( $button['id'] ) ) {
784 $attrs['id'] = $button['id'];
787 $html .= Html
::element( 'input', $attrs );
796 * Get the whole body of the form.
800 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
804 * Format and display an error message stack.
805 * @param $errors String|Array|Status
808 function getErrors( $errors ) {
809 if ( $errors instanceof Status
) {
810 if ( $errors->isOK() ) {
813 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
815 } elseif ( is_array( $errors ) ) {
816 $errorstr = $this->formatErrors( $errors );
822 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
827 * Format a stack of error messages into a single HTML string
828 * @param array $errors of message keys/values
829 * @return String HTML, a "<ul>" list of errors
831 public static function formatErrors( $errors ) {
834 foreach ( $errors as $error ) {
835 if ( is_array( $error ) ) {
836 $msg = array_shift( $error );
842 $errorstr .= Html
::rawElement(
845 wfMessage( $msg, $error )->parse()
849 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
855 * Set the text for the submit button
856 * @param string $t plaintext.
857 * @return HTMLForm $this for chaining calls (since 1.20)
859 function setSubmitText( $t ) {
860 $this->mSubmitText
= $t;
865 * Set the text for the submit button to a message
867 * @param string $msg message key
868 * @return HTMLForm $this for chaining calls (since 1.20)
870 public function setSubmitTextMsg( $msg ) {
871 $this->setSubmitText( $this->msg( $msg )->text() );
876 * Get the text for the submit button, either customised or a default.
879 function getSubmitText() {
880 return $this->mSubmitText
882 : $this->msg( 'htmlform-submit' )->text();
886 * @param string $name Submit button name
887 * @return HTMLForm $this for chaining calls (since 1.20)
889 public function setSubmitName( $name ) {
890 $this->mSubmitName
= $name;
895 * @param string $name Tooltip for the submit button
896 * @return HTMLForm $this for chaining calls (since 1.20)
898 public function setSubmitTooltip( $name ) {
899 $this->mSubmitTooltip
= $name;
904 * Set the id for the submit button.
906 * @todo FIXME: Integrity of $t is *not* validated
907 * @return HTMLForm $this for chaining calls (since 1.20)
909 function setSubmitID( $t ) {
910 $this->mSubmitID
= $t;
915 * Stop a default submit button being shown for this form. This implies that an
916 * alternate submit method must be provided manually.
920 * @param bool $suppressSubmit Set to false to re-enable the button again
922 * @return HTMLForm $this for chaining calls
924 function suppressDefaultSubmit( $suppressSubmit = true ) {
925 $this->mShowSubmit
= !$suppressSubmit;
930 * Set the id of the \<table\> or outermost \<div\> element.
933 * @param string $id new value of the id attribute, or "" to remove
934 * @return HTMLForm $this for chaining calls
936 public function setTableId( $id ) {
937 $this->mTableId
= $id;
942 * @param string $id DOM id for the form
943 * @return HTMLForm $this for chaining calls (since 1.20)
945 public function setId( $id ) {
951 * Prompt the whole form to be wrapped in a "<fieldset>", with
952 * this text as its "<legend>" element.
953 * @param string|false $legend HTML to go inside the "<legend>" element, or
954 * false for no <legend>
956 * @return HTMLForm $this for chaining calls (since 1.20)
958 public function setWrapperLegend( $legend ) {
959 $this->mWrapperLegend
= $legend;
964 * Prompt the whole form to be wrapped in a "<fieldset>", with
965 * this message as its "<legend>" element.
967 * @param string $msg message key
968 * @return HTMLForm $this for chaining calls (since 1.20)
970 public function setWrapperLegendMsg( $msg ) {
971 $this->setWrapperLegend( $this->msg( $msg )->text() );
976 * Set the prefix for various default messages
977 * @todo currently only used for the "<fieldset>" legend on forms
978 * with multiple sections; should be used elsewhere?
980 * @return HTMLForm $this for chaining calls (since 1.20)
982 function setMessagePrefix( $p ) {
983 $this->mMessagePrefix
= $p;
988 * Set the title for form submission
989 * @param $t Title of page the form is on/should be posted to
990 * @return HTMLForm $this for chaining calls (since 1.20)
992 function setTitle( $t ) {
1001 function getTitle() {
1002 return $this->mTitle
=== false
1003 ?
$this->getContext()->getTitle()
1008 * Set the method used to submit the form
1009 * @param $method String
1010 * @return HTMLForm $this for chaining calls (since 1.20)
1012 public function setMethod( $method = 'post' ) {
1013 $this->mMethod
= $method;
1017 public function getMethod() {
1018 return $this->mMethod
;
1023 * @param array[]|HTMLFormField[] $fields array of fields (either arrays or objects)
1024 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
1025 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
1026 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields
1029 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '', &$hasUserVisibleFields = false ) {
1030 $displayFormat = $this->getDisplayFormat();
1033 $subsectionHtml = '';
1036 switch ( $displayFormat ) {
1038 $getFieldHtmlMethod = 'getTableRow';
1041 // Close enough to a div.
1042 $getFieldHtmlMethod = 'getDiv';
1045 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1048 foreach ( $fields as $key => $value ) {
1049 if ( $value instanceof HTMLFormField
) {
1050 $v = empty( $value->mParams
['nodata'] )
1051 ?
$this->mFieldData
[$key]
1052 : $value->getDefault();
1053 $html .= $value->$getFieldHtmlMethod( $v );
1055 $labelValue = trim( $value->getLabel() );
1056 if ( $labelValue != ' ' && $labelValue !== '' ) {
1060 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1061 get_class( $value ) !== 'HTMLApiField' ) {
1062 $hasUserVisibleFields = true;
1064 } elseif ( is_array( $value ) ) {
1065 $subsectionHasVisibleFields = false;
1066 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-", $subsectionHasVisibleFields );
1069 if ( $subsectionHasVisibleFields === true ) {
1070 // Display the section with various niceties.
1071 $hasUserVisibleFields = true;
1073 $legend = $this->getLegend( $key );
1075 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1076 $section = $this->mSectionHeaders
[$key] . $section;
1078 if ( isset( $this->mSectionFooters
[$key] ) ) {
1079 $section .= $this->mSectionFooters
[$key];
1082 $attributes = array();
1083 if ( $fieldsetIDPrefix ) {
1084 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1086 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1088 // Just return the inputs, nothing fancy.
1089 $subsectionHtml .= $section;
1094 if ( $displayFormat !== 'raw' ) {
1097 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1098 $classes[] = 'mw-htmlform-nolabel';
1102 'class' => implode( ' ', $classes ),
1105 if ( $sectionName ) {
1106 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1109 if ( $displayFormat === 'table' ) {
1110 $html = Html
::rawElement( 'table', $attribs,
1111 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1112 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1113 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1117 if ( $this->mSubSectionBeforeFields
) {
1118 return $subsectionHtml . "\n" . $html;
1120 return $html . "\n" . $subsectionHtml;
1125 * Construct the form fields from the Descriptor array
1127 function loadData() {
1128 $fieldData = array();
1130 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1131 if ( !empty( $field->mParams
['nodata'] ) ) {
1133 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1134 $fieldData[$fieldname] = $field->getDefault();
1136 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1141 foreach ( $fieldData as $name => &$value ) {
1142 $field = $this->mFlatFields
[$name];
1143 $value = $field->filter( $value, $this->mFlatFields
);
1146 $this->mFieldData
= $fieldData;
1150 * Stop a reset button being shown for this form
1151 * @param bool $suppressReset set to false to re-enable the
1153 * @return HTMLForm $this for chaining calls (since 1.20)
1155 function suppressReset( $suppressReset = true ) {
1156 $this->mShowReset
= !$suppressReset;
1161 * Overload this if you want to apply special filtration routines
1162 * to the form as a whole, after it's submitted but before it's
1167 function filterDataForSubmit( $data ) {
1172 * Get a string to go in the "<legend>" of a section fieldset.
1173 * Override this if you want something more complicated.
1174 * @param $key String
1177 public function getLegend( $key ) {
1178 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1182 * Set the value for the action attribute of the form.
1183 * When set to false (which is the default state), the set title is used.
1187 * @param string|bool $action
1188 * @return HTMLForm $this for chaining calls (since 1.20)
1190 public function setAction( $action ) {
1191 $this->mAction
= $action;
1196 * Get the value for the action attribute of the form.
1202 public function getAction() {
1203 global $wgScript, $wgArticlePath;
1205 // If an action is alredy provided, return it
1206 if ( $this->mAction
!== false ) {
1207 return $this->mAction
;
1210 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1211 // meaning that getLocalURL() would return something like "index.php?title=...".
1212 // As browser remove the query string before submitting GET forms,
1213 // it means that the title would be lost. In such case use $wgScript instead
1214 // and put title in an hidden field (see getHiddenFields()).
1215 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1219 return $this->getTitle()->getLocalURL();