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 * 'options' -- associative array mapping labels to values.
55 * Some field types support multi-level arrays.
56 * 'options-messages' -- associative array mapping message keys to values.
57 * Some field types support multi-level arrays.
58 * 'options-message' -- message key to be parsed to extract the list of
59 * options (like 'ipbreason-dropdown').
60 * 'label-message' -- message key for a message to use as the label.
61 * can be an array of msg key and then parameters to
63 * 'label' -- alternatively, a raw text message. Overridden by
65 * 'help' -- message text for a message to use as a help text.
66 * 'help-message' -- message key for a message to use as a help text.
67 * can be an array of msg key and then parameters to
69 * Overwrites 'help-messages' and 'help'.
70 * 'help-messages' -- array of message key. As above, each item can
71 * be an array of msg key and then parameters.
73 * 'required' -- passed through to the object, indicating that it
74 * is a required field.
75 * 'size' -- the length of text fields
76 * 'filter-callback -- a function name to give you the chance to
77 * massage the inputted value before it's processed.
78 * @see HTMLForm::filter()
79 * 'validation-callback' -- a function name to give you the chance
80 * to impose extra validation on the field input.
81 * @see HTMLForm::validate()
82 * 'name' -- By default, the 'name' attribute of the input field
83 * is "wp{$fieldname}". If you want a different name
84 * (eg one without the "wp" prefix), specify it here and
85 * it will be used without modification.
87 * Since 1.20, you can chain mutators to ease the form generation:
90 * $form = new HTMLForm( $someFields );
91 * $form->setMethod( 'get' )
92 * ->setWrapperLegendMsg( 'message-key' )
94 * ->displayForm( '' );
96 * Note that you will have prepareForm and displayForm at the end. Other
97 * methods call done after that would simply not be part of the form :(
99 * @todo Document 'section' / 'subsection' stuff
101 class HTMLForm
extends ContextSource
{
102 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
103 public static $typeMappings = array(
104 'api' => 'HTMLApiField',
105 'text' => 'HTMLTextField',
106 'textarea' => 'HTMLTextAreaField',
107 'select' => 'HTMLSelectField',
108 'radio' => 'HTMLRadioField',
109 'multiselect' => 'HTMLMultiSelectField',
110 'limitselect' => 'HTMLSelectLimitField',
111 'check' => 'HTMLCheckField',
112 'toggle' => 'HTMLCheckField',
113 'int' => 'HTMLIntField',
114 'float' => 'HTMLFloatField',
115 'info' => 'HTMLInfoField',
116 'selectorother' => 'HTMLSelectOrOtherField',
117 'selectandother' => 'HTMLSelectAndOtherField',
118 'namespaceselect' => 'HTMLSelectNamespace',
119 'tagfilter' => 'HTMLTagFilter',
120 'submit' => 'HTMLSubmitField',
121 'hidden' => 'HTMLHiddenField',
122 'edittools' => 'HTMLEditTools',
123 'checkmatrix' => 'HTMLCheckMatrix',
124 'cloner' => 'HTMLFormFieldCloner',
125 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
126 // HTMLTextField will output the correct type="" attribute automagically.
127 // There are about four zillion other HTML5 input types, like range, but
128 // we don't use those at the moment, so no point in adding all of them.
129 'email' => 'HTMLTextField',
130 'password' => 'HTMLTextField',
131 'url' => 'HTMLTextField',
136 protected $mMessagePrefix;
138 /** @var HTMLFormField[] */
139 protected $mFlatFields;
141 protected $mFieldTree;
142 protected $mShowReset = false;
143 protected $mShowSubmit = true;
144 protected $mSubmitModifierClass = 'mw-ui-constructive';
146 protected $mSubmitCallback;
147 protected $mValidationErrorMessage;
149 protected $mPre = '';
150 protected $mHeader = '';
151 protected $mFooter = '';
152 protected $mSectionHeaders = array();
153 protected $mSectionFooters = array();
154 protected $mPost = '';
156 protected $mTableId = '';
158 protected $mSubmitID;
159 protected $mSubmitName;
160 protected $mSubmitText;
161 protected $mSubmitTooltip;
164 protected $mMethod = 'post';
165 protected $mWasSubmitted = false;
168 * Form action URL. false means we will use the URL to set Title
172 protected $mAction = false;
174 protected $mUseMultipart = false;
175 protected $mHiddenFields = array();
176 protected $mButtons = array();
178 protected $mWrapperLegend = false;
181 * Salt for the edit token.
184 protected $mTokenSalt = '';
187 * If true, sections that contain both fields and subsections will
188 * render their subsections before their fields.
190 * Subclasses may set this to false to render subsections after fields
193 protected $mSubSectionBeforeFields = true;
196 * Format in which to display form. For viable options,
197 * @see $availableDisplayFormats
200 protected $displayFormat = 'table';
203 * Available formats in which to display the form
206 protected $availableDisplayFormats = array(
214 * Available formats in which to display the form
217 protected $availableSubclassDisplayFormats = array(
222 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
224 * @throws MWException When the display format requested is not known
225 * @param string $displayFormat
226 * @param mixed $arguments... Additional arguments to pass to the constructor.
229 public static function factory( $displayFormat/*, $arguments...*/ ) {
230 $arguments = func_get_args();
231 array_shift( $arguments );
233 switch ( $displayFormat ) {
235 $reflector = new ReflectionClass( 'VFormHTMLForm' );
236 return $reflector->newInstanceArgs( $arguments );
238 $reflector = new ReflectionClass( 'HTMLForm' );
239 $form = $reflector->newInstanceArgs( $arguments );
240 $form->setDisplayFormat( $displayFormat );
246 * Build a new HTMLForm from an array of field attributes
248 * @param array $descriptor Array of Field constructs, as described above
249 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
250 * Obviates the need to call $form->setTitle()
251 * @param string $messagePrefix A prefix to go in front of default messages
253 public function __construct( $descriptor, /*IContextSource*/ $context = null,
256 if ( $context instanceof IContextSource
) {
257 $this->setContext( $context );
258 $this->mTitle
= false; // We don't need them to set a title
259 $this->mMessagePrefix
= $messagePrefix;
260 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
261 $this->mMessagePrefix
= $messagePrefix;
262 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
264 // it's actually $messagePrefix
265 $this->mMessagePrefix
= $context;
268 // Evil hack for mobile :(
269 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat
=== 'table' ) {
270 $this->displayFormat
= 'div';
273 // Expand out into a tree.
274 $loadedDescriptor = array();
275 $this->mFlatFields
= array();
277 foreach ( $descriptor as $fieldname => $info ) {
278 $section = isset( $info['section'] )
282 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
283 $this->mUseMultipart
= true;
286 $field = static::loadInputFromParameters( $fieldname, $info, $this );
288 $setSection =& $loadedDescriptor;
290 $sectionParts = explode( '/', $section );
292 while ( count( $sectionParts ) ) {
293 $newName = array_shift( $sectionParts );
295 if ( !isset( $setSection[$newName] ) ) {
296 $setSection[$newName] = array();
299 $setSection =& $setSection[$newName];
303 $setSection[$fieldname] = $field;
304 $this->mFlatFields
[$fieldname] = $field;
307 $this->mFieldTree
= $loadedDescriptor;
311 * Set format in which to display the form
313 * @param string $format The name of the format to use, must be one of
314 * $this->availableDisplayFormats
316 * @throws MWException
318 * @return HTMLForm $this for chaining calls (since 1.20)
320 public function setDisplayFormat( $format ) {
322 in_array( $format, $this->availableSubclassDisplayFormats
) ||
323 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
325 throw new MWException( 'Cannot change display format after creation, ' .
326 'use HTMLForm::factory() instead' );
329 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
330 throw new MWException( 'Display format must be one of ' .
331 print_r( $this->availableDisplayFormats
, true ) );
334 // Evil hack for mobile :(
335 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
339 $this->displayFormat
= $format;
345 * Getter for displayFormat
349 public function getDisplayFormat() {
350 return $this->displayFormat
;
354 * Test if displayFormat is 'vform'
356 * @deprecated since 1.25
359 public function isVForm() {
364 * Get the HTMLFormField subclass for this descriptor.
366 * The descriptor can be passed either 'class' which is the name of
367 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
368 * This makes sure the 'class' is always set, and also is returned by
369 * this function for ease.
373 * @param string $fieldname Name of the field
374 * @param array $descriptor Input Descriptor, as described above
376 * @throws MWException
377 * @return string Name of a HTMLFormField subclass
379 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
380 if ( isset( $descriptor['class'] ) ) {
381 $class = $descriptor['class'];
382 } elseif ( isset( $descriptor['type'] ) ) {
383 $class = static::$typeMappings[$descriptor['type']];
384 $descriptor['class'] = $class;
390 throw new MWException( "Descriptor with no class for $fieldname: "
391 . print_r( $descriptor, true ) );
398 * Initialise a new Object for the field
400 * @param string $fieldname Name of the field
401 * @param array $descriptor Input Descriptor, as described above
402 * @param HTMLForm|null $parent Parent instance of HTMLForm
404 * @throws MWException
405 * @return HTMLFormField Instance of a subclass of HTMLFormField
407 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm
$parent = null ) {
408 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
410 $descriptor['fieldname'] = $fieldname;
412 $descriptor['parent'] = $parent;
415 # @todo This will throw a fatal error whenever someone try to use
416 # 'class' to feed a CSS class instead of 'cssclass'. Would be
417 # great to avoid the fatal error and show a nice error.
418 $obj = new $class( $descriptor );
424 * Prepare form for submission.
426 * @attention When doing method chaining, that should be the very last
427 * method call before displayForm().
429 * @throws MWException
430 * @return HTMLForm $this for chaining calls (since 1.20)
432 function prepareForm() {
433 # Check if we have the info we need
434 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
435 throw new MWException( "You must call setTitle() on an HTMLForm" );
438 # Load data from the request.
445 * Try submitting, with edit token check first
446 * @return Status|bool
448 function tryAuthorizedSubmit() {
452 if ( $this->getMethod() != 'post' ) {
453 $submit = true; // no session check needed
454 } elseif ( $this->getRequest()->wasPosted() ) {
455 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
456 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
457 // Session tokens for logged-out users have no security value.
458 // However, if the user gave one, check it in order to give a nice
459 // "session expired" error instead of "permission denied" or such.
460 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
467 $this->mWasSubmitted
= true;
468 $result = $this->trySubmit();
475 * The here's-one-I-made-earlier option: do the submission if
476 * posted, or display the form with or without funky validation
478 * @return bool|Status Whether submission was successful.
481 $this->prepareForm();
483 $result = $this->tryAuthorizedSubmit();
484 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
488 $this->displayForm( $result );
494 * Validate all the fields, and call the submission callback
495 * function if everything is kosher.
496 * @throws MWException
497 * @return bool|string|array|Status
498 * - Bool true or a good Status object indicates success,
499 * - Bool false indicates no submission was attempted,
500 * - Anything else indicates failure. The value may be a fatal Status
501 * object, an HTML string, or an array of arrays (message keys and
502 * params) or strings (message keys)
504 function trySubmit() {
505 $this->mWasSubmitted
= true;
507 # Check for cancelled submission
508 foreach ( $this->mFlatFields
as $fieldname => $field ) {
509 if ( !empty( $field->mParams
['nodata'] ) ) {
512 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
513 $this->mWasSubmitted
= false;
518 # Check for validation
519 foreach ( $this->mFlatFields
as $fieldname => $field ) {
520 if ( !empty( $field->mParams
['nodata'] ) ) {
523 if ( $field->isHidden( $this->mFieldData
) ) {
526 if ( $field->validate(
527 $this->mFieldData
[$fieldname],
531 return isset( $this->mValidationErrorMessage
)
532 ?
$this->mValidationErrorMessage
533 : array( 'htmlform-invalid-input' );
537 $callback = $this->mSubmitCallback
;
538 if ( !is_callable( $callback ) ) {
539 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
540 'setSubmitCallback() to set one.' );
543 $data = $this->filterDataForSubmit( $this->mFieldData
);
545 $res = call_user_func( $callback, $data, $this );
546 if ( $res === false ) {
547 $this->mWasSubmitted
= false;
554 * Test whether the form was considered to have been submitted or not, i.e.
555 * whether the last call to tryAuthorizedSubmit or trySubmit returned
558 * This will return false until HTMLForm::tryAuthorizedSubmit or
559 * HTMLForm::trySubmit is called.
564 function wasSubmitted() {
565 return $this->mWasSubmitted
;
569 * Set a callback to a function to do something with the form
570 * once it's been successfully validated.
572 * @param callable $cb The function will be passed the output from
573 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
574 * return as documented for HTMLForm::trySubmit
576 * @return HTMLForm $this for chaining calls (since 1.20)
578 function setSubmitCallback( $cb ) {
579 $this->mSubmitCallback
= $cb;
585 * Set a message to display on a validation error.
587 * @param string|array $msg String or Array of valid inputs to wfMessage()
588 * (so each entry can be either a String or Array)
590 * @return HTMLForm $this for chaining calls (since 1.20)
592 function setValidationErrorMessage( $msg ) {
593 $this->mValidationErrorMessage
= $msg;
599 * Set the introductory message, overwriting any existing message.
601 * @param string $msg Complete text of message to display
603 * @return HTMLForm $this for chaining calls (since 1.20)
605 function setIntro( $msg ) {
606 $this->setPreText( $msg );
612 * Set the introductory message, overwriting any existing message.
615 * @param string $msg Complete text of message to display
617 * @return HTMLForm $this for chaining calls (since 1.20)
619 function setPreText( $msg ) {
626 * Add introductory text.
628 * @param string $msg Complete text of message to display
630 * @return HTMLForm $this for chaining calls (since 1.20)
632 function addPreText( $msg ) {
639 * Add header text, inside the form.
641 * @param string $msg Complete text of message to display
642 * @param string|null $section The section to add the header to
644 * @return HTMLForm $this for chaining calls (since 1.20)
646 function addHeaderText( $msg, $section = null ) {
647 if ( is_null( $section ) ) {
648 $this->mHeader
.= $msg;
650 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
651 $this->mSectionHeaders
[$section] = '';
653 $this->mSectionHeaders
[$section] .= $msg;
660 * Set header text, inside the form.
663 * @param string $msg Complete text of message to display
664 * @param string|null $section The section to add the header to
666 * @return HTMLForm $this for chaining calls (since 1.20)
668 function setHeaderText( $msg, $section = null ) {
669 if ( is_null( $section ) ) {
670 $this->mHeader
= $msg;
672 $this->mSectionHeaders
[$section] = $msg;
679 * Add footer text, inside the form.
681 * @param string $msg Complete text of message to display
682 * @param string|null $section The section to add the footer text to
684 * @return HTMLForm $this for chaining calls (since 1.20)
686 function addFooterText( $msg, $section = null ) {
687 if ( is_null( $section ) ) {
688 $this->mFooter
.= $msg;
690 if ( !isset( $this->mSectionFooters
[$section] ) ) {
691 $this->mSectionFooters
[$section] = '';
693 $this->mSectionFooters
[$section] .= $msg;
700 * Set footer text, inside the form.
703 * @param string $msg Complete text of message to display
704 * @param string|null $section The section to add the footer text to
706 * @return HTMLForm $this for chaining calls (since 1.20)
708 function setFooterText( $msg, $section = null ) {
709 if ( is_null( $section ) ) {
710 $this->mFooter
= $msg;
712 $this->mSectionFooters
[$section] = $msg;
719 * Add text to the end of the display.
721 * @param string $msg Complete text of message to display
723 * @return HTMLForm $this for chaining calls (since 1.20)
725 function addPostText( $msg ) {
726 $this->mPost
.= $msg;
732 * Set text at the end of the display.
734 * @param string $msg Complete text of message to display
736 * @return HTMLForm $this for chaining calls (since 1.20)
738 function setPostText( $msg ) {
745 * Add a hidden field to the output
747 * @param string $name Field name. This will be used exactly as entered
748 * @param string $value Field value
749 * @param array $attribs
751 * @return HTMLForm $this for chaining calls (since 1.20)
753 public function addHiddenField( $name, $value, $attribs = array() ) {
754 $attribs +
= array( 'name' => $name );
755 $this->mHiddenFields
[] = array( $value, $attribs );
761 * Add an array of hidden fields to the output
765 * @param array $fields Associative array of fields to add;
766 * mapping names to their values
768 * @return HTMLForm $this for chaining calls
770 public function addHiddenFields( array $fields ) {
771 foreach ( $fields as $name => $value ) {
772 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
779 * Add a button to the form
781 * @param string $name Field name.
782 * @param string $value Field value
783 * @param string $id DOM id for the button (default: null)
784 * @param array $attribs
786 * @return HTMLForm $this for chaining calls (since 1.20)
788 public function addButton( $name, $value, $id = null, $attribs = null ) {
789 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
795 * Set the salt for the edit token.
797 * Only useful when the method is "post".
800 * @param string|array $salt Salt to use
801 * @return HTMLForm $this For chaining calls
803 public function setTokenSalt( $salt ) {
804 $this->mTokenSalt
= $salt;
810 * Display the form (sending to the context's OutputPage object), with an
811 * appropriate error message or stack of messages, and any validation errors, etc.
813 * @attention You should call prepareForm() before calling this function.
814 * Moreover, when doing method chaining this should be the very last method
815 * call just after prepareForm().
817 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
819 * @return void Nothing, should be last call
821 function displayForm( $submitResult ) {
822 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
826 * Returns the raw HTML generated by the form
828 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
832 function getHTML( $submitResult ) {
833 # For good measure (it is the default)
834 $this->getOutput()->preventClickjacking();
835 $this->getOutput()->addModules( 'mediawiki.htmlform' );
838 . $this->getErrors( $submitResult )
841 . $this->getHiddenFields()
842 . $this->getButtons()
845 $html = $this->wrapForm( $html );
847 return '' . $this->mPre
. $html . $this->mPost
;
851 * Get HTML attributes for the `<form>` tag.
854 protected function getFormAttributes() {
855 # Use multipart/form-data
856 $encType = $this->mUseMultipart
857 ?
'multipart/form-data'
858 : 'application/x-www-form-urlencoded';
861 'action' => $this->getAction(),
862 'method' => $this->getMethod(),
863 'class' => array( 'visualClear' ),
864 'enctype' => $encType,
866 if ( !empty( $this->mId
) ) {
867 $attribs['id'] = $this->mId
;
873 * Wrap the form innards in an actual "<form>" element
875 * @param string $html HTML contents to wrap.
877 * @return string Wrapped HTML.
879 function wrapForm( $html ) {
880 # Include a <fieldset> wrapper for style, if requested.
881 if ( $this->mWrapperLegend
!== false ) {
882 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
885 return Html
::rawElement( 'form', $this->getFormAttributes(), $html );
889 * Get the hidden fields that should go inside the form.
890 * @return string HTML.
892 function getHiddenFields() {
894 if ( $this->getMethod() == 'post' ) {
895 $html .= Html
::hidden(
897 $this->getUser()->getEditToken( $this->mTokenSalt
),
898 array( 'id' => 'wpEditToken' )
900 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
903 $articlePath = $this->getConfig()->get( 'ArticlePath' );
904 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
905 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
908 foreach ( $this->mHiddenFields
as $data ) {
909 list( $value, $attribs ) = $data;
910 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
917 * Get the submit and (potentially) reset buttons.
918 * @return string HTML.
920 function getButtons() {
922 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
924 if ( $this->mShowSubmit
) {
927 if ( isset( $this->mSubmitID
) ) {
928 $attribs['id'] = $this->mSubmitID
;
931 if ( isset( $this->mSubmitName
) ) {
932 $attribs['name'] = $this->mSubmitName
;
935 if ( isset( $this->mSubmitTooltip
) ) {
936 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
939 $attribs['class'] = array( 'mw-htmlform-submit' );
941 if ( $useMediaWikiUIEverywhere ) {
942 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass
);
945 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
948 if ( $this->mShowReset
) {
949 $buttons .= Html
::element(
953 'value' => $this->msg( 'htmlform-reset' )->text(),
954 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
959 foreach ( $this->mButtons
as $button ) {
962 'name' => $button['name'],
963 'value' => $button['value']
966 if ( $button['attribs'] ) {
967 $attrs +
= $button['attribs'];
970 if ( isset( $button['id'] ) ) {
971 $attrs['id'] = $button['id'];
974 if ( $useMediaWikiUIEverywhere ) {
975 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
976 $attrs['class'][] = 'mw-ui-button';
979 $buttons .= Html
::element( 'input', $attrs ) . "\n";
982 $html = Html
::rawElement( 'span',
983 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
989 * Get the whole body of the form.
993 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
997 * Format and display an error message stack.
999 * @param string|array|Status $errors
1003 function getErrors( $errors ) {
1004 if ( $errors instanceof Status
) {
1005 if ( $errors->isOK() ) {
1008 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1010 } elseif ( is_array( $errors ) ) {
1011 $errorstr = $this->formatErrors( $errors );
1013 $errorstr = $errors;
1017 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1022 * Format a stack of error messages into a single HTML string
1024 * @param array $errors Array of message keys/values
1026 * @return string HTML, a "<ul>" list of errors
1028 public function formatErrors( $errors ) {
1031 foreach ( $errors as $error ) {
1032 if ( is_array( $error ) ) {
1033 $msg = array_shift( $error );
1039 $errorstr .= Html
::rawElement(
1042 $this->msg( $msg, $error )->parse()
1046 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1052 * Set the text for the submit button
1054 * @param string $t Plaintext
1056 * @return HTMLForm $this for chaining calls (since 1.20)
1058 function setSubmitText( $t ) {
1059 $this->mSubmitText
= $t;
1065 * Identify that the submit button in the form has a destructive action
1068 public function setSubmitDestructive() {
1069 $this->mSubmitModifierClass
= 'mw-ui-destructive';
1073 * Identify that the submit button in the form has a progressive action
1076 public function setSubmitProgressive() {
1077 $this->mSubmitModifierClass
= 'mw-ui-progressive';
1081 * Set the text for the submit button to a message
1084 * @param string|Message $msg Message key or Message object
1086 * @return HTMLForm $this for chaining calls (since 1.20)
1088 public function setSubmitTextMsg( $msg ) {
1089 if ( !$msg instanceof Message
) {
1090 $msg = $this->msg( $msg );
1092 $this->setSubmitText( $msg->text() );
1098 * Get the text for the submit button, either customised or a default.
1101 function getSubmitText() {
1102 return $this->mSubmitText
1103 ?
$this->mSubmitText
1104 : $this->msg( 'htmlform-submit' )->text();
1108 * @param string $name Submit button name
1110 * @return HTMLForm $this for chaining calls (since 1.20)
1112 public function setSubmitName( $name ) {
1113 $this->mSubmitName
= $name;
1119 * @param string $name Tooltip for the submit button
1121 * @return HTMLForm $this for chaining calls (since 1.20)
1123 public function setSubmitTooltip( $name ) {
1124 $this->mSubmitTooltip
= $name;
1130 * Set the id for the submit button.
1134 * @todo FIXME: Integrity of $t is *not* validated
1135 * @return HTMLForm $this for chaining calls (since 1.20)
1137 function setSubmitID( $t ) {
1138 $this->mSubmitID
= $t;
1144 * Stop a default submit button being shown for this form. This implies that an
1145 * alternate submit method must be provided manually.
1149 * @param bool $suppressSubmit Set to false to re-enable the button again
1151 * @return HTMLForm $this for chaining calls
1153 function suppressDefaultSubmit( $suppressSubmit = true ) {
1154 $this->mShowSubmit
= !$suppressSubmit;
1160 * Set the id of the \<table\> or outermost \<div\> element.
1164 * @param string $id New value of the id attribute, or "" to remove
1166 * @return HTMLForm $this for chaining calls
1168 public function setTableId( $id ) {
1169 $this->mTableId
= $id;
1175 * @param string $id DOM id for the form
1177 * @return HTMLForm $this for chaining calls (since 1.20)
1179 public function setId( $id ) {
1186 * Prompt the whole form to be wrapped in a "<fieldset>", with
1187 * this text as its "<legend>" element.
1189 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1190 * false for no <legend>
1193 * @return HTMLForm $this for chaining calls (since 1.20)
1195 public function setWrapperLegend( $legend ) {
1196 $this->mWrapperLegend
= $legend;
1202 * Prompt the whole form to be wrapped in a "<fieldset>", with
1203 * this message as its "<legend>" element.
1206 * @param string|Message $msg Message key or Message object
1208 * @return HTMLForm $this for chaining calls (since 1.20)
1210 public function setWrapperLegendMsg( $msg ) {
1211 if ( !$msg instanceof Message
) {
1212 $msg = $this->msg( $msg );
1214 $this->setWrapperLegend( $msg->text() );
1220 * Set the prefix for various default messages
1221 * @todo Currently only used for the "<fieldset>" legend on forms
1222 * with multiple sections; should be used elsewhere?
1226 * @return HTMLForm $this for chaining calls (since 1.20)
1228 function setMessagePrefix( $p ) {
1229 $this->mMessagePrefix
= $p;
1235 * Set the title for form submission
1237 * @param Title $t Title of page the form is on/should be posted to
1239 * @return HTMLForm $this for chaining calls (since 1.20)
1241 function setTitle( $t ) {
1251 function getTitle() {
1252 return $this->mTitle
=== false
1253 ?
$this->getContext()->getTitle()
1258 * Set the method used to submit the form
1260 * @param string $method
1262 * @return HTMLForm $this for chaining calls (since 1.20)
1264 public function setMethod( $method = 'post' ) {
1265 $this->mMethod
= $method;
1270 public function getMethod() {
1271 return $this->mMethod
;
1277 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1279 * @param string $sectionName ID attribute of the "<table>" tag for this
1280 * section, ignored if empty.
1281 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1282 * each subsection, ignored if empty.
1283 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1287 public function displaySection( $fields,
1289 $fieldsetIDPrefix = '',
1290 &$hasUserVisibleFields = false ) {
1291 $displayFormat = $this->getDisplayFormat();
1294 $subsectionHtml = '';
1297 // Conveniently, PHP method names are case-insensitive.
1298 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1300 foreach ( $fields as $key => $value ) {
1301 if ( $value instanceof HTMLFormField
) {
1302 $v = empty( $value->mParams
['nodata'] )
1303 ?
$this->mFieldData
[$key]
1304 : $value->getDefault();
1305 $html .= $value->$getFieldHtmlMethod( $v );
1307 $labelValue = trim( $value->getLabel() );
1308 if ( $labelValue != ' ' && $labelValue !== '' ) {
1312 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1313 get_class( $value ) !== 'HTMLApiField'
1315 $hasUserVisibleFields = true;
1317 } elseif ( is_array( $value ) ) {
1318 $subsectionHasVisibleFields = false;
1320 $this->displaySection( $value,
1322 "$fieldsetIDPrefix$key-",
1323 $subsectionHasVisibleFields );
1326 if ( $subsectionHasVisibleFields === true ) {
1327 // Display the section with various niceties.
1328 $hasUserVisibleFields = true;
1330 $legend = $this->getLegend( $key );
1332 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1333 $section = $this->mSectionHeaders
[$key] . $section;
1335 if ( isset( $this->mSectionFooters
[$key] ) ) {
1336 $section .= $this->mSectionFooters
[$key];
1339 $attributes = array();
1340 if ( $fieldsetIDPrefix ) {
1341 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1343 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1345 // Just return the inputs, nothing fancy.
1346 $subsectionHtml .= $section;
1351 if ( $displayFormat !== 'raw' ) {
1354 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1355 $classes[] = 'mw-htmlform-nolabel';
1359 'class' => implode( ' ', $classes ),
1362 if ( $sectionName ) {
1363 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1366 if ( $displayFormat === 'table' ) {
1367 $html = Html
::rawElement( 'table',
1369 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1370 } elseif ( $displayFormat === 'inline' ) {
1371 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1373 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1377 if ( $this->mSubSectionBeforeFields
) {
1378 return $subsectionHtml . "\n" . $html;
1380 return $html . "\n" . $subsectionHtml;
1385 * Construct the form fields from the Descriptor array
1387 function loadData() {
1388 $fieldData = array();
1390 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1391 if ( !empty( $field->mParams
['nodata'] ) ) {
1393 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1394 $fieldData[$fieldname] = $field->getDefault();
1396 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1401 foreach ( $fieldData as $name => &$value ) {
1402 $field = $this->mFlatFields
[$name];
1403 $value = $field->filter( $value, $this->mFlatFields
);
1406 $this->mFieldData
= $fieldData;
1410 * Stop a reset button being shown for this form
1412 * @param bool $suppressReset Set to false to re-enable the button again
1414 * @return HTMLForm $this for chaining calls (since 1.20)
1416 function suppressReset( $suppressReset = true ) {
1417 $this->mShowReset
= !$suppressReset;
1423 * Overload this if you want to apply special filtration routines
1424 * to the form as a whole, after it's submitted but before it's
1427 * @param array $data
1431 function filterDataForSubmit( $data ) {
1436 * Get a string to go in the "<legend>" of a section fieldset.
1437 * Override this if you want something more complicated.
1439 * @param string $key
1443 public function getLegend( $key ) {
1444 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1448 * Set the value for the action attribute of the form.
1449 * When set to false (which is the default state), the set title is used.
1453 * @param string|bool $action
1455 * @return HTMLForm $this for chaining calls (since 1.20)
1457 public function setAction( $action ) {
1458 $this->mAction
= $action;
1464 * Get the value for the action attribute of the form.
1470 public function getAction() {
1471 // If an action is alredy provided, return it
1472 if ( $this->mAction
!== false ) {
1473 return $this->mAction
;
1476 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1477 // Check whether we are in GET mode and the ArticlePath contains a "?"
1478 // meaning that getLocalURL() would return something like "index.php?title=...".
1479 // As browser remove the query string before submitting GET forms,
1480 // it means that the title would be lost. In such case use wfScript() instead
1481 // and put title in an hidden field (see getHiddenFields()).
1482 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1486 return $this->getTitle()->getLocalURL();