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',
156 'title' => 'HTMLTitleTextField',
161 protected $mMessagePrefix;
163 /** @var HTMLFormField[] */
164 protected $mFlatFields;
166 protected $mFieldTree;
167 protected $mShowReset = false;
168 protected $mShowSubmit = true;
169 protected $mSubmitFlag = 'constructive';
171 protected $mSubmitCallback;
172 protected $mValidationErrorMessage;
174 protected $mPre = '';
175 protected $mHeader = '';
176 protected $mFooter = '';
177 protected $mSectionHeaders = array();
178 protected $mSectionFooters = array();
179 protected $mPost = '';
181 protected $mTableId = '';
183 protected $mSubmitID;
184 protected $mSubmitName;
185 protected $mSubmitText;
186 protected $mSubmitTooltip;
189 protected $mMethod = 'post';
190 protected $mWasSubmitted = false;
193 * Form action URL. false means we will use the URL to set Title
197 protected $mAction = false;
199 protected $mUseMultipart = false;
200 protected $mHiddenFields = array();
201 protected $mButtons = array();
203 protected $mWrapperLegend = false;
206 * Salt for the edit token.
209 protected $mTokenSalt = '';
212 * If true, sections that contain both fields and subsections will
213 * render their subsections before their fields.
215 * Subclasses may set this to false to render subsections after fields
218 protected $mSubSectionBeforeFields = true;
221 * Format in which to display form. For viable options,
222 * @see $availableDisplayFormats
225 protected $displayFormat = 'table';
228 * Available formats in which to display the form
231 protected $availableDisplayFormats = array(
239 * Available formats in which to display the form
242 protected $availableSubclassDisplayFormats = array(
248 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
250 * @param string $displayFormat
251 * @param mixed $arguments... Additional arguments to pass to the constructor.
254 public static function factory( $displayFormat/*, $arguments...*/ ) {
255 $arguments = func_get_args();
256 array_shift( $arguments );
258 switch ( $displayFormat ) {
260 $reflector = new ReflectionClass( 'VFormHTMLForm' );
261 return $reflector->newInstanceArgs( $arguments );
263 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
264 return $reflector->newInstanceArgs( $arguments );
266 $reflector = new ReflectionClass( 'HTMLForm' );
267 $form = $reflector->newInstanceArgs( $arguments );
268 $form->setDisplayFormat( $displayFormat );
274 * Build a new HTMLForm from an array of field attributes
276 * @param array $descriptor Array of Field constructs, as described above
277 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
278 * Obviates the need to call $form->setTitle()
279 * @param string $messagePrefix A prefix to go in front of default messages
281 public function __construct( $descriptor, /*IContextSource*/ $context = null,
284 if ( $context instanceof IContextSource
) {
285 $this->setContext( $context );
286 $this->mTitle
= false; // We don't need them to set a title
287 $this->mMessagePrefix
= $messagePrefix;
288 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
289 $this->mMessagePrefix
= $messagePrefix;
290 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
292 // it's actually $messagePrefix
293 $this->mMessagePrefix
= $context;
296 // Evil hack for mobile :(
298 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
299 && $this->displayFormat
=== 'table'
301 $this->displayFormat
= 'div';
304 // Expand out into a tree.
305 $loadedDescriptor = array();
306 $this->mFlatFields
= array();
308 foreach ( $descriptor as $fieldname => $info ) {
309 $section = isset( $info['section'] )
313 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
314 $this->mUseMultipart
= true;
317 $field = static::loadInputFromParameters( $fieldname, $info, $this );
319 $setSection =& $loadedDescriptor;
321 $sectionParts = explode( '/', $section );
323 while ( count( $sectionParts ) ) {
324 $newName = array_shift( $sectionParts );
326 if ( !isset( $setSection[$newName] ) ) {
327 $setSection[$newName] = array();
330 $setSection =& $setSection[$newName];
334 $setSection[$fieldname] = $field;
335 $this->mFlatFields
[$fieldname] = $field;
338 $this->mFieldTree
= $loadedDescriptor;
342 * Set format in which to display the form
344 * @param string $format The name of the format to use, must be one of
345 * $this->availableDisplayFormats
347 * @throws MWException
349 * @return HTMLForm $this for chaining calls (since 1.20)
351 public function setDisplayFormat( $format ) {
353 in_array( $format, $this->availableSubclassDisplayFormats
) ||
354 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
356 throw new MWException( 'Cannot change display format after creation, ' .
357 'use HTMLForm::factory() instead' );
360 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
361 throw new MWException( 'Display format must be one of ' .
362 print_r( $this->availableDisplayFormats
, true ) );
365 // Evil hack for mobile :(
366 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
370 $this->displayFormat
= $format;
376 * Getter for displayFormat
380 public function getDisplayFormat() {
381 return $this->displayFormat
;
385 * Test if displayFormat is 'vform'
387 * @deprecated since 1.25
390 public function isVForm() {
391 wfDeprecated( __METHOD__
, '1.25' );
396 * Get the HTMLFormField subclass for this descriptor.
398 * The descriptor can be passed either 'class' which is the name of
399 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
400 * This makes sure the 'class' is always set, and also is returned by
401 * this function for ease.
405 * @param string $fieldname Name of the field
406 * @param array $descriptor Input Descriptor, as described above
408 * @throws MWException
409 * @return string Name of a HTMLFormField subclass
411 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
412 if ( isset( $descriptor['class'] ) ) {
413 $class = $descriptor['class'];
414 } elseif ( isset( $descriptor['type'] ) ) {
415 $class = static::$typeMappings[$descriptor['type']];
416 $descriptor['class'] = $class;
422 throw new MWException( "Descriptor with no class for $fieldname: "
423 . print_r( $descriptor, true ) );
430 * Initialise a new Object for the field
432 * @param string $fieldname Name of the field
433 * @param array $descriptor Input Descriptor, as described above
434 * @param HTMLForm|null $parent Parent instance of HTMLForm
436 * @throws MWException
437 * @return HTMLFormField Instance of a subclass of HTMLFormField
439 public static function loadInputFromParameters( $fieldname, $descriptor,
440 HTMLForm
$parent = null
442 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
444 $descriptor['fieldname'] = $fieldname;
446 $descriptor['parent'] = $parent;
449 # @todo This will throw a fatal error whenever someone try to use
450 # 'class' to feed a CSS class instead of 'cssclass'. Would be
451 # great to avoid the fatal error and show a nice error.
452 $obj = new $class( $descriptor );
458 * Prepare form for submission.
460 * @attention When doing method chaining, that should be the very last
461 * method call before displayForm().
463 * @throws MWException
464 * @return HTMLForm $this for chaining calls (since 1.20)
466 function prepareForm() {
467 # Check if we have the info we need
468 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
469 throw new MWException( "You must call setTitle() on an HTMLForm" );
472 # Load data from the request.
479 * Try submitting, with edit token check first
480 * @return Status|bool
482 function tryAuthorizedSubmit() {
486 if ( $this->getMethod() != 'post' ) {
487 $submit = true; // no session check needed
488 } elseif ( $this->getRequest()->wasPosted() ) {
489 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
490 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
491 // Session tokens for logged-out users have no security value.
492 // However, if the user gave one, check it in order to give a nice
493 // "session expired" error instead of "permission denied" or such.
494 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
501 $this->mWasSubmitted
= true;
502 $result = $this->trySubmit();
509 * The here's-one-I-made-earlier option: do the submission if
510 * posted, or display the form with or without funky validation
512 * @return bool|Status Whether submission was successful.
515 $this->prepareForm();
517 $result = $this->tryAuthorizedSubmit();
518 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
522 $this->displayForm( $result );
528 * Validate all the fields, and call the submission callback
529 * function if everything is kosher.
530 * @throws MWException
531 * @return bool|string|array|Status
532 * - Bool true or a good Status object indicates success,
533 * - Bool false indicates no submission was attempted,
534 * - Anything else indicates failure. The value may be a fatal Status
535 * object, an HTML string, or an array of arrays (message keys and
536 * params) or strings (message keys)
538 function trySubmit() {
539 $this->mWasSubmitted
= true;
541 # Check for cancelled submission
542 foreach ( $this->mFlatFields
as $fieldname => $field ) {
543 if ( !empty( $field->mParams
['nodata'] ) ) {
546 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
547 $this->mWasSubmitted
= false;
552 # Check for validation
553 foreach ( $this->mFlatFields
as $fieldname => $field ) {
554 if ( !empty( $field->mParams
['nodata'] ) ) {
557 if ( $field->isHidden( $this->mFieldData
) ) {
560 if ( $field->validate(
561 $this->mFieldData
[$fieldname],
565 return isset( $this->mValidationErrorMessage
)
566 ?
$this->mValidationErrorMessage
567 : array( 'htmlform-invalid-input' );
571 $callback = $this->mSubmitCallback
;
572 if ( !is_callable( $callback ) ) {
573 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
574 'setSubmitCallback() to set one.' );
577 $data = $this->filterDataForSubmit( $this->mFieldData
);
579 $res = call_user_func( $callback, $data, $this );
580 if ( $res === false ) {
581 $this->mWasSubmitted
= false;
588 * Test whether the form was considered to have been submitted or not, i.e.
589 * whether the last call to tryAuthorizedSubmit or trySubmit returned
592 * This will return false until HTMLForm::tryAuthorizedSubmit or
593 * HTMLForm::trySubmit is called.
598 function wasSubmitted() {
599 return $this->mWasSubmitted
;
603 * Set a callback to a function to do something with the form
604 * once it's been successfully validated.
606 * @param callable $cb The function will be passed the output from
607 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
608 * return as documented for HTMLForm::trySubmit
610 * @return HTMLForm $this for chaining calls (since 1.20)
612 function setSubmitCallback( $cb ) {
613 $this->mSubmitCallback
= $cb;
619 * Set a message to display on a validation error.
621 * @param string|array $msg String or Array of valid inputs to wfMessage()
622 * (so each entry can be either a String or Array)
624 * @return HTMLForm $this for chaining calls (since 1.20)
626 function setValidationErrorMessage( $msg ) {
627 $this->mValidationErrorMessage
= $msg;
633 * Set the introductory message, overwriting any existing message.
635 * @param string $msg Complete text of message to display
637 * @return HTMLForm $this for chaining calls (since 1.20)
639 function setIntro( $msg ) {
640 $this->setPreText( $msg );
646 * Set the introductory message, overwriting any existing message.
649 * @param string $msg Complete text of message to display
651 * @return HTMLForm $this for chaining calls (since 1.20)
653 function setPreText( $msg ) {
660 * Add introductory text.
662 * @param string $msg Complete text of message to display
664 * @return HTMLForm $this for chaining calls (since 1.20)
666 function addPreText( $msg ) {
673 * Add header text, inside the form.
675 * @param string $msg Complete text of message to display
676 * @param string|null $section The section to add the header to
678 * @return HTMLForm $this for chaining calls (since 1.20)
680 function addHeaderText( $msg, $section = null ) {
681 if ( is_null( $section ) ) {
682 $this->mHeader
.= $msg;
684 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
685 $this->mSectionHeaders
[$section] = '';
687 $this->mSectionHeaders
[$section] .= $msg;
694 * Set header text, inside the form.
697 * @param string $msg Complete text of message to display
698 * @param string|null $section The section to add the header to
700 * @return HTMLForm $this for chaining calls (since 1.20)
702 function setHeaderText( $msg, $section = null ) {
703 if ( is_null( $section ) ) {
704 $this->mHeader
= $msg;
706 $this->mSectionHeaders
[$section] = $msg;
713 * Add footer text, inside the form.
715 * @param string $msg Complete text of message to display
716 * @param string|null $section The section to add the footer text to
718 * @return HTMLForm $this for chaining calls (since 1.20)
720 function addFooterText( $msg, $section = null ) {
721 if ( is_null( $section ) ) {
722 $this->mFooter
.= $msg;
724 if ( !isset( $this->mSectionFooters
[$section] ) ) {
725 $this->mSectionFooters
[$section] = '';
727 $this->mSectionFooters
[$section] .= $msg;
734 * Set footer text, inside the form.
737 * @param string $msg Complete text of message to display
738 * @param string|null $section The section to add the footer text to
740 * @return HTMLForm $this for chaining calls (since 1.20)
742 function setFooterText( $msg, $section = null ) {
743 if ( is_null( $section ) ) {
744 $this->mFooter
= $msg;
746 $this->mSectionFooters
[$section] = $msg;
753 * Add text to the end of the display.
755 * @param string $msg Complete text of message to display
757 * @return HTMLForm $this for chaining calls (since 1.20)
759 function addPostText( $msg ) {
760 $this->mPost
.= $msg;
766 * Set text at the end of the display.
768 * @param string $msg Complete text of message to display
770 * @return HTMLForm $this for chaining calls (since 1.20)
772 function setPostText( $msg ) {
779 * Add a hidden field to the output
781 * @param string $name Field name. This will be used exactly as entered
782 * @param string $value Field value
783 * @param array $attribs
785 * @return HTMLForm $this for chaining calls (since 1.20)
787 public function addHiddenField( $name, $value, $attribs = array() ) {
788 $attribs +
= array( 'name' => $name );
789 $this->mHiddenFields
[] = array( $value, $attribs );
795 * Add an array of hidden fields to the output
799 * @param array $fields Associative array of fields to add;
800 * mapping names to their values
802 * @return HTMLForm $this for chaining calls
804 public function addHiddenFields( array $fields ) {
805 foreach ( $fields as $name => $value ) {
806 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
813 * Add a button to the form
815 * @param string $name Field name.
816 * @param string $value Field value
817 * @param string $id DOM id for the button (default: null)
818 * @param array $attribs
820 * @return HTMLForm $this for chaining calls (since 1.20)
822 public function addButton( $name, $value, $id = null, $attribs = null ) {
823 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
829 * Set the salt for the edit token.
831 * Only useful when the method is "post".
834 * @param string|array $salt Salt to use
835 * @return HTMLForm $this For chaining calls
837 public function setTokenSalt( $salt ) {
838 $this->mTokenSalt
= $salt;
844 * Display the form (sending to the context's OutputPage object), with an
845 * appropriate error message or stack of messages, and any validation errors, etc.
847 * @attention You should call prepareForm() before calling this function.
848 * Moreover, when doing method chaining this should be the very last method
849 * call just after prepareForm().
851 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
853 * @return void Nothing, should be last call
855 function displayForm( $submitResult ) {
856 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
860 * Returns the raw HTML generated by the form
862 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
866 function getHTML( $submitResult ) {
867 # For good measure (it is the default)
868 $this->getOutput()->preventClickjacking();
869 $this->getOutput()->addModules( 'mediawiki.htmlform' );
872 . $this->getErrors( $submitResult )
873 // In OOUI forms, we handle mHeader elsewhere. FIXME This is horrible.
874 . ( $this->getDisplayFormat() === 'ooui' ?
'' : $this->mHeader
)
876 . $this->getHiddenFields()
877 . $this->getButtons()
880 $html = $this->wrapForm( $html );
882 return '' . $this->mPre
. $html . $this->mPost
;
886 * Get HTML attributes for the `<form>` tag.
889 protected function getFormAttributes() {
890 # Use multipart/form-data
891 $encType = $this->mUseMultipart
892 ?
'multipart/form-data'
893 : 'application/x-www-form-urlencoded';
896 'action' => $this->getAction(),
897 'method' => $this->getMethod(),
898 'enctype' => $encType,
900 if ( !empty( $this->mId
) ) {
901 $attribs['id'] = $this->mId
;
907 * Wrap the form innards in an actual "<form>" element
909 * @param string $html HTML contents to wrap.
911 * @return string Wrapped HTML.
913 function wrapForm( $html ) {
914 # Include a <fieldset> wrapper for style, if requested.
915 if ( $this->mWrapperLegend
!== false ) {
916 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
917 $html = Xml
::fieldset( $legend, $html );
920 return Html
::rawElement( 'form', $this->getFormAttributes() +
array( 'class' => 'visualClear' ), $html );
924 * Get the hidden fields that should go inside the form.
925 * @return string HTML.
927 function getHiddenFields() {
929 if ( $this->getMethod() == 'post' ) {
930 $html .= Html
::hidden(
932 $this->getUser()->getEditToken( $this->mTokenSalt
),
933 array( 'id' => 'wpEditToken' )
935 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
938 $articlePath = $this->getConfig()->get( 'ArticlePath' );
939 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
940 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
943 foreach ( $this->mHiddenFields
as $data ) {
944 list( $value, $attribs ) = $data;
945 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
952 * Get the submit and (potentially) reset buttons.
953 * @return string HTML.
955 function getButtons() {
957 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
959 if ( $this->mShowSubmit
) {
962 if ( isset( $this->mSubmitID
) ) {
963 $attribs['id'] = $this->mSubmitID
;
966 if ( isset( $this->mSubmitName
) ) {
967 $attribs['name'] = $this->mSubmitName
;
970 if ( isset( $this->mSubmitTooltip
) ) {
971 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
974 $attribs['class'] = array( 'mw-htmlform-submit' );
976 if ( $useMediaWikiUIEverywhere ) {
977 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-' . $this->mSubmitFlag
);
980 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
983 if ( $this->mShowReset
) {
984 $buttons .= Html
::element(
988 'value' => $this->msg( 'htmlform-reset' )->text(),
989 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
994 foreach ( $this->mButtons
as $button ) {
997 'name' => $button['name'],
998 'value' => $button['value']
1001 if ( $button['attribs'] ) {
1002 $attrs +
= $button['attribs'];
1005 if ( isset( $button['id'] ) ) {
1006 $attrs['id'] = $button['id'];
1009 if ( $useMediaWikiUIEverywhere ) {
1010 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1011 $attrs['class'][] = 'mw-ui-button';
1014 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1017 $html = Html
::rawElement( 'span',
1018 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1024 * Get the whole body of the form.
1027 function getBody() {
1028 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1032 * Format and display an error message stack.
1034 * @param string|array|Status $errors
1038 function getErrors( $errors ) {
1039 if ( $errors instanceof Status
) {
1040 if ( $errors->isOK() ) {
1043 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1045 } elseif ( is_array( $errors ) ) {
1046 $errorstr = $this->formatErrors( $errors );
1048 $errorstr = $errors;
1052 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1057 * Format a stack of error messages into a single HTML string
1059 * @param array $errors Array of message keys/values
1061 * @return string HTML, a "<ul>" list of errors
1063 public function formatErrors( $errors ) {
1066 foreach ( $errors as $error ) {
1067 if ( is_array( $error ) ) {
1068 $msg = array_shift( $error );
1074 $errorstr .= Html
::rawElement(
1077 $this->msg( $msg, $error )->parse()
1081 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1087 * Set the text for the submit button
1089 * @param string $t Plaintext
1091 * @return HTMLForm $this for chaining calls (since 1.20)
1093 function setSubmitText( $t ) {
1094 $this->mSubmitText
= $t;
1100 * Identify that the submit button in the form has a destructive action
1103 public function setSubmitDestructive() {
1104 $this->mSubmitFlag
= 'destructive';
1108 * Identify that the submit button in the form has a progressive action
1111 public function setSubmitProgressive() {
1112 $this->mSubmitFlag
= 'progressive';
1116 * Set the text for the submit button to a message
1119 * @param string|Message $msg Message key or Message object
1121 * @return HTMLForm $this for chaining calls (since 1.20)
1123 public function setSubmitTextMsg( $msg ) {
1124 if ( !$msg instanceof Message
) {
1125 $msg = $this->msg( $msg );
1127 $this->setSubmitText( $msg->text() );
1133 * Get the text for the submit button, either customised or a default.
1136 function getSubmitText() {
1137 return $this->mSubmitText
1138 ?
$this->mSubmitText
1139 : $this->msg( 'htmlform-submit' )->text();
1143 * @param string $name Submit button name
1145 * @return HTMLForm $this for chaining calls (since 1.20)
1147 public function setSubmitName( $name ) {
1148 $this->mSubmitName
= $name;
1154 * @param string $name Tooltip for the submit button
1156 * @return HTMLForm $this for chaining calls (since 1.20)
1158 public function setSubmitTooltip( $name ) {
1159 $this->mSubmitTooltip
= $name;
1165 * Set the id for the submit button.
1169 * @todo FIXME: Integrity of $t is *not* validated
1170 * @return HTMLForm $this for chaining calls (since 1.20)
1172 function setSubmitID( $t ) {
1173 $this->mSubmitID
= $t;
1179 * Stop a default submit button being shown for this form. This implies that an
1180 * alternate submit method must be provided manually.
1184 * @param bool $suppressSubmit Set to false to re-enable the button again
1186 * @return HTMLForm $this for chaining calls
1188 function suppressDefaultSubmit( $suppressSubmit = true ) {
1189 $this->mShowSubmit
= !$suppressSubmit;
1195 * Set the id of the \<table\> or outermost \<div\> element.
1199 * @param string $id New value of the id attribute, or "" to remove
1201 * @return HTMLForm $this for chaining calls
1203 public function setTableId( $id ) {
1204 $this->mTableId
= $id;
1210 * @param string $id DOM id for the form
1212 * @return HTMLForm $this for chaining calls (since 1.20)
1214 public function setId( $id ) {
1221 * Prompt the whole form to be wrapped in a "<fieldset>", with
1222 * this text as its "<legend>" element.
1224 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1225 * If true, a wrapper will be displayed, but no legend.
1226 * If a string, a wrapper will be displayed with that string as a legend.
1227 * The string will be escaped before being output (this doesn't support HTML).
1229 * @return HTMLForm $this for chaining calls (since 1.20)
1231 public function setWrapperLegend( $legend ) {
1232 $this->mWrapperLegend
= $legend;
1238 * Prompt the whole form to be wrapped in a "<fieldset>", with
1239 * this message as its "<legend>" element.
1242 * @param string|Message $msg Message key or Message object
1244 * @return HTMLForm $this for chaining calls (since 1.20)
1246 public function setWrapperLegendMsg( $msg ) {
1247 if ( !$msg instanceof Message
) {
1248 $msg = $this->msg( $msg );
1250 $this->setWrapperLegend( $msg->text() );
1256 * Set the prefix for various default messages
1257 * @todo Currently only used for the "<fieldset>" legend on forms
1258 * with multiple sections; should be used elsewhere?
1262 * @return HTMLForm $this for chaining calls (since 1.20)
1264 function setMessagePrefix( $p ) {
1265 $this->mMessagePrefix
= $p;
1271 * Set the title for form submission
1273 * @param Title $t Title of page the form is on/should be posted to
1275 * @return HTMLForm $this for chaining calls (since 1.20)
1277 function setTitle( $t ) {
1287 function getTitle() {
1288 return $this->mTitle
=== false
1289 ?
$this->getContext()->getTitle()
1294 * Set the method used to submit the form
1296 * @param string $method
1298 * @return HTMLForm $this for chaining calls (since 1.20)
1300 public function setMethod( $method = 'post' ) {
1301 $this->mMethod
= $method;
1306 public function getMethod() {
1307 return $this->mMethod
;
1313 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1315 * @param string $sectionName ID attribute of the "<table>" tag for this
1316 * section, ignored if empty.
1317 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1318 * each subsection, ignored if empty.
1319 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1323 public function displaySection( $fields,
1325 $fieldsetIDPrefix = '',
1326 &$hasUserVisibleFields = false ) {
1327 $displayFormat = $this->getDisplayFormat();
1330 $subsectionHtml = '';
1333 // Conveniently, PHP method names are case-insensitive.
1334 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1336 foreach ( $fields as $key => $value ) {
1337 if ( $value instanceof HTMLFormField
) {
1338 $v = empty( $value->mParams
['nodata'] )
1339 ?
$this->mFieldData
[$key]
1340 : $value->getDefault();
1341 $html .= $value->$getFieldHtmlMethod( $v );
1343 $labelValue = trim( $value->getLabel() );
1344 if ( $labelValue != ' ' && $labelValue !== '' ) {
1348 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1349 get_class( $value ) !== 'HTMLApiField'
1351 $hasUserVisibleFields = true;
1353 } elseif ( is_array( $value ) ) {
1354 $subsectionHasVisibleFields = false;
1356 $this->displaySection( $value,
1358 "$fieldsetIDPrefix$key-",
1359 $subsectionHasVisibleFields );
1362 if ( $subsectionHasVisibleFields === true ) {
1363 // Display the section with various niceties.
1364 $hasUserVisibleFields = true;
1366 $legend = $this->getLegend( $key );
1368 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1369 $section = $this->mSectionHeaders
[$key] . $section;
1371 if ( isset( $this->mSectionFooters
[$key] ) ) {
1372 $section .= $this->mSectionFooters
[$key];
1375 $attributes = array();
1376 if ( $fieldsetIDPrefix ) {
1377 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1379 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1381 // Just return the inputs, nothing fancy.
1382 $subsectionHtml .= $section;
1387 if ( $displayFormat !== 'raw' ) {
1390 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1391 $classes[] = 'mw-htmlform-nolabel';
1395 'class' => implode( ' ', $classes ),
1398 if ( $sectionName ) {
1399 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1402 if ( $displayFormat === 'table' ) {
1403 $html = Html
::rawElement( 'table',
1405 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1406 } elseif ( $displayFormat === 'inline' ) {
1407 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1408 } elseif ( $displayFormat === 'ooui' ) {
1410 'classes' => $classes,
1412 if ( $sectionName ) {
1413 $config['id'] = Sanitizer
::escapeId( $sectionName );
1415 if ( is_string( $this->mWrapperLegend
) ) {
1416 $config['label'] = $this->mWrapperLegend
;
1418 $fieldset = new OOUI\
FieldsetLayout( $config );
1419 // Ewww. We should pass this as $config['items'], but there might be string snippets.
1420 $fieldset->group
->appendContent( new OOUI\
HtmlSnippet( $html ) );
1423 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1427 if ( $subsectionHtml ) {
1428 if ( $this->mSubSectionBeforeFields
) {
1429 return $subsectionHtml . "\n" . $html;
1431 return $html . "\n" . $subsectionHtml;
1439 * Construct the form fields from the Descriptor array
1441 function loadData() {
1442 $fieldData = array();
1444 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1445 if ( !empty( $field->mParams
['nodata'] ) ) {
1447 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1448 $fieldData[$fieldname] = $field->getDefault();
1450 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1455 foreach ( $fieldData as $name => &$value ) {
1456 $field = $this->mFlatFields
[$name];
1457 $value = $field->filter( $value, $this->mFlatFields
);
1460 $this->mFieldData
= $fieldData;
1464 * Stop a reset button being shown for this form
1466 * @param bool $suppressReset Set to false to re-enable the button again
1468 * @return HTMLForm $this for chaining calls (since 1.20)
1470 function suppressReset( $suppressReset = true ) {
1471 $this->mShowReset
= !$suppressReset;
1477 * Overload this if you want to apply special filtration routines
1478 * to the form as a whole, after it's submitted but before it's
1481 * @param array $data
1485 function filterDataForSubmit( $data ) {
1490 * Get a string to go in the "<legend>" of a section fieldset.
1491 * Override this if you want something more complicated.
1493 * @param string $key
1497 public function getLegend( $key ) {
1498 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1502 * Set the value for the action attribute of the form.
1503 * When set to false (which is the default state), the set title is used.
1507 * @param string|bool $action
1509 * @return HTMLForm $this for chaining calls (since 1.20)
1511 public function setAction( $action ) {
1512 $this->mAction
= $action;
1518 * Get the value for the action attribute of the form.
1524 public function getAction() {
1525 // If an action is alredy provided, return it
1526 if ( $this->mAction
!== false ) {
1527 return $this->mAction
;
1530 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1531 // Check whether we are in GET mode and the ArticlePath contains a "?"
1532 // meaning that getLocalURL() would return something like "index.php?title=...".
1533 // As browser remove the query string before submitting GET forms,
1534 // it means that the title would be lost. In such case use wfScript() instead
1535 // and put title in an hidden field (see getHiddenFields()).
1536 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1540 return $this->getTitle()->getLocalURL();