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 * @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( 'OOUIHTMLForm' );
261 return $reflector->newInstanceArgs( $arguments );
263 $reflector = new ReflectionClass( 'HTMLForm' );
264 $form = $reflector->newInstanceArgs( $arguments );
265 $form->setDisplayFormat( $displayFormat );
271 * Build a new HTMLForm from an array of field attributes
273 * @param array $descriptor Array of Field constructs, as described above
274 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
275 * Obviates the need to call $form->setTitle()
276 * @param string $messagePrefix A prefix to go in front of default messages
278 public function __construct( $descriptor, /*IContextSource*/ $context = null,
281 if ( $context instanceof IContextSource
) {
282 $this->setContext( $context );
283 $this->mTitle
= false; // We don't need them to set a title
284 $this->mMessagePrefix
= $messagePrefix;
285 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
286 $this->mMessagePrefix
= $messagePrefix;
287 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
289 // it's actually $messagePrefix
290 $this->mMessagePrefix
= $context;
293 // Evil hack for mobile :(
295 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
296 && $this->displayFormat
=== 'table'
298 $this->displayFormat
= 'div';
301 // Expand out into a tree.
302 $loadedDescriptor = array();
303 $this->mFlatFields
= array();
305 foreach ( $descriptor as $fieldname => $info ) {
306 $section = isset( $info['section'] )
310 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
311 $this->mUseMultipart
= true;
314 $field = static::loadInputFromParameters( $fieldname, $info, $this );
316 $setSection =& $loadedDescriptor;
318 $sectionParts = explode( '/', $section );
320 while ( count( $sectionParts ) ) {
321 $newName = array_shift( $sectionParts );
323 if ( !isset( $setSection[$newName] ) ) {
324 $setSection[$newName] = array();
327 $setSection =& $setSection[$newName];
331 $setSection[$fieldname] = $field;
332 $this->mFlatFields
[$fieldname] = $field;
335 $this->mFieldTree
= $loadedDescriptor;
339 * Set format in which to display the form
341 * @param string $format The name of the format to use, must be one of
342 * $this->availableDisplayFormats
344 * @throws MWException
346 * @return HTMLForm $this for chaining calls (since 1.20)
348 public function setDisplayFormat( $format ) {
350 in_array( $format, $this->availableSubclassDisplayFormats
) ||
351 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
353 throw new MWException( 'Cannot change display format after creation, ' .
354 'use HTMLForm::factory() instead' );
357 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
358 throw new MWException( 'Display format must be one of ' .
359 print_r( $this->availableDisplayFormats
, true ) );
362 // Evil hack for mobile :(
363 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
367 $this->displayFormat
= $format;
373 * Getter for displayFormat
377 public function getDisplayFormat() {
378 return $this->displayFormat
;
382 * Test if displayFormat is 'vform'
384 * @deprecated since 1.25
387 public function isVForm() {
388 wfDeprecated( __METHOD__
, '1.25' );
393 * Get the HTMLFormField subclass for this descriptor.
395 * The descriptor can be passed either 'class' which is the name of
396 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
397 * This makes sure the 'class' is always set, and also is returned by
398 * this function for ease.
402 * @param string $fieldname Name of the field
403 * @param array $descriptor Input Descriptor, as described above
405 * @throws MWException
406 * @return string Name of a HTMLFormField subclass
408 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
409 if ( isset( $descriptor['class'] ) ) {
410 $class = $descriptor['class'];
411 } elseif ( isset( $descriptor['type'] ) ) {
412 $class = static::$typeMappings[$descriptor['type']];
413 $descriptor['class'] = $class;
419 throw new MWException( "Descriptor with no class for $fieldname: "
420 . print_r( $descriptor, true ) );
427 * Initialise a new Object for the field
429 * @param string $fieldname Name of the field
430 * @param array $descriptor Input Descriptor, as described above
431 * @param HTMLForm|null $parent Parent instance of HTMLForm
433 * @throws MWException
434 * @return HTMLFormField Instance of a subclass of HTMLFormField
436 public static function loadInputFromParameters( $fieldname, $descriptor,
437 HTMLForm
$parent = null
439 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
441 $descriptor['fieldname'] = $fieldname;
443 $descriptor['parent'] = $parent;
446 # @todo This will throw a fatal error whenever someone try to use
447 # 'class' to feed a CSS class instead of 'cssclass'. Would be
448 # great to avoid the fatal error and show a nice error.
449 $obj = new $class( $descriptor );
455 * Prepare form for submission.
457 * @attention When doing method chaining, that should be the very last
458 * method call before displayForm().
460 * @throws MWException
461 * @return HTMLForm $this for chaining calls (since 1.20)
463 function prepareForm() {
464 # Check if we have the info we need
465 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
466 throw new MWException( "You must call setTitle() on an HTMLForm" );
469 # Load data from the request.
476 * Try submitting, with edit token check first
477 * @return Status|bool
479 function tryAuthorizedSubmit() {
483 if ( $this->getMethod() != 'post' ) {
484 $submit = true; // no session check needed
485 } elseif ( $this->getRequest()->wasPosted() ) {
486 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
487 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
488 // Session tokens for logged-out users have no security value.
489 // However, if the user gave one, check it in order to give a nice
490 // "session expired" error instead of "permission denied" or such.
491 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
498 $this->mWasSubmitted
= true;
499 $result = $this->trySubmit();
506 * The here's-one-I-made-earlier option: do the submission if
507 * posted, or display the form with or without funky validation
509 * @return bool|Status Whether submission was successful.
512 $this->prepareForm();
514 $result = $this->tryAuthorizedSubmit();
515 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
519 $this->displayForm( $result );
525 * Validate all the fields, and call the submission callback
526 * function if everything is kosher.
527 * @throws MWException
528 * @return bool|string|array|Status
529 * - Bool true or a good Status object indicates success,
530 * - Bool false indicates no submission was attempted,
531 * - Anything else indicates failure. The value may be a fatal Status
532 * object, an HTML string, or an array of arrays (message keys and
533 * params) or strings (message keys)
535 function trySubmit() {
536 $this->mWasSubmitted
= true;
538 # Check for cancelled submission
539 foreach ( $this->mFlatFields
as $fieldname => $field ) {
540 if ( !empty( $field->mParams
['nodata'] ) ) {
543 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
544 $this->mWasSubmitted
= false;
549 # Check for validation
550 foreach ( $this->mFlatFields
as $fieldname => $field ) {
551 if ( !empty( $field->mParams
['nodata'] ) ) {
554 if ( $field->isHidden( $this->mFieldData
) ) {
557 if ( $field->validate(
558 $this->mFieldData
[$fieldname],
562 return isset( $this->mValidationErrorMessage
)
563 ?
$this->mValidationErrorMessage
564 : array( 'htmlform-invalid-input' );
568 $callback = $this->mSubmitCallback
;
569 if ( !is_callable( $callback ) ) {
570 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
571 'setSubmitCallback() to set one.' );
574 $data = $this->filterDataForSubmit( $this->mFieldData
);
576 $res = call_user_func( $callback, $data, $this );
577 if ( $res === false ) {
578 $this->mWasSubmitted
= false;
585 * Test whether the form was considered to have been submitted or not, i.e.
586 * whether the last call to tryAuthorizedSubmit or trySubmit returned
589 * This will return false until HTMLForm::tryAuthorizedSubmit or
590 * HTMLForm::trySubmit is called.
595 function wasSubmitted() {
596 return $this->mWasSubmitted
;
600 * Set a callback to a function to do something with the form
601 * once it's been successfully validated.
603 * @param callable $cb The function will be passed the output from
604 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
605 * return as documented for HTMLForm::trySubmit
607 * @return HTMLForm $this for chaining calls (since 1.20)
609 function setSubmitCallback( $cb ) {
610 $this->mSubmitCallback
= $cb;
616 * Set a message to display on a validation error.
618 * @param string|array $msg String or Array of valid inputs to wfMessage()
619 * (so each entry can be either a String or Array)
621 * @return HTMLForm $this for chaining calls (since 1.20)
623 function setValidationErrorMessage( $msg ) {
624 $this->mValidationErrorMessage
= $msg;
630 * Set the introductory message, overwriting any existing message.
632 * @param string $msg Complete text of message to display
634 * @return HTMLForm $this for chaining calls (since 1.20)
636 function setIntro( $msg ) {
637 $this->setPreText( $msg );
643 * Set the introductory message, overwriting any existing message.
646 * @param string $msg Complete text of message to display
648 * @return HTMLForm $this for chaining calls (since 1.20)
650 function setPreText( $msg ) {
657 * Add introductory text.
659 * @param string $msg Complete text of message to display
661 * @return HTMLForm $this for chaining calls (since 1.20)
663 function addPreText( $msg ) {
670 * Add header text, inside the form.
672 * @param string $msg Complete text of message to display
673 * @param string|null $section The section to add the header to
675 * @return HTMLForm $this for chaining calls (since 1.20)
677 function addHeaderText( $msg, $section = null ) {
678 if ( is_null( $section ) ) {
679 $this->mHeader
.= $msg;
681 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
682 $this->mSectionHeaders
[$section] = '';
684 $this->mSectionHeaders
[$section] .= $msg;
691 * Set header text, inside the form.
694 * @param string $msg Complete text of message to display
695 * @param string|null $section The section to add the header to
697 * @return HTMLForm $this for chaining calls (since 1.20)
699 function setHeaderText( $msg, $section = null ) {
700 if ( is_null( $section ) ) {
701 $this->mHeader
= $msg;
703 $this->mSectionHeaders
[$section] = $msg;
710 * Add footer text, inside the form.
712 * @param string $msg Complete text of message to display
713 * @param string|null $section The section to add the footer text to
715 * @return HTMLForm $this for chaining calls (since 1.20)
717 function addFooterText( $msg, $section = null ) {
718 if ( is_null( $section ) ) {
719 $this->mFooter
.= $msg;
721 if ( !isset( $this->mSectionFooters
[$section] ) ) {
722 $this->mSectionFooters
[$section] = '';
724 $this->mSectionFooters
[$section] .= $msg;
731 * Set footer text, inside the form.
734 * @param string $msg Complete text of message to display
735 * @param string|null $section The section to add the footer text to
737 * @return HTMLForm $this for chaining calls (since 1.20)
739 function setFooterText( $msg, $section = null ) {
740 if ( is_null( $section ) ) {
741 $this->mFooter
= $msg;
743 $this->mSectionFooters
[$section] = $msg;
750 * Add text to the end of the display.
752 * @param string $msg Complete text of message to display
754 * @return HTMLForm $this for chaining calls (since 1.20)
756 function addPostText( $msg ) {
757 $this->mPost
.= $msg;
763 * Set text at the end of the display.
765 * @param string $msg Complete text of message to display
767 * @return HTMLForm $this for chaining calls (since 1.20)
769 function setPostText( $msg ) {
776 * Add a hidden field to the output
778 * @param string $name Field name. This will be used exactly as entered
779 * @param string $value Field value
780 * @param array $attribs
782 * @return HTMLForm $this for chaining calls (since 1.20)
784 public function addHiddenField( $name, $value, $attribs = array() ) {
785 $attribs +
= array( 'name' => $name );
786 $this->mHiddenFields
[] = array( $value, $attribs );
792 * Add an array of hidden fields to the output
796 * @param array $fields Associative array of fields to add;
797 * mapping names to their values
799 * @return HTMLForm $this for chaining calls
801 public function addHiddenFields( array $fields ) {
802 foreach ( $fields as $name => $value ) {
803 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
810 * Add a button to the form
812 * @param string $name Field name.
813 * @param string $value Field value
814 * @param string $id DOM id for the button (default: null)
815 * @param array $attribs
817 * @return HTMLForm $this for chaining calls (since 1.20)
819 public function addButton( $name, $value, $id = null, $attribs = null ) {
820 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
826 * Set the salt for the edit token.
828 * Only useful when the method is "post".
831 * @param string|array $salt Salt to use
832 * @return HTMLForm $this For chaining calls
834 public function setTokenSalt( $salt ) {
835 $this->mTokenSalt
= $salt;
841 * Display the form (sending to the context's OutputPage object), with an
842 * appropriate error message or stack of messages, and any validation errors, etc.
844 * @attention You should call prepareForm() before calling this function.
845 * Moreover, when doing method chaining this should be the very last method
846 * call just after prepareForm().
848 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
850 * @return void Nothing, should be last call
852 function displayForm( $submitResult ) {
853 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
857 * Returns the raw HTML generated by the form
859 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
863 function getHTML( $submitResult ) {
864 # For good measure (it is the default)
865 $this->getOutput()->preventClickjacking();
866 $this->getOutput()->addModules( 'mediawiki.htmlform' );
869 . $this->getErrors( $submitResult )
872 . $this->getHiddenFields()
873 . $this->getButtons()
876 $html = $this->wrapForm( $html );
878 return '' . $this->mPre
. $html . $this->mPost
;
882 * Get HTML attributes for the `<form>` tag.
885 protected function getFormAttributes() {
886 # Use multipart/form-data
887 $encType = $this->mUseMultipart
888 ?
'multipart/form-data'
889 : 'application/x-www-form-urlencoded';
892 'action' => $this->getAction(),
893 'method' => $this->getMethod(),
894 'class' => array( 'visualClear' ),
895 'enctype' => $encType,
897 if ( !empty( $this->mId
) ) {
898 $attribs['id'] = $this->mId
;
904 * Wrap the form innards in an actual "<form>" element
906 * @param string $html HTML contents to wrap.
908 * @return string Wrapped HTML.
910 function wrapForm( $html ) {
911 # Include a <fieldset> wrapper for style, if requested.
912 if ( $this->mWrapperLegend
!== false ) {
913 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
916 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
920 * Get the hidden fields that should go inside the form.
921 * @return string HTML.
923 function getHiddenFields() {
925 if ( $this->getMethod() == 'post' ) {
926 $html .= Html
::hidden(
928 $this->getUser()->getEditToken( $this->mTokenSalt
),
929 array( 'id' => 'wpEditToken' )
931 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
934 $articlePath = $this->getConfig()->get( 'ArticlePath' );
935 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
936 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
939 foreach ( $this->mHiddenFields
as $data ) {
940 list( $value, $attribs ) = $data;
941 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
948 * Get the submit and (potentially) reset buttons.
949 * @return string HTML.
951 function getButtons() {
953 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
955 if ( $this->mShowSubmit
) {
958 if ( isset( $this->mSubmitID
) ) {
959 $attribs['id'] = $this->mSubmitID
;
962 if ( isset( $this->mSubmitName
) ) {
963 $attribs['name'] = $this->mSubmitName
;
966 if ( isset( $this->mSubmitTooltip
) ) {
967 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
970 $attribs['class'] = array( 'mw-htmlform-submit' );
972 if ( $useMediaWikiUIEverywhere ) {
973 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
976 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
979 if ( $this->mShowReset
) {
980 $buttons .= Html
::element(
984 'value' => $this->msg( 'htmlform-reset' )->text(),
985 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
990 foreach ( $this->mButtons
as $button ) {
993 'name' => $button['name'],
994 'value' => $button['value']
997 if ( $button['attribs'] ) {
998 $attrs +
= $button['attribs'];
1001 if ( isset( $button['id'] ) ) {
1002 $attrs['id'] = $button['id'];
1005 if ( $useMediaWikiUIEverywhere ) {
1006 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1007 $attrs['class'][] = 'mw-ui-button';
1010 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1013 $html = Html
::rawElement( 'span',
1014 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1020 * Get the whole body of the form.
1023 function getBody() {
1024 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1028 * Format and display an error message stack.
1030 * @param string|array|Status $errors
1034 function getErrors( $errors ) {
1035 if ( $errors instanceof Status
) {
1036 if ( $errors->isOK() ) {
1039 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1041 } elseif ( is_array( $errors ) ) {
1042 $errorstr = $this->formatErrors( $errors );
1044 $errorstr = $errors;
1048 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1053 * Format a stack of error messages into a single HTML string
1055 * @param array $errors Array of message keys/values
1057 * @return string HTML, a "<ul>" list of errors
1059 public function formatErrors( $errors ) {
1062 foreach ( $errors as $error ) {
1063 if ( is_array( $error ) ) {
1064 $msg = array_shift( $error );
1070 $errorstr .= Html
::rawElement(
1073 $this->msg( $msg, $error )->parse()
1077 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1083 * Set the text for the submit button
1085 * @param string $t Plaintext
1087 * @return HTMLForm $this for chaining calls (since 1.20)
1089 function setSubmitText( $t ) {
1090 $this->mSubmitText
= $t;
1096 * Identify that the submit button in the form has a destructive action
1099 public function setSubmitDestructive() {
1100 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1104 * Identify that the submit button in the form has a progressive action
1107 public function setSubmitProgressive() {
1108 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1112 * Set the text for the submit button to a message
1115 * @param string|Message $msg Message key or Message object
1117 * @return HTMLForm $this for chaining calls (since 1.20)
1119 public function setSubmitTextMsg( $msg ) {
1120 if ( !$msg instanceof Message
) {
1121 $msg = $this->msg( $msg );
1123 $this->setSubmitText( $msg->text() );
1129 * Get the text for the submit button, either customised or a default.
1132 function getSubmitText() {
1133 return $this->mSubmitText
1134 ?
$this->mSubmitText
1135 : $this->msg( 'htmlform-submit' )->text();
1139 * @param string $name Submit button name
1141 * @return HTMLForm $this for chaining calls (since 1.20)
1143 public function setSubmitName( $name ) {
1144 $this->mSubmitName
= $name;
1150 * @param string $name Tooltip for the submit button
1152 * @return HTMLForm $this for chaining calls (since 1.20)
1154 public function setSubmitTooltip( $name ) {
1155 $this->mSubmitTooltip
= $name;
1161 * Set the id for the submit button.
1165 * @todo FIXME: Integrity of $t is *not* validated
1166 * @return HTMLForm $this for chaining calls (since 1.20)
1168 function setSubmitID( $t ) {
1169 $this->mSubmitID
= $t;
1175 * Stop a default submit button being shown for this form. This implies that an
1176 * alternate submit method must be provided manually.
1180 * @param bool $suppressSubmit Set to false to re-enable the button again
1182 * @return HTMLForm $this for chaining calls
1184 function suppressDefaultSubmit( $suppressSubmit = true ) {
1185 $this->mShowSubmit
= !$suppressSubmit;
1191 * Set the id of the \<table\> or outermost \<div\> element.
1195 * @param string $id New value of the id attribute, or "" to remove
1197 * @return HTMLForm $this for chaining calls
1199 public function setTableId( $id ) {
1200 $this->mTableId
= $id;
1206 * @param string $id DOM id for the form
1208 * @return HTMLForm $this for chaining calls (since 1.20)
1210 public function setId( $id ) {
1217 * Prompt the whole form to be wrapped in a "<fieldset>", with
1218 * this text as its "<legend>" element.
1220 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1221 * false for no <legend>
1224 * @return HTMLForm $this for chaining calls (since 1.20)
1226 public function setWrapperLegend( $legend ) {
1227 $this->mWrapperLegend
= $legend;
1233 * Prompt the whole form to be wrapped in a "<fieldset>", with
1234 * this message as its "<legend>" element.
1237 * @param string|Message $msg Message key or Message object
1239 * @return HTMLForm $this for chaining calls (since 1.20)
1241 public function setWrapperLegendMsg( $msg ) {
1242 if ( !$msg instanceof Message
) {
1243 $msg = $this->msg( $msg );
1245 $this->setWrapperLegend( $msg->text() );
1251 * Set the prefix for various default messages
1252 * @todo Currently only used for the "<fieldset>" legend on forms
1253 * with multiple sections; should be used elsewhere?
1257 * @return HTMLForm $this for chaining calls (since 1.20)
1259 function setMessagePrefix( $p ) {
1260 $this->mMessagePrefix
= $p;
1266 * Set the title for form submission
1268 * @param Title $t Title of page the form is on/should be posted to
1270 * @return HTMLForm $this for chaining calls (since 1.20)
1272 function setTitle( $t ) {
1282 function getTitle() {
1283 return $this->mTitle
=== false
1284 ?
$this->getContext()->getTitle()
1289 * Set the method used to submit the form
1291 * @param string $method
1293 * @return HTMLForm $this for chaining calls (since 1.20)
1295 public function setMethod( $method = 'post' ) {
1296 $this->mMethod
= $method;
1301 public function getMethod() {
1302 return $this->mMethod
;
1308 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1310 * @param string $sectionName ID attribute of the "<table>" tag for this
1311 * section, ignored if empty.
1312 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1313 * each subsection, ignored if empty.
1314 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1318 public function displaySection( $fields,
1320 $fieldsetIDPrefix = '',
1321 &$hasUserVisibleFields = false ) {
1322 $displayFormat = $this->getDisplayFormat();
1325 $subsectionHtml = '';
1328 // Conveniently, PHP method names are case-insensitive.
1329 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1331 foreach ( $fields as $key => $value ) {
1332 if ( $value instanceof HTMLFormField
) {
1333 $v = empty( $value->mParams
['nodata'] )
1334 ?
$this->mFieldData
[$key]
1335 : $value->getDefault();
1336 $html .= $value->$getFieldHtmlMethod( $v );
1338 $labelValue = trim( $value->getLabel() );
1339 if ( $labelValue != ' ' && $labelValue !== '' ) {
1343 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1344 get_class( $value ) !== 'HTMLApiField'
1346 $hasUserVisibleFields = true;
1348 } elseif ( is_array( $value ) ) {
1349 $subsectionHasVisibleFields = false;
1351 $this->displaySection( $value,
1353 "$fieldsetIDPrefix$key-",
1354 $subsectionHasVisibleFields );
1357 if ( $subsectionHasVisibleFields === true ) {
1358 // Display the section with various niceties.
1359 $hasUserVisibleFields = true;
1361 $legend = $this->getLegend( $key );
1363 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1364 $section = $this->mSectionHeaders
[$key] . $section;
1366 if ( isset( $this->mSectionFooters
[$key] ) ) {
1367 $section .= $this->mSectionFooters
[$key];
1370 $attributes = array();
1371 if ( $fieldsetIDPrefix ) {
1372 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1374 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1376 // Just return the inputs, nothing fancy.
1377 $subsectionHtml .= $section;
1382 if ( $displayFormat !== 'raw' ) {
1385 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1386 $classes[] = 'mw-htmlform-nolabel';
1390 'class' => implode( ' ', $classes ),
1393 if ( $sectionName ) {
1394 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1397 if ( $displayFormat === 'table' ) {
1398 $html = Html
::rawElement( 'table',
1400 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1401 } elseif ( $displayFormat === 'inline' ) {
1402 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1403 } elseif ( $displayFormat === 'ooui' ) {
1405 'classes' => $classes,
1407 if ( $sectionName ) {
1408 $config['id'] = Sanitizer
::escapeId( $sectionName );
1410 $fieldset = new OOUI\
FieldsetLayout( $config );
1411 // Ewww. We should pass this as $config['items'], but there might be string snippets.
1412 $fieldset->group
->appendContent( new OOUI\
HtmlSnippet( $html ) );
1413 $html = $fieldset->toString();
1415 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1419 if ( $this->mSubSectionBeforeFields
) {
1420 return $subsectionHtml . "\n" . $html;
1422 return $html . "\n" . $subsectionHtml;
1427 * Construct the form fields from the Descriptor array
1429 function loadData() {
1430 $fieldData = array();
1432 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1433 if ( !empty( $field->mParams
['nodata'] ) ) {
1435 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1436 $fieldData[$fieldname] = $field->getDefault();
1438 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1443 foreach ( $fieldData as $name => &$value ) {
1444 $field = $this->mFlatFields
[$name];
1445 $value = $field->filter( $value, $this->mFlatFields
);
1448 $this->mFieldData
= $fieldData;
1452 * Stop a reset button being shown for this form
1454 * @param bool $suppressReset Set to false to re-enable the button again
1456 * @return HTMLForm $this for chaining calls (since 1.20)
1458 function suppressReset( $suppressReset = true ) {
1459 $this->mShowReset
= !$suppressReset;
1465 * Overload this if you want to apply special filtration routines
1466 * to the form as a whole, after it's submitted but before it's
1469 * @param array $data
1473 function filterDataForSubmit( $data ) {
1478 * Get a string to go in the "<legend>" of a section fieldset.
1479 * Override this if you want something more complicated.
1481 * @param string $key
1485 public function getLegend( $key ) {
1486 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1490 * Set the value for the action attribute of the form.
1491 * When set to false (which is the default state), the set title is used.
1495 * @param string|bool $action
1497 * @return HTMLForm $this for chaining calls (since 1.20)
1499 public function setAction( $action ) {
1500 $this->mAction
= $action;
1506 * Get the value for the action attribute of the form.
1512 public function getAction() {
1513 // If an action is alredy provided, return it
1514 if ( $this->mAction
!== false ) {
1515 return $this->mAction
;
1518 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1519 // Check whether we are in GET mode and the ArticlePath contains a "?"
1520 // meaning that getLocalURL() would return something like "index.php?title=...".
1521 // As browser remove the query string before submitting GET forms,
1522 // it means that the title would be lost. In such case use wfScript() instead
1523 // and put title in an hidden field (see getHiddenFields()).
1524 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1528 return $this->getTitle()->getLocalURL();