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 'advancednamespaceselect' => 'HTMLAdvancedSelectNamespace',
144 'advancednamespaceselectwithbutton' => 'HTMLAdvancedSelectNamespaceWithButton',
145 'tagfilter' => 'HTMLTagFilter',
146 'submit' => 'HTMLSubmitField',
147 'hidden' => 'HTMLHiddenField',
148 'edittools' => 'HTMLEditTools',
149 'checkmatrix' => 'HTMLCheckMatrix',
150 'cloner' => 'HTMLFormFieldCloner',
151 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
152 // HTMLTextField will output the correct type="" attribute automagically.
153 // There are about four zillion other HTML5 input types, like range, but
154 // we don't use those at the moment, so no point in adding all of them.
155 'email' => 'HTMLTextField',
156 'password' => 'HTMLTextField',
157 'url' => 'HTMLTextField',
158 'title' => 'HTMLTitleTextField',
159 'user' => 'HTMLUserTextField',
164 protected $mMessagePrefix;
166 /** @var HTMLFormField[] */
167 protected $mFlatFields;
169 protected $mFieldTree;
170 protected $mShowReset = false;
171 protected $mShowSubmit = true;
172 protected $mSubmitFlags = array( 'constructive', 'primary' );
174 protected $mSubmitCallback;
175 protected $mValidationErrorMessage;
177 protected $mPre = '';
178 protected $mHeader = '';
179 protected $mFooter = '';
180 protected $mSectionHeaders = array();
181 protected $mSectionFooters = array();
182 protected $mPost = '';
184 protected $mTableId = '';
186 protected $mSubmitID;
187 protected $mSubmitName;
188 protected $mSubmitText;
189 protected $mSubmitTooltip;
192 protected $mMethod = 'post';
193 protected $mWasSubmitted = false;
196 * Form action URL. false means we will use the URL to set Title
200 protected $mAction = false;
202 protected $mUseMultipart = false;
203 protected $mHiddenFields = array();
204 protected $mButtons = array();
206 protected $mWrapperLegend = false;
209 * Salt for the edit token.
212 protected $mTokenSalt = '';
215 * If true, sections that contain both fields and subsections will
216 * render their subsections before their fields.
218 * Subclasses may set this to false to render subsections after fields
221 protected $mSubSectionBeforeFields = true;
224 * Format in which to display form. For viable options,
225 * @see $availableDisplayFormats
228 protected $displayFormat = 'table';
231 * Available formats in which to display the form
234 protected $availableDisplayFormats = array(
242 * Available formats in which to display the form
245 protected $availableSubclassDisplayFormats = array(
251 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
253 * @param string $displayFormat
254 * @param mixed $arguments... Additional arguments to pass to the constructor.
257 public static function factory( $displayFormat/*, $arguments...*/ ) {
258 $arguments = func_get_args();
259 array_shift( $arguments );
261 switch ( $displayFormat ) {
263 $reflector = new ReflectionClass( 'VFormHTMLForm' );
264 return $reflector->newInstanceArgs( $arguments );
266 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
267 return $reflector->newInstanceArgs( $arguments );
269 $reflector = new ReflectionClass( 'HTMLForm' );
270 $form = $reflector->newInstanceArgs( $arguments );
271 $form->setDisplayFormat( $displayFormat );
277 * Build a new HTMLForm from an array of field attributes
279 * @param array $descriptor Array of Field constructs, as described above
280 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
281 * Obviates the need to call $form->setTitle()
282 * @param string $messagePrefix A prefix to go in front of default messages
284 public function __construct( $descriptor, /*IContextSource*/ $context = null,
287 if ( $context instanceof IContextSource
) {
288 $this->setContext( $context );
289 $this->mTitle
= false; // We don't need them to set a title
290 $this->mMessagePrefix
= $messagePrefix;
291 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
292 $this->mMessagePrefix
= $messagePrefix;
293 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
295 // it's actually $messagePrefix
296 $this->mMessagePrefix
= $context;
299 // Evil hack for mobile :(
301 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
302 && $this->displayFormat
=== 'table'
304 $this->displayFormat
= 'div';
307 // Expand out into a tree.
308 $loadedDescriptor = array();
309 $this->mFlatFields
= array();
311 foreach ( $descriptor as $fieldname => $info ) {
312 $section = isset( $info['section'] )
316 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
317 $this->mUseMultipart
= true;
320 $field = static::loadInputFromParameters( $fieldname, $info, $this );
322 $setSection =& $loadedDescriptor;
324 $sectionParts = explode( '/', $section );
326 while ( count( $sectionParts ) ) {
327 $newName = array_shift( $sectionParts );
329 if ( !isset( $setSection[$newName] ) ) {
330 $setSection[$newName] = array();
333 $setSection =& $setSection[$newName];
337 $setSection[$fieldname] = $field;
338 $this->mFlatFields
[$fieldname] = $field;
341 $this->mFieldTree
= $loadedDescriptor;
345 * Set format in which to display the form
347 * @param string $format The name of the format to use, must be one of
348 * $this->availableDisplayFormats
350 * @throws MWException
352 * @return HTMLForm $this for chaining calls (since 1.20)
354 public function setDisplayFormat( $format ) {
356 in_array( $format, $this->availableSubclassDisplayFormats
) ||
357 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
359 throw new MWException( 'Cannot change display format after creation, ' .
360 'use HTMLForm::factory() instead' );
363 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
364 throw new MWException( 'Display format must be one of ' .
365 print_r( $this->availableDisplayFormats
, true ) );
368 // Evil hack for mobile :(
369 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
373 $this->displayFormat
= $format;
379 * Getter for displayFormat
383 public function getDisplayFormat() {
384 return $this->displayFormat
;
388 * Test if displayFormat is 'vform'
390 * @deprecated since 1.25
393 public function isVForm() {
394 wfDeprecated( __METHOD__
, '1.25' );
399 * Get the HTMLFormField subclass for this descriptor.
401 * The descriptor can be passed either 'class' which is the name of
402 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
403 * This makes sure the 'class' is always set, and also is returned by
404 * this function for ease.
408 * @param string $fieldname Name of the field
409 * @param array $descriptor Input Descriptor, as described above
411 * @throws MWException
412 * @return string Name of a HTMLFormField subclass
414 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
415 if ( isset( $descriptor['class'] ) ) {
416 $class = $descriptor['class'];
417 } elseif ( isset( $descriptor['type'] ) ) {
418 $class = static::$typeMappings[$descriptor['type']];
419 $descriptor['class'] = $class;
425 throw new MWException( "Descriptor with no class for $fieldname: "
426 . print_r( $descriptor, true ) );
433 * Initialise a new Object for the field
435 * @param string $fieldname Name of the field
436 * @param array $descriptor Input Descriptor, as described above
437 * @param HTMLForm|null $parent Parent instance of HTMLForm
439 * @throws MWException
440 * @return HTMLFormField Instance of a subclass of HTMLFormField
442 public static function loadInputFromParameters( $fieldname, $descriptor,
443 HTMLForm
$parent = null
445 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
447 $descriptor['fieldname'] = $fieldname;
449 $descriptor['parent'] = $parent;
452 # @todo This will throw a fatal error whenever someone try to use
453 # 'class' to feed a CSS class instead of 'cssclass'. Would be
454 # great to avoid the fatal error and show a nice error.
455 $obj = new $class( $descriptor );
461 * Prepare form for submission.
463 * @attention When doing method chaining, that should be the very last
464 * method call before displayForm().
466 * @throws MWException
467 * @return HTMLForm $this for chaining calls (since 1.20)
469 function prepareForm() {
470 # Check if we have the info we need
471 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
472 throw new MWException( "You must call setTitle() on an HTMLForm" );
475 # Load data from the request.
482 * Try submitting, with edit token check first
483 * @return Status|bool
485 function tryAuthorizedSubmit() {
489 if ( $this->getMethod() != 'post' ) {
490 $submit = true; // no session check needed
491 } elseif ( $this->getRequest()->wasPosted() ) {
492 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
493 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
494 // Session tokens for logged-out users have no security value.
495 // However, if the user gave one, check it in order to give a nice
496 // "session expired" error instead of "permission denied" or such.
497 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
504 $this->mWasSubmitted
= true;
505 $result = $this->trySubmit();
512 * The here's-one-I-made-earlier option: do the submission if
513 * posted, or display the form with or without funky validation
515 * @return bool|Status Whether submission was successful.
518 $this->prepareForm();
520 $result = $this->tryAuthorizedSubmit();
521 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
525 $this->displayForm( $result );
531 * Validate all the fields, and call the submission callback
532 * function if everything is kosher.
533 * @throws MWException
534 * @return bool|string|array|Status
535 * - Bool true or a good Status object indicates success,
536 * - Bool false indicates no submission was attempted,
537 * - Anything else indicates failure. The value may be a fatal Status
538 * object, an HTML string, or an array of arrays (message keys and
539 * params) or strings (message keys)
541 function trySubmit() {
542 $this->mWasSubmitted
= true;
544 # Check for cancelled submission
545 foreach ( $this->mFlatFields
as $fieldname => $field ) {
546 if ( !empty( $field->mParams
['nodata'] ) ) {
549 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
550 $this->mWasSubmitted
= false;
555 # Check for validation
556 foreach ( $this->mFlatFields
as $fieldname => $field ) {
557 if ( !empty( $field->mParams
['nodata'] ) ) {
560 if ( $field->isHidden( $this->mFieldData
) ) {
563 if ( $field->validate(
564 $this->mFieldData
[$fieldname],
568 return isset( $this->mValidationErrorMessage
)
569 ?
$this->mValidationErrorMessage
570 : array( 'htmlform-invalid-input' );
574 $callback = $this->mSubmitCallback
;
575 if ( !is_callable( $callback ) ) {
576 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
577 'setSubmitCallback() to set one.' );
580 $data = $this->filterDataForSubmit( $this->mFieldData
);
582 $res = call_user_func( $callback, $data, $this );
583 if ( $res === false ) {
584 $this->mWasSubmitted
= false;
591 * Test whether the form was considered to have been submitted or not, i.e.
592 * whether the last call to tryAuthorizedSubmit or trySubmit returned
595 * This will return false until HTMLForm::tryAuthorizedSubmit or
596 * HTMLForm::trySubmit is called.
601 function wasSubmitted() {
602 return $this->mWasSubmitted
;
606 * Set a callback to a function to do something with the form
607 * once it's been successfully validated.
609 * @param callable $cb The function will be passed the output from
610 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
611 * return as documented for HTMLForm::trySubmit
613 * @return HTMLForm $this for chaining calls (since 1.20)
615 function setSubmitCallback( $cb ) {
616 $this->mSubmitCallback
= $cb;
622 * Set a message to display on a validation error.
624 * @param string|array $msg String or Array of valid inputs to wfMessage()
625 * (so each entry can be either a String or Array)
627 * @return HTMLForm $this for chaining calls (since 1.20)
629 function setValidationErrorMessage( $msg ) {
630 $this->mValidationErrorMessage
= $msg;
636 * Set the introductory message, overwriting any existing message.
638 * @param string $msg Complete text of message to display
640 * @return HTMLForm $this for chaining calls (since 1.20)
642 function setIntro( $msg ) {
643 $this->setPreText( $msg );
649 * Set the introductory message, overwriting any existing message.
652 * @param string $msg Complete text of message to display
654 * @return HTMLForm $this for chaining calls (since 1.20)
656 function setPreText( $msg ) {
663 * Add introductory text.
665 * @param string $msg Complete text of message to display
667 * @return HTMLForm $this for chaining calls (since 1.20)
669 function addPreText( $msg ) {
676 * Add header text, inside the form.
678 * @param string $msg Complete text of message to display
679 * @param string|null $section The section to add the header to
681 * @return HTMLForm $this for chaining calls (since 1.20)
683 function addHeaderText( $msg, $section = null ) {
684 if ( is_null( $section ) ) {
685 $this->mHeader
.= $msg;
687 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
688 $this->mSectionHeaders
[$section] = '';
690 $this->mSectionHeaders
[$section] .= $msg;
697 * Set header text, inside the form.
700 * @param string $msg Complete text of message to display
701 * @param string|null $section The section to add the header to
703 * @return HTMLForm $this for chaining calls (since 1.20)
705 function setHeaderText( $msg, $section = null ) {
706 if ( is_null( $section ) ) {
707 $this->mHeader
= $msg;
709 $this->mSectionHeaders
[$section] = $msg;
716 * Add footer text, inside the form.
718 * @param string $msg Complete text of message to display
719 * @param string|null $section The section to add the footer text to
721 * @return HTMLForm $this for chaining calls (since 1.20)
723 function addFooterText( $msg, $section = null ) {
724 if ( is_null( $section ) ) {
725 $this->mFooter
.= $msg;
727 if ( !isset( $this->mSectionFooters
[$section] ) ) {
728 $this->mSectionFooters
[$section] = '';
730 $this->mSectionFooters
[$section] .= $msg;
737 * Set footer text, inside the form.
740 * @param string $msg Complete text of message to display
741 * @param string|null $section The section to add the footer text to
743 * @return HTMLForm $this for chaining calls (since 1.20)
745 function setFooterText( $msg, $section = null ) {
746 if ( is_null( $section ) ) {
747 $this->mFooter
= $msg;
749 $this->mSectionFooters
[$section] = $msg;
756 * Add text to the end of the display.
758 * @param string $msg Complete text of message to display
760 * @return HTMLForm $this for chaining calls (since 1.20)
762 function addPostText( $msg ) {
763 $this->mPost
.= $msg;
769 * Set text at the end of the display.
771 * @param string $msg Complete text of message to display
773 * @return HTMLForm $this for chaining calls (since 1.20)
775 function setPostText( $msg ) {
782 * Add a hidden field to the output
784 * @param string $name Field name. This will be used exactly as entered
785 * @param string $value Field value
786 * @param array $attribs
788 * @return HTMLForm $this for chaining calls (since 1.20)
790 public function addHiddenField( $name, $value, $attribs = array() ) {
791 $attribs +
= array( 'name' => $name );
792 $this->mHiddenFields
[] = array( $value, $attribs );
798 * Add an array of hidden fields to the output
802 * @param array $fields Associative array of fields to add;
803 * mapping names to their values
805 * @return HTMLForm $this for chaining calls
807 public function addHiddenFields( array $fields ) {
808 foreach ( $fields as $name => $value ) {
809 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
816 * Add a button to the form
818 * @param string $name Field name.
819 * @param string $value Field value
820 * @param string $id DOM id for the button (default: null)
821 * @param array $attribs
823 * @return HTMLForm $this for chaining calls (since 1.20)
825 public function addButton( $name, $value, $id = null, $attribs = null ) {
826 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
832 * Set the salt for the edit token.
834 * Only useful when the method is "post".
837 * @param string|array $salt Salt to use
838 * @return HTMLForm $this For chaining calls
840 public function setTokenSalt( $salt ) {
841 $this->mTokenSalt
= $salt;
847 * Display the form (sending to the context's OutputPage object), with an
848 * appropriate error message or stack of messages, and any validation errors, etc.
850 * @attention You should call prepareForm() before calling this function.
851 * Moreover, when doing method chaining this should be the very last method
852 * call just after prepareForm().
854 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
856 * @return void Nothing, should be last call
858 function displayForm( $submitResult ) {
859 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
863 * Returns the raw HTML generated by the form
865 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
869 function getHTML( $submitResult ) {
870 # For good measure (it is the default)
871 $this->getOutput()->preventClickjacking();
872 $this->getOutput()->addModules( 'mediawiki.htmlform' );
875 . $this->getErrors( $submitResult )
876 // In OOUI forms, we handle mHeader elsewhere. FIXME This is horrible.
877 . ( $this->getDisplayFormat() === 'ooui' ?
'' : $this->mHeader
)
879 . $this->getHiddenFields()
880 . $this->getButtons()
883 $html = $this->wrapForm( $html );
885 return '' . $this->mPre
. $html . $this->mPost
;
889 * Get HTML attributes for the `<form>` tag.
892 protected function getFormAttributes() {
893 # Use multipart/form-data
894 $encType = $this->mUseMultipart
895 ?
'multipart/form-data'
896 : 'application/x-www-form-urlencoded';
899 'action' => $this->getAction(),
900 'method' => $this->getMethod(),
901 'enctype' => $encType,
903 if ( !empty( $this->mId
) ) {
904 $attribs['id'] = $this->mId
;
910 * Wrap the form innards in an actual "<form>" element
912 * @param string $html HTML contents to wrap.
914 * @return string Wrapped HTML.
916 function wrapForm( $html ) {
917 # Include a <fieldset> wrapper for style, if requested.
918 if ( $this->mWrapperLegend
!== false ) {
919 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
920 $html = Xml
::fieldset( $legend, $html );
923 return Html
::rawElement( 'form', $this->getFormAttributes() +
array( 'class' => 'visualClear' ), $html );
927 * Get the hidden fields that should go inside the form.
928 * @return string HTML.
930 function getHiddenFields() {
932 if ( $this->getMethod() == 'post' ) {
933 $html .= Html
::hidden(
935 $this->getUser()->getEditToken( $this->mTokenSalt
),
936 array( 'id' => 'wpEditToken' )
938 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
941 $articlePath = $this->getConfig()->get( 'ArticlePath' );
942 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
943 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
946 foreach ( $this->mHiddenFields
as $data ) {
947 list( $value, $attribs ) = $data;
948 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
955 * Get the submit and (potentially) reset buttons.
956 * @return string HTML.
958 function getButtons() {
960 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
962 if ( $this->mShowSubmit
) {
965 if ( isset( $this->mSubmitID
) ) {
966 $attribs['id'] = $this->mSubmitID
;
969 if ( isset( $this->mSubmitName
) ) {
970 $attribs['name'] = $this->mSubmitName
;
973 if ( isset( $this->mSubmitTooltip
) ) {
974 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
977 $attribs['class'] = array( 'mw-htmlform-submit' );
979 if ( $useMediaWikiUIEverywhere ) {
980 foreach ( $this->mSubmitFlags
as $flag ) {
981 array_push( $attribs['class'], 'mw-ui-' . $flag );
983 array_push( $attribs['class'], 'mw-ui-button' );
986 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
989 if ( $this->mShowReset
) {
990 $buttons .= Html
::element(
994 'value' => $this->msg( 'htmlform-reset' )->text(),
995 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
1000 foreach ( $this->mButtons
as $button ) {
1003 'name' => $button['name'],
1004 'value' => $button['value']
1007 if ( $button['attribs'] ) {
1008 $attrs +
= $button['attribs'];
1011 if ( isset( $button['id'] ) ) {
1012 $attrs['id'] = $button['id'];
1015 if ( $useMediaWikiUIEverywhere ) {
1016 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1017 $attrs['class'][] = 'mw-ui-button';
1020 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1023 $html = Html
::rawElement( 'span',
1024 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1030 * Get the whole body of the form.
1033 function getBody() {
1034 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1038 * Format and display an error message stack.
1040 * @param string|array|Status $errors
1044 function getErrors( $errors ) {
1045 if ( $errors instanceof Status
) {
1046 if ( $errors->isOK() ) {
1049 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1051 } elseif ( is_array( $errors ) ) {
1052 $errorstr = $this->formatErrors( $errors );
1054 $errorstr = $errors;
1058 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1063 * Format a stack of error messages into a single HTML string
1065 * @param array $errors Array of message keys/values
1067 * @return string HTML, a "<ul>" list of errors
1069 public function formatErrors( $errors ) {
1072 foreach ( $errors as $error ) {
1073 if ( is_array( $error ) ) {
1074 $msg = array_shift( $error );
1080 $errorstr .= Html
::rawElement(
1083 $this->msg( $msg, $error )->parse()
1087 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1093 * Set the text for the submit button
1095 * @param string $t Plaintext
1097 * @return HTMLForm $this for chaining calls (since 1.20)
1099 function setSubmitText( $t ) {
1100 $this->mSubmitText
= $t;
1106 * Identify that the submit button in the form has a destructive action
1109 public function setSubmitDestructive() {
1110 $this->mSubmitFlags
= array( 'destructive', 'primary' );
1114 * Identify that the submit button in the form has a progressive action
1117 public function setSubmitProgressive() {
1118 $this->mSubmitFlags
= array( 'progressive', 'primary' );
1122 * Set the text for the submit button to a message
1125 * @param string|Message $msg Message key or Message object
1127 * @return HTMLForm $this for chaining calls (since 1.20)
1129 public function setSubmitTextMsg( $msg ) {
1130 if ( !$msg instanceof Message
) {
1131 $msg = $this->msg( $msg );
1133 $this->setSubmitText( $msg->text() );
1139 * Get the text for the submit button, either customised or a default.
1142 function getSubmitText() {
1143 return $this->mSubmitText
1144 ?
$this->mSubmitText
1145 : $this->msg( 'htmlform-submit' )->text();
1149 * @param string $name Submit button name
1151 * @return HTMLForm $this for chaining calls (since 1.20)
1153 public function setSubmitName( $name ) {
1154 $this->mSubmitName
= $name;
1160 * @param string $name Tooltip for the submit button
1162 * @return HTMLForm $this for chaining calls (since 1.20)
1164 public function setSubmitTooltip( $name ) {
1165 $this->mSubmitTooltip
= $name;
1171 * Set the id for the submit button.
1175 * @todo FIXME: Integrity of $t is *not* validated
1176 * @return HTMLForm $this for chaining calls (since 1.20)
1178 function setSubmitID( $t ) {
1179 $this->mSubmitID
= $t;
1185 * Stop a default submit button being shown for this form. This implies that an
1186 * alternate submit method must be provided manually.
1190 * @param bool $suppressSubmit Set to false to re-enable the button again
1192 * @return HTMLForm $this for chaining calls
1194 function suppressDefaultSubmit( $suppressSubmit = true ) {
1195 $this->mShowSubmit
= !$suppressSubmit;
1201 * Set the id of the \<table\> or outermost \<div\> element.
1205 * @param string $id New value of the id attribute, or "" to remove
1207 * @return HTMLForm $this for chaining calls
1209 public function setTableId( $id ) {
1210 $this->mTableId
= $id;
1216 * @param string $id DOM id for the form
1218 * @return HTMLForm $this for chaining calls (since 1.20)
1220 public function setId( $id ) {
1227 * Prompt the whole form to be wrapped in a "<fieldset>", with
1228 * this text as its "<legend>" element.
1230 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1231 * If true, a wrapper will be displayed, but no legend.
1232 * If a string, a wrapper will be displayed with that string as a legend.
1233 * The string will be escaped before being output (this doesn't support HTML).
1235 * @return HTMLForm $this for chaining calls (since 1.20)
1237 public function setWrapperLegend( $legend ) {
1238 $this->mWrapperLegend
= $legend;
1244 * Prompt the whole form to be wrapped in a "<fieldset>", with
1245 * this message as its "<legend>" element.
1248 * @param string|Message $msg Message key or Message object
1250 * @return HTMLForm $this for chaining calls (since 1.20)
1252 public function setWrapperLegendMsg( $msg ) {
1253 if ( !$msg instanceof Message
) {
1254 $msg = $this->msg( $msg );
1256 $this->setWrapperLegend( $msg->text() );
1262 * Set the prefix for various default messages
1263 * @todo Currently only used for the "<fieldset>" legend on forms
1264 * with multiple sections; should be used elsewhere?
1268 * @return HTMLForm $this for chaining calls (since 1.20)
1270 function setMessagePrefix( $p ) {
1271 $this->mMessagePrefix
= $p;
1277 * Set the title for form submission
1279 * @param Title $t Title of page the form is on/should be posted to
1281 * @return HTMLForm $this for chaining calls (since 1.20)
1283 function setTitle( $t ) {
1293 function getTitle() {
1294 return $this->mTitle
=== false
1295 ?
$this->getContext()->getTitle()
1300 * Set the method used to submit the form
1302 * @param string $method
1304 * @return HTMLForm $this for chaining calls (since 1.20)
1306 public function setMethod( $method = 'post' ) {
1307 $this->mMethod
= strtolower( $method );
1313 * @return string Always lowercase
1315 public function getMethod() {
1316 return $this->mMethod
;
1322 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1324 * @param string $sectionName ID attribute of the "<table>" tag for this
1325 * section, ignored if empty.
1326 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1327 * each subsection, ignored if empty.
1328 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1332 public function displaySection( $fields,
1334 $fieldsetIDPrefix = '',
1335 &$hasUserVisibleFields = false ) {
1336 $displayFormat = $this->getDisplayFormat();
1339 $subsectionHtml = '';
1342 // Conveniently, PHP method names are case-insensitive.
1343 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1345 foreach ( $fields as $key => $value ) {
1346 if ( $value instanceof HTMLFormField
) {
1347 $v = empty( $value->mParams
['nodata'] )
1348 ?
$this->mFieldData
[$key]
1349 : $value->getDefault();
1350 $html .= $value->$getFieldHtmlMethod( $v );
1352 $labelValue = trim( $value->getLabel() );
1353 if ( $labelValue != ' ' && $labelValue !== '' ) {
1357 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1358 get_class( $value ) !== 'HTMLApiField'
1360 $hasUserVisibleFields = true;
1362 } elseif ( is_array( $value ) ) {
1363 $subsectionHasVisibleFields = false;
1365 $this->displaySection( $value,
1367 "$fieldsetIDPrefix$key-",
1368 $subsectionHasVisibleFields );
1371 if ( $subsectionHasVisibleFields === true ) {
1372 // Display the section with various niceties.
1373 $hasUserVisibleFields = true;
1375 $legend = $this->getLegend( $key );
1377 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1378 $section = $this->mSectionHeaders
[$key] . $section;
1380 if ( isset( $this->mSectionFooters
[$key] ) ) {
1381 $section .= $this->mSectionFooters
[$key];
1384 $attributes = array();
1385 if ( $fieldsetIDPrefix ) {
1386 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1388 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1390 // Just return the inputs, nothing fancy.
1391 $subsectionHtml .= $section;
1396 if ( $displayFormat !== 'raw' ) {
1399 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1400 $classes[] = 'mw-htmlform-nolabel';
1404 'class' => implode( ' ', $classes ),
1407 if ( $sectionName ) {
1408 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1411 if ( $displayFormat === 'table' ) {
1412 $html = Html
::rawElement( 'table',
1414 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1415 } elseif ( $displayFormat === 'inline' ) {
1416 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1417 } elseif ( $displayFormat === 'ooui' ) {
1419 'classes' => $classes,
1421 if ( $sectionName ) {
1422 $config['id'] = Sanitizer
::escapeId( $sectionName );
1424 if ( is_string( $this->mWrapperLegend
) ) {
1425 $config['label'] = $this->mWrapperLegend
;
1427 $fieldset = new OOUI\
FieldsetLayout( $config );
1428 // Ewww. We should pass this as $config['items'], but there might be string snippets.
1429 $fieldset->group
->appendContent( new OOUI\
HtmlSnippet( $html ) );
1432 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1436 if ( $subsectionHtml ) {
1437 if ( $this->mSubSectionBeforeFields
) {
1438 return $subsectionHtml . "\n" . $html;
1440 return $html . "\n" . $subsectionHtml;
1448 * Construct the form fields from the Descriptor array
1450 function loadData() {
1451 $fieldData = array();
1453 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1454 if ( !empty( $field->mParams
['nodata'] ) ) {
1456 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1457 $fieldData[$fieldname] = $field->getDefault();
1459 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1464 foreach ( $fieldData as $name => &$value ) {
1465 $field = $this->mFlatFields
[$name];
1466 $value = $field->filter( $value, $this->mFlatFields
);
1469 $this->mFieldData
= $fieldData;
1473 * Stop a reset button being shown for this form
1475 * @param bool $suppressReset Set to false to re-enable the button again
1477 * @return HTMLForm $this for chaining calls (since 1.20)
1479 function suppressReset( $suppressReset = true ) {
1480 $this->mShowReset
= !$suppressReset;
1486 * Overload this if you want to apply special filtration routines
1487 * to the form as a whole, after it's submitted but before it's
1490 * @param array $data
1494 function filterDataForSubmit( $data ) {
1499 * Get a string to go in the "<legend>" of a section fieldset.
1500 * Override this if you want something more complicated.
1502 * @param string $key
1506 public function getLegend( $key ) {
1507 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1511 * Set the value for the action attribute of the form.
1512 * When set to false (which is the default state), the set title is used.
1516 * @param string|bool $action
1518 * @return HTMLForm $this for chaining calls (since 1.20)
1520 public function setAction( $action ) {
1521 $this->mAction
= $action;
1527 * Get the value for the action attribute of the form.
1533 public function getAction() {
1534 // If an action is alredy provided, return it
1535 if ( $this->mAction
!== false ) {
1536 return $this->mAction
;
1539 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1540 // Check whether we are in GET mode and the ArticlePath contains a "?"
1541 // meaning that getLocalURL() would return something like "index.php?title=...".
1542 // As browser remove the query string before submitting GET forms,
1543 // it means that the title would be lost. In such case use wfScript() instead
1544 // and put title in an hidden field (see getHiddenFields()).
1545 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1549 return $this->getTitle()->getLocalURL();