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(
245 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
247 * @throws MWException When the display format requested is not known
248 * @param string $displayFormat
249 * @param mixed $arguments... Additional arguments to pass to the constructor.
252 public static function factory( $displayFormat/*, $arguments...*/ ) {
253 $arguments = func_get_args();
254 array_shift( $arguments );
256 switch ( $displayFormat ) {
258 $reflector = new ReflectionClass( 'VFormHTMLForm' );
259 return $reflector->newInstanceArgs( $arguments );
261 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
262 return $reflector->newInstanceArgs( $arguments );
264 $reflector = new ReflectionClass( 'HTMLForm' );
265 $form = $reflector->newInstanceArgs( $arguments );
266 $form->setDisplayFormat( $displayFormat );
272 * Build a new HTMLForm from an array of field attributes
274 * @param array $descriptor Array of Field constructs, as described above
275 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
276 * Obviates the need to call $form->setTitle()
277 * @param string $messagePrefix A prefix to go in front of default messages
279 public function __construct( $descriptor, /*IContextSource*/ $context = null,
282 if ( $context instanceof IContextSource
) {
283 $this->setContext( $context );
284 $this->mTitle
= false; // We don't need them to set a title
285 $this->mMessagePrefix
= $messagePrefix;
286 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
287 $this->mMessagePrefix
= $messagePrefix;
288 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
290 // it's actually $messagePrefix
291 $this->mMessagePrefix
= $context;
294 // Evil hack for mobile :(
295 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat
=== 'table' ) {
296 $this->displayFormat
= 'div';
299 // Expand out into a tree.
300 $loadedDescriptor = array();
301 $this->mFlatFields
= array();
303 foreach ( $descriptor as $fieldname => $info ) {
304 $section = isset( $info['section'] )
308 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
309 $this->mUseMultipart
= true;
312 $field = static::loadInputFromParameters( $fieldname, $info, $this );
314 $setSection =& $loadedDescriptor;
316 $sectionParts = explode( '/', $section );
318 while ( count( $sectionParts ) ) {
319 $newName = array_shift( $sectionParts );
321 if ( !isset( $setSection[$newName] ) ) {
322 $setSection[$newName] = array();
325 $setSection =& $setSection[$newName];
329 $setSection[$fieldname] = $field;
330 $this->mFlatFields
[$fieldname] = $field;
333 $this->mFieldTree
= $loadedDescriptor;
337 * Set format in which to display the form
339 * @param string $format The name of the format to use, must be one of
340 * $this->availableDisplayFormats
342 * @throws MWException
344 * @return HTMLForm $this for chaining calls (since 1.20)
346 public function setDisplayFormat( $format ) {
348 in_array( $format, $this->availableSubclassDisplayFormats
) ||
349 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
351 throw new MWException( 'Cannot change display format after creation, ' .
352 'use HTMLForm::factory() instead' );
355 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
356 throw new MWException( 'Display format must be one of ' .
357 print_r( $this->availableDisplayFormats
, true ) );
360 // Evil hack for mobile :(
361 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
365 $this->displayFormat
= $format;
371 * Getter for displayFormat
375 public function getDisplayFormat() {
376 return $this->displayFormat
;
380 * Test if displayFormat is 'vform'
382 * @deprecated since 1.25
385 public function isVForm() {
386 wfDeprecated( __METHOD__
, '1.25' );
391 * Get the HTMLFormField subclass for this descriptor.
393 * The descriptor can be passed either 'class' which is the name of
394 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
395 * This makes sure the 'class' is always set, and also is returned by
396 * this function for ease.
400 * @param string $fieldname Name of the field
401 * @param array $descriptor Input Descriptor, as described above
403 * @throws MWException
404 * @return string Name of a HTMLFormField subclass
406 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
407 if ( isset( $descriptor['class'] ) ) {
408 $class = $descriptor['class'];
409 } elseif ( isset( $descriptor['type'] ) ) {
410 $class = static::$typeMappings[$descriptor['type']];
411 $descriptor['class'] = $class;
417 throw new MWException( "Descriptor with no class for $fieldname: "
418 . print_r( $descriptor, true ) );
425 * Initialise a new Object for the field
427 * @param string $fieldname Name of the field
428 * @param array $descriptor Input Descriptor, as described above
429 * @param HTMLForm|null $parent Parent instance of HTMLForm
431 * @throws MWException
432 * @return HTMLFormField Instance of a subclass of HTMLFormField
434 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm
$parent = null ) {
435 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
437 $descriptor['fieldname'] = $fieldname;
439 $descriptor['parent'] = $parent;
442 # @todo This will throw a fatal error whenever someone try to use
443 # 'class' to feed a CSS class instead of 'cssclass'. Would be
444 # great to avoid the fatal error and show a nice error.
445 $obj = new $class( $descriptor );
451 * Prepare form for submission.
453 * @attention When doing method chaining, that should be the very last
454 * method call before displayForm().
456 * @throws MWException
457 * @return HTMLForm $this for chaining calls (since 1.20)
459 function prepareForm() {
460 # Check if we have the info we need
461 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
462 throw new MWException( "You must call setTitle() on an HTMLForm" );
465 # Load data from the request.
472 * Try submitting, with edit token check first
473 * @return Status|bool
475 function tryAuthorizedSubmit() {
479 if ( $this->getMethod() != 'post' ) {
480 $submit = true; // no session check needed
481 } elseif ( $this->getRequest()->wasPosted() ) {
482 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
483 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
484 // Session tokens for logged-out users have no security value.
485 // However, if the user gave one, check it in order to give a nice
486 // "session expired" error instead of "permission denied" or such.
487 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
494 $this->mWasSubmitted
= true;
495 $result = $this->trySubmit();
502 * The here's-one-I-made-earlier option: do the submission if
503 * posted, or display the form with or without funky validation
505 * @return bool|Status Whether submission was successful.
508 $this->prepareForm();
510 $result = $this->tryAuthorizedSubmit();
511 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
515 $this->displayForm( $result );
521 * Validate all the fields, and call the submission callback
522 * function if everything is kosher.
523 * @throws MWException
524 * @return bool|string|array|Status
525 * - Bool true or a good Status object indicates success,
526 * - Bool false indicates no submission was attempted,
527 * - Anything else indicates failure. The value may be a fatal Status
528 * object, an HTML string, or an array of arrays (message keys and
529 * params) or strings (message keys)
531 function trySubmit() {
532 $this->mWasSubmitted
= true;
534 # Check for cancelled submission
535 foreach ( $this->mFlatFields
as $fieldname => $field ) {
536 if ( !empty( $field->mParams
['nodata'] ) ) {
539 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
540 $this->mWasSubmitted
= false;
545 # Check for validation
546 foreach ( $this->mFlatFields
as $fieldname => $field ) {
547 if ( !empty( $field->mParams
['nodata'] ) ) {
550 if ( $field->isHidden( $this->mFieldData
) ) {
553 if ( $field->validate(
554 $this->mFieldData
[$fieldname],
558 return isset( $this->mValidationErrorMessage
)
559 ?
$this->mValidationErrorMessage
560 : array( 'htmlform-invalid-input' );
564 $callback = $this->mSubmitCallback
;
565 if ( !is_callable( $callback ) ) {
566 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
567 'setSubmitCallback() to set one.' );
570 $data = $this->filterDataForSubmit( $this->mFieldData
);
572 $res = call_user_func( $callback, $data, $this );
573 if ( $res === false ) {
574 $this->mWasSubmitted
= false;
581 * Test whether the form was considered to have been submitted or not, i.e.
582 * whether the last call to tryAuthorizedSubmit or trySubmit returned
585 * This will return false until HTMLForm::tryAuthorizedSubmit or
586 * HTMLForm::trySubmit is called.
591 function wasSubmitted() {
592 return $this->mWasSubmitted
;
596 * Set a callback to a function to do something with the form
597 * once it's been successfully validated.
599 * @param callable $cb The function will be passed the output from
600 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
601 * return as documented for HTMLForm::trySubmit
603 * @return HTMLForm $this for chaining calls (since 1.20)
605 function setSubmitCallback( $cb ) {
606 $this->mSubmitCallback
= $cb;
612 * Set a message to display on a validation error.
614 * @param string|array $msg String or Array of valid inputs to wfMessage()
615 * (so each entry can be either a String or Array)
617 * @return HTMLForm $this for chaining calls (since 1.20)
619 function setValidationErrorMessage( $msg ) {
620 $this->mValidationErrorMessage
= $msg;
626 * Set the introductory message, overwriting any existing message.
628 * @param string $msg Complete text of message to display
630 * @return HTMLForm $this for chaining calls (since 1.20)
632 function setIntro( $msg ) {
633 $this->setPreText( $msg );
639 * Set the introductory message, overwriting any existing message.
642 * @param string $msg Complete text of message to display
644 * @return HTMLForm $this for chaining calls (since 1.20)
646 function setPreText( $msg ) {
653 * Add introductory text.
655 * @param string $msg Complete text of message to display
657 * @return HTMLForm $this for chaining calls (since 1.20)
659 function addPreText( $msg ) {
666 * Add header text, inside the form.
668 * @param string $msg Complete text of message to display
669 * @param string|null $section The section to add the header to
671 * @return HTMLForm $this for chaining calls (since 1.20)
673 function addHeaderText( $msg, $section = null ) {
674 if ( is_null( $section ) ) {
675 $this->mHeader
.= $msg;
677 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
678 $this->mSectionHeaders
[$section] = '';
680 $this->mSectionHeaders
[$section] .= $msg;
687 * Set header text, inside the form.
690 * @param string $msg Complete text of message to display
691 * @param string|null $section The section to add the header to
693 * @return HTMLForm $this for chaining calls (since 1.20)
695 function setHeaderText( $msg, $section = null ) {
696 if ( is_null( $section ) ) {
697 $this->mHeader
= $msg;
699 $this->mSectionHeaders
[$section] = $msg;
706 * Add footer text, inside the form.
708 * @param string $msg Complete text of message to display
709 * @param string|null $section The section to add the footer text to
711 * @return HTMLForm $this for chaining calls (since 1.20)
713 function addFooterText( $msg, $section = null ) {
714 if ( is_null( $section ) ) {
715 $this->mFooter
.= $msg;
717 if ( !isset( $this->mSectionFooters
[$section] ) ) {
718 $this->mSectionFooters
[$section] = '';
720 $this->mSectionFooters
[$section] .= $msg;
727 * Set footer text, inside the form.
730 * @param string $msg Complete text of message to display
731 * @param string|null $section The section to add the footer text to
733 * @return HTMLForm $this for chaining calls (since 1.20)
735 function setFooterText( $msg, $section = null ) {
736 if ( is_null( $section ) ) {
737 $this->mFooter
= $msg;
739 $this->mSectionFooters
[$section] = $msg;
746 * Add text to the end of the display.
748 * @param string $msg Complete text of message to display
750 * @return HTMLForm $this for chaining calls (since 1.20)
752 function addPostText( $msg ) {
753 $this->mPost
.= $msg;
759 * Set text at the end of the display.
761 * @param string $msg Complete text of message to display
763 * @return HTMLForm $this for chaining calls (since 1.20)
765 function setPostText( $msg ) {
772 * Add a hidden field to the output
774 * @param string $name Field name. This will be used exactly as entered
775 * @param string $value Field value
776 * @param array $attribs
778 * @return HTMLForm $this for chaining calls (since 1.20)
780 public function addHiddenField( $name, $value, $attribs = array() ) {
781 $attribs +
= array( 'name' => $name );
782 $this->mHiddenFields
[] = array( $value, $attribs );
788 * Add an array of hidden fields to the output
792 * @param array $fields Associative array of fields to add;
793 * mapping names to their values
795 * @return HTMLForm $this for chaining calls
797 public function addHiddenFields( array $fields ) {
798 foreach ( $fields as $name => $value ) {
799 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
806 * Add a button to the form
808 * @param string $name Field name.
809 * @param string $value Field value
810 * @param string $id DOM id for the button (default: null)
811 * @param array $attribs
813 * @return HTMLForm $this for chaining calls (since 1.20)
815 public function addButton( $name, $value, $id = null, $attribs = null ) {
816 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
822 * Set the salt for the edit token.
824 * Only useful when the method is "post".
827 * @param string|array $salt Salt to use
828 * @return HTMLForm $this For chaining calls
830 public function setTokenSalt( $salt ) {
831 $this->mTokenSalt
= $salt;
837 * Display the form (sending to the context's OutputPage object), with an
838 * appropriate error message or stack of messages, and any validation errors, etc.
840 * @attention You should call prepareForm() before calling this function.
841 * Moreover, when doing method chaining this should be the very last method
842 * call just after prepareForm().
844 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
846 * @return void Nothing, should be last call
848 function displayForm( $submitResult ) {
849 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
853 * Returns the raw HTML generated by the form
855 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
859 function getHTML( $submitResult ) {
860 # For good measure (it is the default)
861 $this->getOutput()->preventClickjacking();
862 $this->getOutput()->addModules( 'mediawiki.htmlform' );
865 . $this->getErrors( $submitResult )
868 . $this->getHiddenFields()
869 . $this->getButtons()
872 $html = $this->wrapForm( $html );
874 return '' . $this->mPre
. $html . $this->mPost
;
878 * Get HTML attributes for the `<form>` tag.
881 protected function getFormAttributes() {
882 # Use multipart/form-data
883 $encType = $this->mUseMultipart
884 ?
'multipart/form-data'
885 : 'application/x-www-form-urlencoded';
888 'action' => $this->getAction(),
889 'method' => $this->getMethod(),
890 'class' => array( 'visualClear' ),
891 'enctype' => $encType,
893 if ( !empty( $this->mId
) ) {
894 $attribs['id'] = $this->mId
;
900 * Wrap the form innards in an actual "<form>" element
902 * @param string $html HTML contents to wrap.
904 * @return string Wrapped HTML.
906 function wrapForm( $html ) {
907 # Include a <fieldset> wrapper for style, if requested.
908 if ( $this->mWrapperLegend
!== false ) {
909 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
912 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
916 * Get the hidden fields that should go inside the form.
917 * @return string HTML.
919 function getHiddenFields() {
921 if ( $this->getMethod() == 'post' ) {
922 $html .= Html
::hidden(
924 $this->getUser()->getEditToken( $this->mTokenSalt
),
925 array( 'id' => 'wpEditToken' )
927 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
930 $articlePath = $this->getConfig()->get( 'ArticlePath' );
931 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
932 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
935 foreach ( $this->mHiddenFields
as $data ) {
936 list( $value, $attribs ) = $data;
937 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
944 * Get the submit and (potentially) reset buttons.
945 * @return string HTML.
947 function getButtons() {
949 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
951 if ( $this->mShowSubmit
) {
954 if ( isset( $this->mSubmitID
) ) {
955 $attribs['id'] = $this->mSubmitID
;
958 if ( isset( $this->mSubmitName
) ) {
959 $attribs['name'] = $this->mSubmitName
;
962 if ( isset( $this->mSubmitTooltip
) ) {
963 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
966 $attribs['class'] = array( 'mw-htmlform-submit' );
968 if ( $useMediaWikiUIEverywhere ) {
969 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
972 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
975 if ( $this->mShowReset
) {
976 $buttons .= Html
::element(
980 'value' => $this->msg( 'htmlform-reset' )->text(),
981 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
986 foreach ( $this->mButtons
as $button ) {
989 'name' => $button['name'],
990 'value' => $button['value']
993 if ( $button['attribs'] ) {
994 $attrs +
= $button['attribs'];
997 if ( isset( $button['id'] ) ) {
998 $attrs['id'] = $button['id'];
1001 if ( $useMediaWikiUIEverywhere ) {
1002 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1003 $attrs['class'][] = 'mw-ui-button';
1006 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1009 $html = Html
::rawElement( 'span',
1010 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1016 * Get the whole body of the form.
1019 function getBody() {
1020 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1024 * Format and display an error message stack.
1026 * @param string|array|Status $errors
1030 function getErrors( $errors ) {
1031 if ( $errors instanceof Status
) {
1032 if ( $errors->isOK() ) {
1035 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1037 } elseif ( is_array( $errors ) ) {
1038 $errorstr = $this->formatErrors( $errors );
1040 $errorstr = $errors;
1044 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1049 * Format a stack of error messages into a single HTML string
1051 * @param array $errors Array of message keys/values
1053 * @return string HTML, a "<ul>" list of errors
1055 public function formatErrors( $errors ) {
1058 foreach ( $errors as $error ) {
1059 if ( is_array( $error ) ) {
1060 $msg = array_shift( $error );
1066 $errorstr .= Html
::rawElement(
1069 $this->msg( $msg, $error )->parse()
1073 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1079 * Set the text for the submit button
1081 * @param string $t Plaintext
1083 * @return HTMLForm $this for chaining calls (since 1.20)
1085 function setSubmitText( $t ) {
1086 $this->mSubmitText
= $t;
1092 * Identify that the submit button in the form has a destructive action
1095 public function setSubmitDestructive() {
1096 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1100 * Identify that the submit button in the form has a progressive action
1103 public function setSubmitProgressive() {
1104 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1108 * Set the text for the submit button to a message
1111 * @param string|Message $msg Message key or Message object
1113 * @return HTMLForm $this for chaining calls (since 1.20)
1115 public function setSubmitTextMsg( $msg ) {
1116 if ( !$msg instanceof Message
) {
1117 $msg = $this->msg( $msg );
1119 $this->setSubmitText( $msg->text() );
1125 * Get the text for the submit button, either customised or a default.
1128 function getSubmitText() {
1129 return $this->mSubmitText
1130 ?
$this->mSubmitText
1131 : $this->msg( 'htmlform-submit' )->text();
1135 * @param string $name Submit button name
1137 * @return HTMLForm $this for chaining calls (since 1.20)
1139 public function setSubmitName( $name ) {
1140 $this->mSubmitName
= $name;
1146 * @param string $name Tooltip for the submit button
1148 * @return HTMLForm $this for chaining calls (since 1.20)
1150 public function setSubmitTooltip( $name ) {
1151 $this->mSubmitTooltip
= $name;
1157 * Set the id for the submit button.
1161 * @todo FIXME: Integrity of $t is *not* validated
1162 * @return HTMLForm $this for chaining calls (since 1.20)
1164 function setSubmitID( $t ) {
1165 $this->mSubmitID
= $t;
1171 * Stop a default submit button being shown for this form. This implies that an
1172 * alternate submit method must be provided manually.
1176 * @param bool $suppressSubmit Set to false to re-enable the button again
1178 * @return HTMLForm $this for chaining calls
1180 function suppressDefaultSubmit( $suppressSubmit = true ) {
1181 $this->mShowSubmit
= !$suppressSubmit;
1187 * Set the id of the \<table\> or outermost \<div\> element.
1191 * @param string $id New value of the id attribute, or "" to remove
1193 * @return HTMLForm $this for chaining calls
1195 public function setTableId( $id ) {
1196 $this->mTableId
= $id;
1202 * @param string $id DOM id for the form
1204 * @return HTMLForm $this for chaining calls (since 1.20)
1206 public function setId( $id ) {
1213 * Prompt the whole form to be wrapped in a "<fieldset>", with
1214 * this text as its "<legend>" element.
1216 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1217 * false for no <legend>
1220 * @return HTMLForm $this for chaining calls (since 1.20)
1222 public function setWrapperLegend( $legend ) {
1223 $this->mWrapperLegend
= $legend;
1229 * Prompt the whole form to be wrapped in a "<fieldset>", with
1230 * this message as its "<legend>" element.
1233 * @param string|Message $msg Message key or Message object
1235 * @return HTMLForm $this for chaining calls (since 1.20)
1237 public function setWrapperLegendMsg( $msg ) {
1238 if ( !$msg instanceof Message
) {
1239 $msg = $this->msg( $msg );
1241 $this->setWrapperLegend( $msg->text() );
1247 * Set the prefix for various default messages
1248 * @todo Currently only used for the "<fieldset>" legend on forms
1249 * with multiple sections; should be used elsewhere?
1253 * @return HTMLForm $this for chaining calls (since 1.20)
1255 function setMessagePrefix( $p ) {
1256 $this->mMessagePrefix
= $p;
1262 * Set the title for form submission
1264 * @param Title $t Title of page the form is on/should be posted to
1266 * @return HTMLForm $this for chaining calls (since 1.20)
1268 function setTitle( $t ) {
1278 function getTitle() {
1279 return $this->mTitle
=== false
1280 ?
$this->getContext()->getTitle()
1285 * Set the method used to submit the form
1287 * @param string $method
1289 * @return HTMLForm $this for chaining calls (since 1.20)
1291 public function setMethod( $method = 'post' ) {
1292 $this->mMethod
= $method;
1297 public function getMethod() {
1298 return $this->mMethod
;
1304 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1306 * @param string $sectionName ID attribute of the "<table>" tag for this
1307 * section, ignored if empty.
1308 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1309 * each subsection, ignored if empty.
1310 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1314 public function displaySection( $fields,
1316 $fieldsetIDPrefix = '',
1317 &$hasUserVisibleFields = false ) {
1318 $displayFormat = $this->getDisplayFormat();
1321 $subsectionHtml = '';
1324 // Conveniently, PHP method names are case-insensitive.
1325 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1327 foreach ( $fields as $key => $value ) {
1328 if ( $value instanceof HTMLFormField
) {
1329 $v = empty( $value->mParams
['nodata'] )
1330 ?
$this->mFieldData
[$key]
1331 : $value->getDefault();
1332 $html .= $value->$getFieldHtmlMethod( $v );
1334 $labelValue = trim( $value->getLabel() );
1335 if ( $labelValue != ' ' && $labelValue !== '' ) {
1339 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1340 get_class( $value ) !== 'HTMLApiField'
1342 $hasUserVisibleFields = true;
1344 } elseif ( is_array( $value ) ) {
1345 $subsectionHasVisibleFields = false;
1347 $this->displaySection( $value,
1349 "$fieldsetIDPrefix$key-",
1350 $subsectionHasVisibleFields );
1353 if ( $subsectionHasVisibleFields === true ) {
1354 // Display the section with various niceties.
1355 $hasUserVisibleFields = true;
1357 $legend = $this->getLegend( $key );
1359 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1360 $section = $this->mSectionHeaders
[$key] . $section;
1362 if ( isset( $this->mSectionFooters
[$key] ) ) {
1363 $section .= $this->mSectionFooters
[$key];
1366 $attributes = array();
1367 if ( $fieldsetIDPrefix ) {
1368 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1370 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1372 // Just return the inputs, nothing fancy.
1373 $subsectionHtml .= $section;
1378 if ( $displayFormat !== 'raw' ) {
1381 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1382 $classes[] = 'mw-htmlform-nolabel';
1386 'class' => implode( ' ', $classes ),
1389 if ( $sectionName ) {
1390 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1393 if ( $displayFormat === 'table' ) {
1394 $html = Html
::rawElement( 'table',
1396 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1397 } elseif ( $displayFormat === 'inline' ) {
1398 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1399 } elseif ( $displayFormat === 'ooui' ) {
1401 'classes' => $classes,
1403 if ( $sectionName ) {
1404 $config['id'] = Sanitizer
::escapeId( $sectionName );
1406 $fieldset = new OOUI\
FieldsetLayout( $config );
1407 // Ewww. We should pass this as $config['items'], but there might be string snippets.
1408 $fieldset->group
->appendContent( new OOUI\
HtmlSnippet( $html ) );
1409 $html = $fieldset->toString();
1411 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1415 if ( $this->mSubSectionBeforeFields
) {
1416 return $subsectionHtml . "\n" . $html;
1418 return $html . "\n" . $subsectionHtml;
1423 * Construct the form fields from the Descriptor array
1425 function loadData() {
1426 $fieldData = array();
1428 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1429 if ( !empty( $field->mParams
['nodata'] ) ) {
1431 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1432 $fieldData[$fieldname] = $field->getDefault();
1434 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1439 foreach ( $fieldData as $name => &$value ) {
1440 $field = $this->mFlatFields
[$name];
1441 $value = $field->filter( $value, $this->mFlatFields
);
1444 $this->mFieldData
= $fieldData;
1448 * Stop a reset button being shown for this form
1450 * @param bool $suppressReset Set to false to re-enable the button again
1452 * @return HTMLForm $this for chaining calls (since 1.20)
1454 function suppressReset( $suppressReset = true ) {
1455 $this->mShowReset
= !$suppressReset;
1461 * Overload this if you want to apply special filtration routines
1462 * to the form as a whole, after it's submitted but before it's
1465 * @param array $data
1469 function filterDataForSubmit( $data ) {
1474 * Get a string to go in the "<legend>" of a section fieldset.
1475 * Override this if you want something more complicated.
1477 * @param string $key
1481 public function getLegend( $key ) {
1482 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1486 * Set the value for the action attribute of the form.
1487 * When set to false (which is the default state), the set title is used.
1491 * @param string|bool $action
1493 * @return HTMLForm $this for chaining calls (since 1.20)
1495 public function setAction( $action ) {
1496 $this->mAction
= $action;
1502 * Get the value for the action attribute of the form.
1508 public function getAction() {
1509 // If an action is alredy provided, return it
1510 if ( $this->mAction
!== false ) {
1511 return $this->mAction
;
1514 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1515 // Check whether we are in GET mode and the ArticlePath contains a "?"
1516 // meaning that getLocalURL() would return something like "index.php?title=...".
1517 // As browser remove the query string before submitting GET forms,
1518 // it means that the title would be lost. In such case use wfScript() instead
1519 // and put title in an hidden field (see getHiddenFields()).
1520 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1524 return $this->getTitle()->getLocalURL();