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 'textwithbutton' => 'HTMLTextFieldWithButton',
129 'textarea' => 'HTMLTextAreaField',
130 'select' => 'HTMLSelectField',
131 'radio' => 'HTMLRadioField',
132 'multiselect' => 'HTMLMultiSelectField',
133 'limitselect' => 'HTMLSelectLimitField',
134 'check' => 'HTMLCheckField',
135 'toggle' => 'HTMLCheckField',
136 'int' => 'HTMLIntField',
137 'float' => 'HTMLFloatField',
138 'info' => 'HTMLInfoField',
139 'selectorother' => 'HTMLSelectOrOtherField',
140 'selectandother' => 'HTMLSelectAndOtherField',
141 'namespaceselect' => 'HTMLSelectNamespace',
142 'namespaceselectwithbutton' => 'HTMLSelectNamespaceWithButton',
143 'tagfilter' => 'HTMLTagFilter',
144 'submit' => 'HTMLSubmitField',
145 'hidden' => 'HTMLHiddenField',
146 'edittools' => 'HTMLEditTools',
147 'checkmatrix' => 'HTMLCheckMatrix',
148 'cloner' => 'HTMLFormFieldCloner',
149 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
150 // HTMLTextField will output the correct type="" attribute automagically.
151 // There are about four zillion other HTML5 input types, like range, but
152 // we don't use those at the moment, so no point in adding all of them.
153 'email' => 'HTMLTextField',
154 'password' => 'HTMLTextField',
155 'url' => 'HTMLTextField',
160 protected $mMessagePrefix;
162 /** @var HTMLFormField[] */
163 protected $mFlatFields;
165 protected $mFieldTree;
166 protected $mShowReset = false;
167 protected $mShowSubmit = true;
168 protected $mSubmitFlag = 'constructive';
170 protected $mSubmitCallback;
171 protected $mValidationErrorMessage;
173 protected $mPre = '';
174 protected $mHeader = '';
175 protected $mFooter = '';
176 protected $mSectionHeaders = array();
177 protected $mSectionFooters = array();
178 protected $mPost = '';
180 protected $mTableId = '';
182 protected $mSubmitID;
183 protected $mSubmitName;
184 protected $mSubmitText;
185 protected $mSubmitTooltip;
188 protected $mMethod = 'post';
189 protected $mWasSubmitted = false;
192 * Form action URL. false means we will use the URL to set Title
196 protected $mAction = false;
198 protected $mUseMultipart = false;
199 protected $mHiddenFields = array();
200 protected $mButtons = array();
202 protected $mWrapperLegend = false;
205 * Salt for the edit token.
208 protected $mTokenSalt = '';
211 * If true, sections that contain both fields and subsections will
212 * render their subsections before their fields.
214 * Subclasses may set this to false to render subsections after fields
217 protected $mSubSectionBeforeFields = true;
220 * Format in which to display form. For viable options,
221 * @see $availableDisplayFormats
224 protected $displayFormat = 'table';
227 * Available formats in which to display the form
230 protected $availableDisplayFormats = array(
238 * Available formats in which to display the form
241 protected $availableSubclassDisplayFormats = array(
247 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
249 * @param string $displayFormat
250 * @param mixed $arguments... Additional arguments to pass to the constructor.
253 public static function factory( $displayFormat/*, $arguments...*/ ) {
254 $arguments = func_get_args();
255 array_shift( $arguments );
257 switch ( $displayFormat ) {
259 $reflector = new ReflectionClass( 'VFormHTMLForm' );
260 return $reflector->newInstanceArgs( $arguments );
262 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
263 return $reflector->newInstanceArgs( $arguments );
265 $reflector = new ReflectionClass( 'HTMLForm' );
266 $form = $reflector->newInstanceArgs( $arguments );
267 $form->setDisplayFormat( $displayFormat );
273 * Build a new HTMLForm from an array of field attributes
275 * @param array $descriptor Array of Field constructs, as described above
276 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
277 * Obviates the need to call $form->setTitle()
278 * @param string $messagePrefix A prefix to go in front of default messages
280 public function __construct( $descriptor, /*IContextSource*/ $context = null,
283 if ( $context instanceof IContextSource
) {
284 $this->setContext( $context );
285 $this->mTitle
= false; // We don't need them to set a title
286 $this->mMessagePrefix
= $messagePrefix;
287 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
288 $this->mMessagePrefix
= $messagePrefix;
289 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
291 // it's actually $messagePrefix
292 $this->mMessagePrefix
= $context;
295 // Evil hack for mobile :(
297 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
298 && $this->displayFormat
=== 'table'
300 $this->displayFormat
= 'div';
303 // Expand out into a tree.
304 $loadedDescriptor = array();
305 $this->mFlatFields
= array();
307 foreach ( $descriptor as $fieldname => $info ) {
308 $section = isset( $info['section'] )
312 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
313 $this->mUseMultipart
= true;
316 $field = static::loadInputFromParameters( $fieldname, $info, $this );
318 $setSection =& $loadedDescriptor;
320 $sectionParts = explode( '/', $section );
322 while ( count( $sectionParts ) ) {
323 $newName = array_shift( $sectionParts );
325 if ( !isset( $setSection[$newName] ) ) {
326 $setSection[$newName] = array();
329 $setSection =& $setSection[$newName];
333 $setSection[$fieldname] = $field;
334 $this->mFlatFields
[$fieldname] = $field;
337 $this->mFieldTree
= $loadedDescriptor;
341 * Set format in which to display the form
343 * @param string $format The name of the format to use, must be one of
344 * $this->availableDisplayFormats
346 * @throws MWException
348 * @return HTMLForm $this for chaining calls (since 1.20)
350 public function setDisplayFormat( $format ) {
352 in_array( $format, $this->availableSubclassDisplayFormats
) ||
353 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
355 throw new MWException( 'Cannot change display format after creation, ' .
356 'use HTMLForm::factory() instead' );
359 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
360 throw new MWException( 'Display format must be one of ' .
361 print_r( $this->availableDisplayFormats
, true ) );
364 // Evil hack for mobile :(
365 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
369 $this->displayFormat
= $format;
375 * Getter for displayFormat
379 public function getDisplayFormat() {
380 return $this->displayFormat
;
384 * Test if displayFormat is 'vform'
386 * @deprecated since 1.25
389 public function isVForm() {
390 wfDeprecated( __METHOD__
, '1.25' );
395 * Get the HTMLFormField subclass for this descriptor.
397 * The descriptor can be passed either 'class' which is the name of
398 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
399 * This makes sure the 'class' is always set, and also is returned by
400 * this function for ease.
404 * @param string $fieldname Name of the field
405 * @param array $descriptor Input Descriptor, as described above
407 * @throws MWException
408 * @return string Name of a HTMLFormField subclass
410 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
411 if ( isset( $descriptor['class'] ) ) {
412 $class = $descriptor['class'];
413 } elseif ( isset( $descriptor['type'] ) ) {
414 $class = static::$typeMappings[$descriptor['type']];
415 $descriptor['class'] = $class;
421 throw new MWException( "Descriptor with no class for $fieldname: "
422 . print_r( $descriptor, true ) );
429 * Initialise a new Object for the field
431 * @param string $fieldname Name of the field
432 * @param array $descriptor Input Descriptor, as described above
433 * @param HTMLForm|null $parent Parent instance of HTMLForm
435 * @throws MWException
436 * @return HTMLFormField Instance of a subclass of HTMLFormField
438 public static function loadInputFromParameters( $fieldname, $descriptor,
439 HTMLForm
$parent = null
441 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
443 $descriptor['fieldname'] = $fieldname;
445 $descriptor['parent'] = $parent;
448 # @todo This will throw a fatal error whenever someone try to use
449 # 'class' to feed a CSS class instead of 'cssclass'. Would be
450 # great to avoid the fatal error and show a nice error.
451 $obj = new $class( $descriptor );
457 * Prepare form for submission.
459 * @attention When doing method chaining, that should be the very last
460 * method call before displayForm().
462 * @throws MWException
463 * @return HTMLForm $this for chaining calls (since 1.20)
465 function prepareForm() {
466 # Check if we have the info we need
467 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
468 throw new MWException( "You must call setTitle() on an HTMLForm" );
471 # Load data from the request.
478 * Try submitting, with edit token check first
479 * @return Status|bool
481 function tryAuthorizedSubmit() {
485 if ( $this->getMethod() != 'post' ) {
486 $submit = true; // no session check needed
487 } elseif ( $this->getRequest()->wasPosted() ) {
488 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
489 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
490 // Session tokens for logged-out users have no security value.
491 // However, if the user gave one, check it in order to give a nice
492 // "session expired" error instead of "permission denied" or such.
493 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
500 $this->mWasSubmitted
= true;
501 $result = $this->trySubmit();
508 * The here's-one-I-made-earlier option: do the submission if
509 * posted, or display the form with or without funky validation
511 * @return bool|Status Whether submission was successful.
514 $this->prepareForm();
516 $result = $this->tryAuthorizedSubmit();
517 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
521 $this->displayForm( $result );
527 * Validate all the fields, and call the submission callback
528 * function if everything is kosher.
529 * @throws MWException
530 * @return bool|string|array|Status
531 * - Bool true or a good Status object indicates success,
532 * - Bool false indicates no submission was attempted,
533 * - Anything else indicates failure. The value may be a fatal Status
534 * object, an HTML string, or an array of arrays (message keys and
535 * params) or strings (message keys)
537 function trySubmit() {
538 $this->mWasSubmitted
= true;
540 # Check for cancelled submission
541 foreach ( $this->mFlatFields
as $fieldname => $field ) {
542 if ( !empty( $field->mParams
['nodata'] ) ) {
545 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
546 $this->mWasSubmitted
= false;
551 # Check for validation
552 foreach ( $this->mFlatFields
as $fieldname => $field ) {
553 if ( !empty( $field->mParams
['nodata'] ) ) {
556 if ( $field->isHidden( $this->mFieldData
) ) {
559 if ( $field->validate(
560 $this->mFieldData
[$fieldname],
564 return isset( $this->mValidationErrorMessage
)
565 ?
$this->mValidationErrorMessage
566 : array( 'htmlform-invalid-input' );
570 $callback = $this->mSubmitCallback
;
571 if ( !is_callable( $callback ) ) {
572 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
573 'setSubmitCallback() to set one.' );
576 $data = $this->filterDataForSubmit( $this->mFieldData
);
578 $res = call_user_func( $callback, $data, $this );
579 if ( $res === false ) {
580 $this->mWasSubmitted
= false;
587 * Test whether the form was considered to have been submitted or not, i.e.
588 * whether the last call to tryAuthorizedSubmit or trySubmit returned
591 * This will return false until HTMLForm::tryAuthorizedSubmit or
592 * HTMLForm::trySubmit is called.
597 function wasSubmitted() {
598 return $this->mWasSubmitted
;
602 * Set a callback to a function to do something with the form
603 * once it's been successfully validated.
605 * @param callable $cb The function will be passed the output from
606 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
607 * return as documented for HTMLForm::trySubmit
609 * @return HTMLForm $this for chaining calls (since 1.20)
611 function setSubmitCallback( $cb ) {
612 $this->mSubmitCallback
= $cb;
618 * Set a message to display on a validation error.
620 * @param string|array $msg String or Array of valid inputs to wfMessage()
621 * (so each entry can be either a String or Array)
623 * @return HTMLForm $this for chaining calls (since 1.20)
625 function setValidationErrorMessage( $msg ) {
626 $this->mValidationErrorMessage
= $msg;
632 * Set the introductory message, overwriting any existing message.
634 * @param string $msg Complete text of message to display
636 * @return HTMLForm $this for chaining calls (since 1.20)
638 function setIntro( $msg ) {
639 $this->setPreText( $msg );
645 * Set the introductory message, overwriting any existing message.
648 * @param string $msg Complete text of message to display
650 * @return HTMLForm $this for chaining calls (since 1.20)
652 function setPreText( $msg ) {
659 * Add introductory text.
661 * @param string $msg Complete text of message to display
663 * @return HTMLForm $this for chaining calls (since 1.20)
665 function addPreText( $msg ) {
672 * Add header text, inside the form.
674 * @param string $msg Complete text of message to display
675 * @param string|null $section The section to add the header to
677 * @return HTMLForm $this for chaining calls (since 1.20)
679 function addHeaderText( $msg, $section = null ) {
680 if ( is_null( $section ) ) {
681 $this->mHeader
.= $msg;
683 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
684 $this->mSectionHeaders
[$section] = '';
686 $this->mSectionHeaders
[$section] .= $msg;
693 * Set header text, inside the form.
696 * @param string $msg Complete text of message to display
697 * @param string|null $section The section to add the header to
699 * @return HTMLForm $this for chaining calls (since 1.20)
701 function setHeaderText( $msg, $section = null ) {
702 if ( is_null( $section ) ) {
703 $this->mHeader
= $msg;
705 $this->mSectionHeaders
[$section] = $msg;
712 * Add footer text, inside the form.
714 * @param string $msg Complete text of message to display
715 * @param string|null $section The section to add the footer text to
717 * @return HTMLForm $this for chaining calls (since 1.20)
719 function addFooterText( $msg, $section = null ) {
720 if ( is_null( $section ) ) {
721 $this->mFooter
.= $msg;
723 if ( !isset( $this->mSectionFooters
[$section] ) ) {
724 $this->mSectionFooters
[$section] = '';
726 $this->mSectionFooters
[$section] .= $msg;
733 * Set footer text, inside the form.
736 * @param string $msg Complete text of message to display
737 * @param string|null $section The section to add the footer text to
739 * @return HTMLForm $this for chaining calls (since 1.20)
741 function setFooterText( $msg, $section = null ) {
742 if ( is_null( $section ) ) {
743 $this->mFooter
= $msg;
745 $this->mSectionFooters
[$section] = $msg;
752 * Add text to the end of the display.
754 * @param string $msg Complete text of message to display
756 * @return HTMLForm $this for chaining calls (since 1.20)
758 function addPostText( $msg ) {
759 $this->mPost
.= $msg;
765 * Set text at the end of the display.
767 * @param string $msg Complete text of message to display
769 * @return HTMLForm $this for chaining calls (since 1.20)
771 function setPostText( $msg ) {
778 * Add a hidden field to the output
780 * @param string $name Field name. This will be used exactly as entered
781 * @param string $value Field value
782 * @param array $attribs
784 * @return HTMLForm $this for chaining calls (since 1.20)
786 public function addHiddenField( $name, $value, $attribs = array() ) {
787 $attribs +
= array( 'name' => $name );
788 $this->mHiddenFields
[] = array( $value, $attribs );
794 * Add an array of hidden fields to the output
798 * @param array $fields Associative array of fields to add;
799 * mapping names to their values
801 * @return HTMLForm $this for chaining calls
803 public function addHiddenFields( array $fields ) {
804 foreach ( $fields as $name => $value ) {
805 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
812 * Add a button to the form
814 * @param string $name Field name.
815 * @param string $value Field value
816 * @param string $id DOM id for the button (default: null)
817 * @param array $attribs
819 * @return HTMLForm $this for chaining calls (since 1.20)
821 public function addButton( $name, $value, $id = null, $attribs = null ) {
822 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
828 * Set the salt for the edit token.
830 * Only useful when the method is "post".
833 * @param string|array $salt Salt to use
834 * @return HTMLForm $this For chaining calls
836 public function setTokenSalt( $salt ) {
837 $this->mTokenSalt
= $salt;
843 * Display the form (sending to the context's OutputPage object), with an
844 * appropriate error message or stack of messages, and any validation errors, etc.
846 * @attention You should call prepareForm() before calling this function.
847 * Moreover, when doing method chaining this should be the very last method
848 * call just after prepareForm().
850 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
852 * @return void Nothing, should be last call
854 function displayForm( $submitResult ) {
855 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
859 * Returns the raw HTML generated by the form
861 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
865 function getHTML( $submitResult ) {
866 # For good measure (it is the default)
867 $this->getOutput()->preventClickjacking();
868 $this->getOutput()->addModules( 'mediawiki.htmlform' );
871 . $this->getErrors( $submitResult )
874 . $this->getHiddenFields()
875 . $this->getButtons()
878 $html = $this->wrapForm( $html );
880 return '' . $this->mPre
. $html . $this->mPost
;
884 * Get HTML attributes for the `<form>` tag.
887 protected function getFormAttributes() {
888 # Use multipart/form-data
889 $encType = $this->mUseMultipart
890 ?
'multipart/form-data'
891 : 'application/x-www-form-urlencoded';
894 'action' => $this->getAction(),
895 'method' => $this->getMethod(),
896 'class' => array( 'visualClear' ),
897 'enctype' => $encType,
899 if ( !empty( $this->mId
) ) {
900 $attribs['id'] = $this->mId
;
906 * Wrap the form innards in an actual "<form>" element
908 * @param string $html HTML contents to wrap.
910 * @return string Wrapped HTML.
912 function wrapForm( $html ) {
913 # Include a <fieldset> wrapper for style, if requested.
914 if ( $this->mWrapperLegend
!== false ) {
915 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
918 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
922 * Get the hidden fields that should go inside the form.
923 * @return string HTML.
925 function getHiddenFields() {
927 if ( $this->getMethod() == 'post' ) {
928 $html .= Html
::hidden(
930 $this->getUser()->getEditToken( $this->mTokenSalt
),
931 array( 'id' => 'wpEditToken' )
933 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
936 $articlePath = $this->getConfig()->get( 'ArticlePath' );
937 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
938 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
941 foreach ( $this->mHiddenFields
as $data ) {
942 list( $value, $attribs ) = $data;
943 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
950 * Get the submit and (potentially) reset buttons.
951 * @return string HTML.
953 function getButtons() {
955 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
957 if ( $this->mShowSubmit
) {
960 if ( isset( $this->mSubmitID
) ) {
961 $attribs['id'] = $this->mSubmitID
;
964 if ( isset( $this->mSubmitName
) ) {
965 $attribs['name'] = $this->mSubmitName
;
968 if ( isset( $this->mSubmitTooltip
) ) {
969 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
972 $attribs['class'] = array( 'mw-htmlform-submit' );
974 if ( $useMediaWikiUIEverywhere ) {
975 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-' . $this->mSubmitFlag
);
978 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
981 if ( $this->mShowReset
) {
982 $buttons .= Html
::element(
986 'value' => $this->msg( 'htmlform-reset' )->text(),
987 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
992 foreach ( $this->mButtons
as $button ) {
995 'name' => $button['name'],
996 'value' => $button['value']
999 if ( $button['attribs'] ) {
1000 $attrs +
= $button['attribs'];
1003 if ( isset( $button['id'] ) ) {
1004 $attrs['id'] = $button['id'];
1007 if ( $useMediaWikiUIEverywhere ) {
1008 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1009 $attrs['class'][] = 'mw-ui-button';
1012 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1015 $html = Html
::rawElement( 'span',
1016 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1022 * Get the whole body of the form.
1025 function getBody() {
1026 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1030 * Format and display an error message stack.
1032 * @param string|array|Status $errors
1036 function getErrors( $errors ) {
1037 if ( $errors instanceof Status
) {
1038 if ( $errors->isOK() ) {
1041 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1043 } elseif ( is_array( $errors ) ) {
1044 $errorstr = $this->formatErrors( $errors );
1046 $errorstr = $errors;
1050 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1055 * Format a stack of error messages into a single HTML string
1057 * @param array $errors Array of message keys/values
1059 * @return string HTML, a "<ul>" list of errors
1061 public function formatErrors( $errors ) {
1064 foreach ( $errors as $error ) {
1065 if ( is_array( $error ) ) {
1066 $msg = array_shift( $error );
1072 $errorstr .= Html
::rawElement(
1075 $this->msg( $msg, $error )->parse()
1079 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1085 * Set the text for the submit button
1087 * @param string $t Plaintext
1089 * @return HTMLForm $this for chaining calls (since 1.20)
1091 function setSubmitText( $t ) {
1092 $this->mSubmitText
= $t;
1098 * Identify that the submit button in the form has a destructive action
1101 public function setSubmitDestructive() {
1102 $this->mSubmitFlag
= 'destructive';
1106 * Identify that the submit button in the form has a progressive action
1109 public function setSubmitProgressive() {
1110 $this->mSubmitFlag
= 'progressive';
1114 * Set the text for the submit button to a message
1117 * @param string|Message $msg Message key or Message object
1119 * @return HTMLForm $this for chaining calls (since 1.20)
1121 public function setSubmitTextMsg( $msg ) {
1122 if ( !$msg instanceof Message
) {
1123 $msg = $this->msg( $msg );
1125 $this->setSubmitText( $msg->text() );
1131 * Get the text for the submit button, either customised or a default.
1134 function getSubmitText() {
1135 return $this->mSubmitText
1136 ?
$this->mSubmitText
1137 : $this->msg( 'htmlform-submit' )->text();
1141 * @param string $name Submit button name
1143 * @return HTMLForm $this for chaining calls (since 1.20)
1145 public function setSubmitName( $name ) {
1146 $this->mSubmitName
= $name;
1152 * @param string $name Tooltip for the submit button
1154 * @return HTMLForm $this for chaining calls (since 1.20)
1156 public function setSubmitTooltip( $name ) {
1157 $this->mSubmitTooltip
= $name;
1163 * Set the id for the submit button.
1167 * @todo FIXME: Integrity of $t is *not* validated
1168 * @return HTMLForm $this for chaining calls (since 1.20)
1170 function setSubmitID( $t ) {
1171 $this->mSubmitID
= $t;
1177 * Stop a default submit button being shown for this form. This implies that an
1178 * alternate submit method must be provided manually.
1182 * @param bool $suppressSubmit Set to false to re-enable the button again
1184 * @return HTMLForm $this for chaining calls
1186 function suppressDefaultSubmit( $suppressSubmit = true ) {
1187 $this->mShowSubmit
= !$suppressSubmit;
1193 * Set the id of the \<table\> or outermost \<div\> element.
1197 * @param string $id New value of the id attribute, or "" to remove
1199 * @return HTMLForm $this for chaining calls
1201 public function setTableId( $id ) {
1202 $this->mTableId
= $id;
1208 * @param string $id DOM id for the form
1210 * @return HTMLForm $this for chaining calls (since 1.20)
1212 public function setId( $id ) {
1219 * Prompt the whole form to be wrapped in a "<fieldset>", with
1220 * this text as its "<legend>" element.
1222 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1223 * false for no <legend>
1226 * @return HTMLForm $this for chaining calls (since 1.20)
1228 public function setWrapperLegend( $legend ) {
1229 $this->mWrapperLegend
= $legend;
1235 * Prompt the whole form to be wrapped in a "<fieldset>", with
1236 * this message as its "<legend>" element.
1239 * @param string|Message $msg Message key or Message object
1241 * @return HTMLForm $this for chaining calls (since 1.20)
1243 public function setWrapperLegendMsg( $msg ) {
1244 if ( !$msg instanceof Message
) {
1245 $msg = $this->msg( $msg );
1247 $this->setWrapperLegend( $msg->text() );
1253 * Set the prefix for various default messages
1254 * @todo Currently only used for the "<fieldset>" legend on forms
1255 * with multiple sections; should be used elsewhere?
1259 * @return HTMLForm $this for chaining calls (since 1.20)
1261 function setMessagePrefix( $p ) {
1262 $this->mMessagePrefix
= $p;
1268 * Set the title for form submission
1270 * @param Title $t Title of page the form is on/should be posted to
1272 * @return HTMLForm $this for chaining calls (since 1.20)
1274 function setTitle( $t ) {
1284 function getTitle() {
1285 return $this->mTitle
=== false
1286 ?
$this->getContext()->getTitle()
1291 * Set the method used to submit the form
1293 * @param string $method
1295 * @return HTMLForm $this for chaining calls (since 1.20)
1297 public function setMethod( $method = 'post' ) {
1298 $this->mMethod
= $method;
1303 public function getMethod() {
1304 return $this->mMethod
;
1310 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1312 * @param string $sectionName ID attribute of the "<table>" tag for this
1313 * section, ignored if empty.
1314 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1315 * each subsection, ignored if empty.
1316 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1320 public function displaySection( $fields,
1322 $fieldsetIDPrefix = '',
1323 &$hasUserVisibleFields = false ) {
1324 $displayFormat = $this->getDisplayFormat();
1327 $subsectionHtml = '';
1330 // Conveniently, PHP method names are case-insensitive.
1331 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1333 foreach ( $fields as $key => $value ) {
1334 if ( $value instanceof HTMLFormField
) {
1335 $v = empty( $value->mParams
['nodata'] )
1336 ?
$this->mFieldData
[$key]
1337 : $value->getDefault();
1338 $html .= $value->$getFieldHtmlMethod( $v );
1340 $labelValue = trim( $value->getLabel() );
1341 if ( $labelValue != ' ' && $labelValue !== '' ) {
1345 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1346 get_class( $value ) !== 'HTMLApiField'
1348 $hasUserVisibleFields = true;
1350 } elseif ( is_array( $value ) ) {
1351 $subsectionHasVisibleFields = false;
1353 $this->displaySection( $value,
1355 "$fieldsetIDPrefix$key-",
1356 $subsectionHasVisibleFields );
1359 if ( $subsectionHasVisibleFields === true ) {
1360 // Display the section with various niceties.
1361 $hasUserVisibleFields = true;
1363 $legend = $this->getLegend( $key );
1365 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1366 $section = $this->mSectionHeaders
[$key] . $section;
1368 if ( isset( $this->mSectionFooters
[$key] ) ) {
1369 $section .= $this->mSectionFooters
[$key];
1372 $attributes = array();
1373 if ( $fieldsetIDPrefix ) {
1374 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1376 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1378 // Just return the inputs, nothing fancy.
1379 $subsectionHtml .= $section;
1384 if ( $displayFormat !== 'raw' ) {
1387 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1388 $classes[] = 'mw-htmlform-nolabel';
1392 'class' => implode( ' ', $classes ),
1395 if ( $sectionName ) {
1396 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1399 if ( $displayFormat === 'table' ) {
1400 $html = Html
::rawElement( 'table',
1402 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1403 } elseif ( $displayFormat === 'inline' ) {
1404 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1405 } elseif ( $displayFormat === 'ooui' ) {
1407 'classes' => $classes,
1409 if ( $sectionName ) {
1410 $config['id'] = Sanitizer
::escapeId( $sectionName );
1412 $fieldset = new OOUI\
FieldsetLayout( $config );
1413 // Ewww. We should pass this as $config['items'], but there might be string snippets.
1414 $fieldset->group
->appendContent( new OOUI\
HtmlSnippet( $html ) );
1415 $html = $fieldset->toString();
1417 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1421 if ( $this->mSubSectionBeforeFields
) {
1422 return $subsectionHtml . "\n" . $html;
1424 return $html . "\n" . $subsectionHtml;
1429 * Construct the form fields from the Descriptor array
1431 function loadData() {
1432 $fieldData = array();
1434 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1435 if ( !empty( $field->mParams
['nodata'] ) ) {
1437 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1438 $fieldData[$fieldname] = $field->getDefault();
1440 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1445 foreach ( $fieldData as $name => &$value ) {
1446 $field = $this->mFlatFields
[$name];
1447 $value = $field->filter( $value, $this->mFlatFields
);
1450 $this->mFieldData
= $fieldData;
1454 * Stop a reset button being shown for this form
1456 * @param bool $suppressReset Set to false to re-enable the button again
1458 * @return HTMLForm $this for chaining calls (since 1.20)
1460 function suppressReset( $suppressReset = true ) {
1461 $this->mShowReset
= !$suppressReset;
1467 * Overload this if you want to apply special filtration routines
1468 * to the form as a whole, after it's submitted but before it's
1471 * @param array $data
1475 function filterDataForSubmit( $data ) {
1480 * Get a string to go in the "<legend>" of a section fieldset.
1481 * Override this if you want something more complicated.
1483 * @param string $key
1487 public function getLegend( $key ) {
1488 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1492 * Set the value for the action attribute of the form.
1493 * When set to false (which is the default state), the set title is used.
1497 * @param string|bool $action
1499 * @return HTMLForm $this for chaining calls (since 1.20)
1501 public function setAction( $action ) {
1502 $this->mAction
= $action;
1508 * Get the value for the action attribute of the form.
1514 public function getAction() {
1515 // If an action is alredy provided, return it
1516 if ( $this->mAction
!== false ) {
1517 return $this->mAction
;
1520 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1521 // Check whether we are in GET mode and the ArticlePath contains a "?"
1522 // meaning that getLocalURL() would return something like "index.php?title=...".
1523 // As browser remove the query string before submitting GET forms,
1524 // it means that the title would be lost. In such case use wfScript() instead
1525 // and put title in an hidden field (see getHiddenFields()).
1526 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1530 return $this->getTitle()->getLocalURL();