4 * HTML form generation and submission handling.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms. in a reusable manner.
28 * In order to generate the form, the HTMLForm object takes an array
29 * structure detailing the form fields available. Each element of the
30 * array is a basic property-list, including the type of field, the
31 * label it is to be given in the form, callbacks for validation and
32 * 'filtering', and other pertinent information.
34 * Field types are implemented as subclasses of the generic HTMLFormField
35 * object, and typically implement at least getInputHTML, which generates
36 * the HTML for the input field to be placed in the table.
38 * You can find extensive documentation on the www.mediawiki.org wiki:
39 * - https://www.mediawiki.org/wiki/HTMLForm
40 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
45 * 'class' -- the subclass of HTMLFormField that will be used
46 * to create the object. *NOT* the CSS class!
47 * 'type' -- roughly translates into the <select> type attribute.
48 * if 'class' is not specified, this is used as a map
49 * through HTMLForm::$typeMappings to get the class name.
50 * 'default' -- default value when the form is displayed
51 * 'id' -- HTML id attribute
52 * 'cssclass' -- CSS class
53 * 'csshelpclass' -- CSS class used to style help text
54 * 'dir' -- Direction of the element.
55 * 'options' -- associative array mapping labels to values.
56 * Some field types support multi-level arrays.
57 * 'options-messages' -- associative array mapping message keys to values.
58 * Some field types support multi-level arrays.
59 * 'options-message' -- message key to be parsed to extract the list of
60 * options (like 'ipbreason-dropdown').
61 * 'label-message' -- message key for a message to use as the label.
62 * can be an array of msg key and then parameters to
64 * 'label' -- alternatively, a raw text message. Overridden by
66 * 'help' -- message text for a message to use as a help text.
67 * 'help-message' -- message key for a message to use as a help text.
68 * can be an array of msg key and then parameters to
70 * Overwrites 'help-messages' and 'help'.
71 * 'help-messages' -- array of message key. As above, each item can
72 * be an array of msg key and then parameters.
74 * 'required' -- passed through to the object, indicating that it
75 * is a required field.
76 * 'size' -- the length of text fields
77 * 'filter-callback -- a function name to give you the chance to
78 * massage the inputted value before it's processed.
79 * @see HTMLForm::filter()
80 * 'validation-callback' -- a function name to give you the chance
81 * to impose extra validation on the field input.
82 * @see HTMLForm::validate()
83 * 'name' -- By default, the 'name' attribute of the input field
84 * is "wp{$fieldname}". If you want a different name
85 * (eg one without the "wp" prefix), specify it here and
86 * it will be used without modification.
87 * 'hide-if' -- expression given as an array stating when the field
88 * should be hidden. The first array value has to be the
89 * expression's logic operator. Supported expressions:
91 * [ 'NOT', array $expression ]
92 * To hide a field if a given expression is not true.
94 * [ '===', string $fieldName, string $value ]
95 * To hide a field if another field identified by
96 * $field has the value $value.
98 * [ '!==', string $fieldName, string $value ]
99 * Same as [ 'NOT', [ '===', $fieldName, $value ]
100 * 'OR', 'AND', 'NOR', 'NAND'
101 * [ 'XXX', array $expression1, ..., array $expressionN ]
102 * To hide a field if one or more (OR), all (AND),
103 * neither (NOR) or not all (NAND) given expressions
104 * are evaluated as true.
105 * The expressions will be given to a JavaScript frontend
106 * module which will continually update the field's
109 * Since 1.20, you can chain mutators to ease the form generation:
112 * $form = new HTMLForm( $someFields );
113 * $form->setMethod( 'get' )
114 * ->setWrapperLegendMsg( 'message-key' )
116 * ->displayForm( '' );
118 * Note that you will have prepareForm and displayForm at the end. Other
119 * methods call done after that would simply not be part of the form :(
121 * @todo Document 'section' / 'subsection' stuff
123 class HTMLForm
extends ContextSource
{
124 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
125 public static $typeMappings = array(
126 'api' => 'HTMLApiField',
127 'text' => 'HTMLTextField',
128 'textarea' => 'HTMLTextAreaField',
129 'select' => 'HTMLSelectField',
130 'radio' => 'HTMLRadioField',
131 'multiselect' => 'HTMLMultiSelectField',
132 'limitselect' => 'HTMLSelectLimitField',
133 'check' => 'HTMLCheckField',
134 'toggle' => 'HTMLCheckField',
135 'int' => 'HTMLIntField',
136 'float' => 'HTMLFloatField',
137 'info' => 'HTMLInfoField',
138 'selectorother' => 'HTMLSelectOrOtherField',
139 'selectandother' => 'HTMLSelectAndOtherField',
140 'namespaceselect' => 'HTMLSelectNamespace',
141 'tagfilter' => 'HTMLTagFilter',
142 'submit' => 'HTMLSubmitField',
143 'hidden' => 'HTMLHiddenField',
144 'edittools' => 'HTMLEditTools',
145 'checkmatrix' => 'HTMLCheckMatrix',
146 'cloner' => 'HTMLFormFieldCloner',
147 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
148 // HTMLTextField will output the correct type="" attribute automagically.
149 // There are about four zillion other HTML5 input types, like range, but
150 // we don't use those at the moment, so no point in adding all of them.
151 'email' => 'HTMLTextField',
152 'password' => 'HTMLTextField',
153 'url' => 'HTMLTextField',
158 protected $mMessagePrefix;
160 /** @var HTMLFormField[] */
161 protected $mFlatFields;
163 protected $mFieldTree;
164 protected $mShowReset = false;
165 protected $mShowSubmit = true;
166 protected $mSubmitModifierClass = 'mw-ui-constructive';
168 protected $mSubmitCallback;
169 protected $mValidationErrorMessage;
171 protected $mPre = '';
172 protected $mHeader = '';
173 protected $mFooter = '';
174 protected $mSectionHeaders = array();
175 protected $mSectionFooters = array();
176 protected $mPost = '';
178 protected $mTableId = '';
180 protected $mSubmitID;
181 protected $mSubmitName;
182 protected $mSubmitText;
183 protected $mSubmitTooltip;
186 protected $mMethod = 'post';
187 protected $mWasSubmitted = false;
190 * Form action URL. false means we will use the URL to set Title
194 protected $mAction = false;
196 protected $mUseMultipart = false;
197 protected $mHiddenFields = array();
198 protected $mButtons = array();
200 protected $mWrapperLegend = false;
203 * Salt for the edit token.
206 protected $mTokenSalt = '';
209 * If true, sections that contain both fields and subsections will
210 * render their subsections before their fields.
212 * Subclasses may set this to false to render subsections after fields
215 protected $mSubSectionBeforeFields = true;
218 * Format in which to display form. For viable options,
219 * @see $availableDisplayFormats
222 protected $displayFormat = 'table';
225 * Available formats in which to display the form
228 protected $availableDisplayFormats = array(
236 * Available formats in which to display the form
239 protected $availableSubclassDisplayFormats = array(
244 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
246 * @throws MWException When the display format requested is not known
247 * @param string $displayFormat
248 * @param mixed $arguments... Additional arguments to pass to the constructor.
251 public static function factory( $displayFormat/*, $arguments...*/ ) {
252 $arguments = func_get_args();
253 array_shift( $arguments );
255 switch ( $displayFormat ) {
257 $reflector = new ReflectionClass( 'VFormHTMLForm' );
258 return $reflector->newInstanceArgs( $arguments );
260 $reflector = new ReflectionClass( 'HTMLForm' );
261 $form = $reflector->newInstanceArgs( $arguments );
262 $form->setDisplayFormat( $displayFormat );
268 * Build a new HTMLForm from an array of field attributes
270 * @param array $descriptor Array of Field constructs, as described above
271 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
272 * Obviates the need to call $form->setTitle()
273 * @param string $messagePrefix A prefix to go in front of default messages
275 public function __construct( $descriptor, /*IContextSource*/ $context = null,
278 if ( $context instanceof IContextSource
) {
279 $this->setContext( $context );
280 $this->mTitle
= false; // We don't need them to set a title
281 $this->mMessagePrefix
= $messagePrefix;
282 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
283 $this->mMessagePrefix
= $messagePrefix;
284 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
286 // it's actually $messagePrefix
287 $this->mMessagePrefix
= $context;
290 // Evil hack for mobile :(
291 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat
=== 'table' ) {
292 $this->displayFormat
= 'div';
295 // Expand out into a tree.
296 $loadedDescriptor = array();
297 $this->mFlatFields
= array();
299 foreach ( $descriptor as $fieldname => $info ) {
300 $section = isset( $info['section'] )
304 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
305 $this->mUseMultipart
= true;
308 $field = static::loadInputFromParameters( $fieldname, $info, $this );
310 $setSection =& $loadedDescriptor;
312 $sectionParts = explode( '/', $section );
314 while ( count( $sectionParts ) ) {
315 $newName = array_shift( $sectionParts );
317 if ( !isset( $setSection[$newName] ) ) {
318 $setSection[$newName] = array();
321 $setSection =& $setSection[$newName];
325 $setSection[$fieldname] = $field;
326 $this->mFlatFields
[$fieldname] = $field;
329 $this->mFieldTree
= $loadedDescriptor;
333 * Set format in which to display the form
335 * @param string $format The name of the format to use, must be one of
336 * $this->availableDisplayFormats
338 * @throws MWException
340 * @return HTMLForm $this for chaining calls (since 1.20)
342 public function setDisplayFormat( $format ) {
344 in_array( $format, $this->availableSubclassDisplayFormats
) ||
345 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
347 throw new MWException( 'Cannot change display format after creation, ' .
348 'use HTMLForm::factory() instead' );
351 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
352 throw new MWException( 'Display format must be one of ' .
353 print_r( $this->availableDisplayFormats
, true ) );
356 // Evil hack for mobile :(
357 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
361 $this->displayFormat
= $format;
367 * Getter for displayFormat
371 public function getDisplayFormat() {
372 return $this->displayFormat
;
376 * Test if displayFormat is 'vform'
378 * @deprecated since 1.25
381 public function isVForm() {
382 wfDeprecated( __METHOD__
, '1.25' );
387 * Get the HTMLFormField subclass for this descriptor.
389 * The descriptor can be passed either 'class' which is the name of
390 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
391 * This makes sure the 'class' is always set, and also is returned by
392 * this function for ease.
396 * @param string $fieldname Name of the field
397 * @param array $descriptor Input Descriptor, as described above
399 * @throws MWException
400 * @return string Name of a HTMLFormField subclass
402 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
403 if ( isset( $descriptor['class'] ) ) {
404 $class = $descriptor['class'];
405 } elseif ( isset( $descriptor['type'] ) ) {
406 $class = static::$typeMappings[$descriptor['type']];
407 $descriptor['class'] = $class;
413 throw new MWException( "Descriptor with no class for $fieldname: "
414 . print_r( $descriptor, true ) );
421 * Initialise a new Object for the field
423 * @param string $fieldname Name of the field
424 * @param array $descriptor Input Descriptor, as described above
425 * @param HTMLForm|null $parent Parent instance of HTMLForm
427 * @throws MWException
428 * @return HTMLFormField Instance of a subclass of HTMLFormField
430 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm
$parent = null ) {
431 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
433 $descriptor['fieldname'] = $fieldname;
435 $descriptor['parent'] = $parent;
438 # @todo This will throw a fatal error whenever someone try to use
439 # 'class' to feed a CSS class instead of 'cssclass'. Would be
440 # great to avoid the fatal error and show a nice error.
441 $obj = new $class( $descriptor );
447 * Prepare form for submission.
449 * @attention When doing method chaining, that should be the very last
450 * method call before displayForm().
452 * @throws MWException
453 * @return HTMLForm $this for chaining calls (since 1.20)
455 function prepareForm() {
456 # Check if we have the info we need
457 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
458 throw new MWException( "You must call setTitle() on an HTMLForm" );
461 # Load data from the request.
468 * Try submitting, with edit token check first
469 * @return Status|bool
471 function tryAuthorizedSubmit() {
475 if ( $this->getMethod() != 'post' ) {
476 $submit = true; // no session check needed
477 } elseif ( $this->getRequest()->wasPosted() ) {
478 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
479 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
480 // Session tokens for logged-out users have no security value.
481 // However, if the user gave one, check it in order to give a nice
482 // "session expired" error instead of "permission denied" or such.
483 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
490 $this->mWasSubmitted
= true;
491 $result = $this->trySubmit();
498 * The here's-one-I-made-earlier option: do the submission if
499 * posted, or display the form with or without funky validation
501 * @return bool|Status Whether submission was successful.
504 $this->prepareForm();
506 $result = $this->tryAuthorizedSubmit();
507 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
511 $this->displayForm( $result );
517 * Validate all the fields, and call the submission callback
518 * function if everything is kosher.
519 * @throws MWException
520 * @return bool|string|array|Status
521 * - Bool true or a good Status object indicates success,
522 * - Bool false indicates no submission was attempted,
523 * - Anything else indicates failure. The value may be a fatal Status
524 * object, an HTML string, or an array of arrays (message keys and
525 * params) or strings (message keys)
527 function trySubmit() {
528 $this->mWasSubmitted
= true;
530 # Check for cancelled submission
531 foreach ( $this->mFlatFields
as $fieldname => $field ) {
532 if ( !empty( $field->mParams
['nodata'] ) ) {
535 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
536 $this->mWasSubmitted
= false;
541 # Check for validation
542 foreach ( $this->mFlatFields
as $fieldname => $field ) {
543 if ( !empty( $field->mParams
['nodata'] ) ) {
546 if ( $field->isHidden( $this->mFieldData
) ) {
549 if ( $field->validate(
550 $this->mFieldData
[$fieldname],
554 return isset( $this->mValidationErrorMessage
)
555 ?
$this->mValidationErrorMessage
556 : array( 'htmlform-invalid-input' );
560 $callback = $this->mSubmitCallback
;
561 if ( !is_callable( $callback ) ) {
562 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
563 'setSubmitCallback() to set one.' );
566 $data = $this->filterDataForSubmit( $this->mFieldData
);
568 $res = call_user_func( $callback, $data, $this );
569 if ( $res === false ) {
570 $this->mWasSubmitted
= false;
577 * Test whether the form was considered to have been submitted or not, i.e.
578 * whether the last call to tryAuthorizedSubmit or trySubmit returned
581 * This will return false until HTMLForm::tryAuthorizedSubmit or
582 * HTMLForm::trySubmit is called.
587 function wasSubmitted() {
588 return $this->mWasSubmitted
;
592 * Set a callback to a function to do something with the form
593 * once it's been successfully validated.
595 * @param callable $cb The function will be passed the output from
596 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
597 * return as documented for HTMLForm::trySubmit
599 * @return HTMLForm $this for chaining calls (since 1.20)
601 function setSubmitCallback( $cb ) {
602 $this->mSubmitCallback
= $cb;
608 * Set a message to display on a validation error.
610 * @param string|array $msg String or Array of valid inputs to wfMessage()
611 * (so each entry can be either a String or Array)
613 * @return HTMLForm $this for chaining calls (since 1.20)
615 function setValidationErrorMessage( $msg ) {
616 $this->mValidationErrorMessage
= $msg;
622 * Set the introductory message, overwriting any existing message.
624 * @param string $msg Complete text of message to display
626 * @return HTMLForm $this for chaining calls (since 1.20)
628 function setIntro( $msg ) {
629 $this->setPreText( $msg );
635 * Set the introductory message, overwriting any existing message.
638 * @param string $msg Complete text of message to display
640 * @return HTMLForm $this for chaining calls (since 1.20)
642 function setPreText( $msg ) {
649 * Add introductory text.
651 * @param string $msg Complete text of message to display
653 * @return HTMLForm $this for chaining calls (since 1.20)
655 function addPreText( $msg ) {
662 * Add header text, inside the form.
664 * @param string $msg Complete text of message to display
665 * @param string|null $section The section to add the header to
667 * @return HTMLForm $this for chaining calls (since 1.20)
669 function addHeaderText( $msg, $section = null ) {
670 if ( is_null( $section ) ) {
671 $this->mHeader
.= $msg;
673 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
674 $this->mSectionHeaders
[$section] = '';
676 $this->mSectionHeaders
[$section] .= $msg;
683 * Set header text, inside the form.
686 * @param string $msg Complete text of message to display
687 * @param string|null $section The section to add the header to
689 * @return HTMLForm $this for chaining calls (since 1.20)
691 function setHeaderText( $msg, $section = null ) {
692 if ( is_null( $section ) ) {
693 $this->mHeader
= $msg;
695 $this->mSectionHeaders
[$section] = $msg;
702 * Add footer text, inside the form.
704 * @param string $msg Complete text of message to display
705 * @param string|null $section The section to add the footer text to
707 * @return HTMLForm $this for chaining calls (since 1.20)
709 function addFooterText( $msg, $section = null ) {
710 if ( is_null( $section ) ) {
711 $this->mFooter
.= $msg;
713 if ( !isset( $this->mSectionFooters
[$section] ) ) {
714 $this->mSectionFooters
[$section] = '';
716 $this->mSectionFooters
[$section] .= $msg;
723 * Set footer text, inside the form.
726 * @param string $msg Complete text of message to display
727 * @param string|null $section The section to add the footer text to
729 * @return HTMLForm $this for chaining calls (since 1.20)
731 function setFooterText( $msg, $section = null ) {
732 if ( is_null( $section ) ) {
733 $this->mFooter
= $msg;
735 $this->mSectionFooters
[$section] = $msg;
742 * Add text to the end of the display.
744 * @param string $msg Complete text of message to display
746 * @return HTMLForm $this for chaining calls (since 1.20)
748 function addPostText( $msg ) {
749 $this->mPost
.= $msg;
755 * Set text at the end of the display.
757 * @param string $msg Complete text of message to display
759 * @return HTMLForm $this for chaining calls (since 1.20)
761 function setPostText( $msg ) {
768 * Add a hidden field to the output
770 * @param string $name Field name. This will be used exactly as entered
771 * @param string $value Field value
772 * @param array $attribs
774 * @return HTMLForm $this for chaining calls (since 1.20)
776 public function addHiddenField( $name, $value, $attribs = array() ) {
777 $attribs +
= array( 'name' => $name );
778 $this->mHiddenFields
[] = array( $value, $attribs );
784 * Add an array of hidden fields to the output
788 * @param array $fields Associative array of fields to add;
789 * mapping names to their values
791 * @return HTMLForm $this for chaining calls
793 public function addHiddenFields( array $fields ) {
794 foreach ( $fields as $name => $value ) {
795 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
802 * Add a button to the form
804 * @param string $name Field name.
805 * @param string $value Field value
806 * @param string $id DOM id for the button (default: null)
807 * @param array $attribs
809 * @return HTMLForm $this for chaining calls (since 1.20)
811 public function addButton( $name, $value, $id = null, $attribs = null ) {
812 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
818 * Set the salt for the edit token.
820 * Only useful when the method is "post".
823 * @param string|array $salt Salt to use
824 * @return HTMLForm $this For chaining calls
826 public function setTokenSalt( $salt ) {
827 $this->mTokenSalt
= $salt;
833 * Display the form (sending to the context's OutputPage object), with an
834 * appropriate error message or stack of messages, and any validation errors, etc.
836 * @attention You should call prepareForm() before calling this function.
837 * Moreover, when doing method chaining this should be the very last method
838 * call just after prepareForm().
840 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
842 * @return void Nothing, should be last call
844 function displayForm( $submitResult ) {
845 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
849 * Returns the raw HTML generated by the form
851 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
855 function getHTML( $submitResult ) {
856 # For good measure (it is the default)
857 $this->getOutput()->preventClickjacking();
858 $this->getOutput()->addModules( 'mediawiki.htmlform' );
861 . $this->getErrors( $submitResult )
864 . $this->getHiddenFields()
865 . $this->getButtons()
868 $html = $this->wrapForm( $html );
870 return '' . $this->mPre
. $html . $this->mPost
;
874 * Get HTML attributes for the `<form>` tag.
877 protected function getFormAttributes() {
878 # Use multipart/form-data
879 $encType = $this->mUseMultipart
880 ?
'multipart/form-data'
881 : 'application/x-www-form-urlencoded';
884 'action' => $this->getAction(),
885 'method' => $this->getMethod(),
886 'class' => array( 'visualClear' ),
887 'enctype' => $encType,
889 if ( !empty( $this->mId
) ) {
890 $attribs['id'] = $this->mId
;
896 * Wrap the form innards in an actual "<form>" element
898 * @param string $html HTML contents to wrap.
900 * @return string Wrapped HTML.
902 function wrapForm( $html ) {
903 # Include a <fieldset> wrapper for style, if requested.
904 if ( $this->mWrapperLegend
!== false ) {
905 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
908 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
912 * Get the hidden fields that should go inside the form.
913 * @return string HTML.
915 function getHiddenFields() {
917 if ( $this->getMethod() == 'post' ) {
918 $html .= Html
::hidden(
920 $this->getUser()->getEditToken( $this->mTokenSalt
),
921 array( 'id' => 'wpEditToken' )
923 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
926 $articlePath = $this->getConfig()->get( 'ArticlePath' );
927 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
928 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
931 foreach ( $this->mHiddenFields
as $data ) {
932 list( $value, $attribs ) = $data;
933 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
940 * Get the submit and (potentially) reset buttons.
941 * @return string HTML.
943 function getButtons() {
945 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
947 if ( $this->mShowSubmit
) {
950 if ( isset( $this->mSubmitID
) ) {
951 $attribs['id'] = $this->mSubmitID
;
954 if ( isset( $this->mSubmitName
) ) {
955 $attribs['name'] = $this->mSubmitName
;
958 if ( isset( $this->mSubmitTooltip
) ) {
959 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
962 $attribs['class'] = array( 'mw-htmlform-submit' );
964 if ( $useMediaWikiUIEverywhere ) {
965 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
968 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
971 if ( $this->mShowReset
) {
972 $buttons .= Html
::element(
976 'value' => $this->msg( 'htmlform-reset' )->text(),
977 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
982 foreach ( $this->mButtons
as $button ) {
985 'name' => $button['name'],
986 'value' => $button['value']
989 if ( $button['attribs'] ) {
990 $attrs +
= $button['attribs'];
993 if ( isset( $button['id'] ) ) {
994 $attrs['id'] = $button['id'];
997 if ( $useMediaWikiUIEverywhere ) {
998 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
999 $attrs['class'][] = 'mw-ui-button';
1002 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1005 $html = Html
::rawElement( 'span',
1006 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1012 * Get the whole body of the form.
1015 function getBody() {
1016 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1020 * Format and display an error message stack.
1022 * @param string|array|Status $errors
1026 function getErrors( $errors ) {
1027 if ( $errors instanceof Status
) {
1028 if ( $errors->isOK() ) {
1031 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1033 } elseif ( is_array( $errors ) ) {
1034 $errorstr = $this->formatErrors( $errors );
1036 $errorstr = $errors;
1040 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1045 * Format a stack of error messages into a single HTML string
1047 * @param array $errors Array of message keys/values
1049 * @return string HTML, a "<ul>" list of errors
1051 public function formatErrors( $errors ) {
1054 foreach ( $errors as $error ) {
1055 if ( is_array( $error ) ) {
1056 $msg = array_shift( $error );
1062 $errorstr .= Html
::rawElement(
1065 $this->msg( $msg, $error )->parse()
1069 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1075 * Set the text for the submit button
1077 * @param string $t Plaintext
1079 * @return HTMLForm $this for chaining calls (since 1.20)
1081 function setSubmitText( $t ) {
1082 $this->mSubmitText
= $t;
1088 * Identify that the submit button in the form has a destructive action
1091 public function setSubmitDestructive() {
1092 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1096 * Identify that the submit button in the form has a progressive action
1099 public function setSubmitProgressive() {
1100 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1104 * Set the text for the submit button to a message
1107 * @param string|Message $msg Message key or Message object
1109 * @return HTMLForm $this for chaining calls (since 1.20)
1111 public function setSubmitTextMsg( $msg ) {
1112 if ( !$msg instanceof Message
) {
1113 $msg = $this->msg( $msg );
1115 $this->setSubmitText( $msg->text() );
1121 * Get the text for the submit button, either customised or a default.
1124 function getSubmitText() {
1125 return $this->mSubmitText
1126 ?
$this->mSubmitText
1127 : $this->msg( 'htmlform-submit' )->text();
1131 * @param string $name Submit button name
1133 * @return HTMLForm $this for chaining calls (since 1.20)
1135 public function setSubmitName( $name ) {
1136 $this->mSubmitName
= $name;
1142 * @param string $name Tooltip for the submit button
1144 * @return HTMLForm $this for chaining calls (since 1.20)
1146 public function setSubmitTooltip( $name ) {
1147 $this->mSubmitTooltip
= $name;
1153 * Set the id for the submit button.
1157 * @todo FIXME: Integrity of $t is *not* validated
1158 * @return HTMLForm $this for chaining calls (since 1.20)
1160 function setSubmitID( $t ) {
1161 $this->mSubmitID
= $t;
1167 * Stop a default submit button being shown for this form. This implies that an
1168 * alternate submit method must be provided manually.
1172 * @param bool $suppressSubmit Set to false to re-enable the button again
1174 * @return HTMLForm $this for chaining calls
1176 function suppressDefaultSubmit( $suppressSubmit = true ) {
1177 $this->mShowSubmit
= !$suppressSubmit;
1183 * Set the id of the \<table\> or outermost \<div\> element.
1187 * @param string $id New value of the id attribute, or "" to remove
1189 * @return HTMLForm $this for chaining calls
1191 public function setTableId( $id ) {
1192 $this->mTableId
= $id;
1198 * @param string $id DOM id for the form
1200 * @return HTMLForm $this for chaining calls (since 1.20)
1202 public function setId( $id ) {
1209 * Prompt the whole form to be wrapped in a "<fieldset>", with
1210 * this text as its "<legend>" element.
1212 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1213 * false for no <legend>
1216 * @return HTMLForm $this for chaining calls (since 1.20)
1218 public function setWrapperLegend( $legend ) {
1219 $this->mWrapperLegend
= $legend;
1225 * Prompt the whole form to be wrapped in a "<fieldset>", with
1226 * this message as its "<legend>" element.
1229 * @param string|Message $msg Message key or Message object
1231 * @return HTMLForm $this for chaining calls (since 1.20)
1233 public function setWrapperLegendMsg( $msg ) {
1234 if ( !$msg instanceof Message
) {
1235 $msg = $this->msg( $msg );
1237 $this->setWrapperLegend( $msg->text() );
1243 * Set the prefix for various default messages
1244 * @todo Currently only used for the "<fieldset>" legend on forms
1245 * with multiple sections; should be used elsewhere?
1249 * @return HTMLForm $this for chaining calls (since 1.20)
1251 function setMessagePrefix( $p ) {
1252 $this->mMessagePrefix
= $p;
1258 * Set the title for form submission
1260 * @param Title $t Title of page the form is on/should be posted to
1262 * @return HTMLForm $this for chaining calls (since 1.20)
1264 function setTitle( $t ) {
1274 function getTitle() {
1275 return $this->mTitle
=== false
1276 ?
$this->getContext()->getTitle()
1281 * Set the method used to submit the form
1283 * @param string $method
1285 * @return HTMLForm $this for chaining calls (since 1.20)
1287 public function setMethod( $method = 'post' ) {
1288 $this->mMethod
= $method;
1293 public function getMethod() {
1294 return $this->mMethod
;
1300 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1302 * @param string $sectionName ID attribute of the "<table>" tag for this
1303 * section, ignored if empty.
1304 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1305 * each subsection, ignored if empty.
1306 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1310 public function displaySection( $fields,
1312 $fieldsetIDPrefix = '',
1313 &$hasUserVisibleFields = false ) {
1314 $displayFormat = $this->getDisplayFormat();
1317 $subsectionHtml = '';
1320 // Conveniently, PHP method names are case-insensitive.
1321 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1323 foreach ( $fields as $key => $value ) {
1324 if ( $value instanceof HTMLFormField
) {
1325 $v = empty( $value->mParams
['nodata'] )
1326 ?
$this->mFieldData
[$key]
1327 : $value->getDefault();
1328 $html .= $value->$getFieldHtmlMethod( $v );
1330 $labelValue = trim( $value->getLabel() );
1331 if ( $labelValue != ' ' && $labelValue !== '' ) {
1335 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1336 get_class( $value ) !== 'HTMLApiField'
1338 $hasUserVisibleFields = true;
1340 } elseif ( is_array( $value ) ) {
1341 $subsectionHasVisibleFields = false;
1343 $this->displaySection( $value,
1345 "$fieldsetIDPrefix$key-",
1346 $subsectionHasVisibleFields );
1349 if ( $subsectionHasVisibleFields === true ) {
1350 // Display the section with various niceties.
1351 $hasUserVisibleFields = true;
1353 $legend = $this->getLegend( $key );
1355 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1356 $section = $this->mSectionHeaders
[$key] . $section;
1358 if ( isset( $this->mSectionFooters
[$key] ) ) {
1359 $section .= $this->mSectionFooters
[$key];
1362 $attributes = array();
1363 if ( $fieldsetIDPrefix ) {
1364 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1366 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1368 // Just return the inputs, nothing fancy.
1369 $subsectionHtml .= $section;
1374 if ( $displayFormat !== 'raw' ) {
1377 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1378 $classes[] = 'mw-htmlform-nolabel';
1382 'class' => implode( ' ', $classes ),
1385 if ( $sectionName ) {
1386 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1389 if ( $displayFormat === 'table' ) {
1390 $html = Html
::rawElement( 'table',
1392 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1393 } elseif ( $displayFormat === 'inline' ) {
1394 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1396 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1400 if ( $this->mSubSectionBeforeFields
) {
1401 return $subsectionHtml . "\n" . $html;
1403 return $html . "\n" . $subsectionHtml;
1408 * Construct the form fields from the Descriptor array
1410 function loadData() {
1411 $fieldData = array();
1413 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1414 if ( !empty( $field->mParams
['nodata'] ) ) {
1416 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1417 $fieldData[$fieldname] = $field->getDefault();
1419 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1424 foreach ( $fieldData as $name => &$value ) {
1425 $field = $this->mFlatFields
[$name];
1426 $value = $field->filter( $value, $this->mFlatFields
);
1429 $this->mFieldData
= $fieldData;
1433 * Stop a reset button being shown for this form
1435 * @param bool $suppressReset Set to false to re-enable the button again
1437 * @return HTMLForm $this for chaining calls (since 1.20)
1439 function suppressReset( $suppressReset = true ) {
1440 $this->mShowReset
= !$suppressReset;
1446 * Overload this if you want to apply special filtration routines
1447 * to the form as a whole, after it's submitted but before it's
1450 * @param array $data
1454 function filterDataForSubmit( $data ) {
1459 * Get a string to go in the "<legend>" of a section fieldset.
1460 * Override this if you want something more complicated.
1462 * @param string $key
1466 public function getLegend( $key ) {
1467 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1471 * Set the value for the action attribute of the form.
1472 * When set to false (which is the default state), the set title is used.
1476 * @param string|bool $action
1478 * @return HTMLForm $this for chaining calls (since 1.20)
1480 public function setAction( $action ) {
1481 $this->mAction
= $action;
1487 * Get the value for the action attribute of the form.
1493 public function getAction() {
1494 // If an action is alredy provided, return it
1495 if ( $this->mAction
!== false ) {
1496 return $this->mAction
;
1499 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1500 // Check whether we are in GET mode and the ArticlePath contains a "?"
1501 // meaning that getLocalURL() would return something like "index.php?title=...".
1502 // As browser remove the query string before submitting GET forms,
1503 // it means that the title would be lost. In such case use wfScript() instead
1504 // and put title in an hidden field (see getHiddenFields()).
1505 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1509 return $this->getTitle()->getLocalURL();