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',
157 'user' => 'HTMLUserTextField',
162 protected $mMessagePrefix;
164 /** @var HTMLFormField[] */
165 protected $mFlatFields;
167 protected $mFieldTree;
168 protected $mShowReset = false;
169 protected $mShowSubmit = true;
170 protected $mSubmitFlags = array( 'constructive', 'primary' );
172 protected $mSubmitCallback;
173 protected $mValidationErrorMessage;
175 protected $mPre = '';
176 protected $mHeader = '';
177 protected $mFooter = '';
178 protected $mSectionHeaders = array();
179 protected $mSectionFooters = array();
180 protected $mPost = '';
182 protected $mTableId = '';
184 protected $mSubmitID;
185 protected $mSubmitName;
186 protected $mSubmitText;
187 protected $mSubmitTooltip;
190 protected $mMethod = 'post';
191 protected $mWasSubmitted = false;
194 * Form action URL. false means we will use the URL to set Title
198 protected $mAction = false;
200 protected $mUseMultipart = false;
201 protected $mHiddenFields = array();
202 protected $mButtons = array();
204 protected $mWrapperLegend = false;
207 * Salt for the edit token.
210 protected $mTokenSalt = '';
213 * If true, sections that contain both fields and subsections will
214 * render their subsections before their fields.
216 * Subclasses may set this to false to render subsections after fields
219 protected $mSubSectionBeforeFields = true;
222 * Format in which to display form. For viable options,
223 * @see $availableDisplayFormats
226 protected $displayFormat = 'table';
229 * Available formats in which to display the form
232 protected $availableDisplayFormats = array(
240 * Available formats in which to display the form
243 protected $availableSubclassDisplayFormats = array(
249 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
251 * @param string $displayFormat
252 * @param mixed $arguments... Additional arguments to pass to the constructor.
255 public static function factory( $displayFormat/*, $arguments...*/ ) {
256 $arguments = func_get_args();
257 array_shift( $arguments );
259 switch ( $displayFormat ) {
261 $reflector = new ReflectionClass( 'VFormHTMLForm' );
262 return $reflector->newInstanceArgs( $arguments );
264 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
265 return $reflector->newInstanceArgs( $arguments );
267 $reflector = new ReflectionClass( 'HTMLForm' );
268 $form = $reflector->newInstanceArgs( $arguments );
269 $form->setDisplayFormat( $displayFormat );
275 * Build a new HTMLForm from an array of field attributes
277 * @param array $descriptor Array of Field constructs, as described above
278 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
279 * Obviates the need to call $form->setTitle()
280 * @param string $messagePrefix A prefix to go in front of default messages
282 public function __construct( $descriptor, /*IContextSource*/ $context = null,
285 if ( $context instanceof IContextSource
) {
286 $this->setContext( $context );
287 $this->mTitle
= false; // We don't need them to set a title
288 $this->mMessagePrefix
= $messagePrefix;
289 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
290 $this->mMessagePrefix
= $messagePrefix;
291 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
293 // it's actually $messagePrefix
294 $this->mMessagePrefix
= $context;
297 // Evil hack for mobile :(
299 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
300 && $this->displayFormat
=== 'table'
302 $this->displayFormat
= 'div';
305 // Expand out into a tree.
306 $loadedDescriptor = array();
307 $this->mFlatFields
= array();
309 foreach ( $descriptor as $fieldname => $info ) {
310 $section = isset( $info['section'] )
314 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
315 $this->mUseMultipart
= true;
318 $field = static::loadInputFromParameters( $fieldname, $info, $this );
320 $setSection =& $loadedDescriptor;
322 $sectionParts = explode( '/', $section );
324 while ( count( $sectionParts ) ) {
325 $newName = array_shift( $sectionParts );
327 if ( !isset( $setSection[$newName] ) ) {
328 $setSection[$newName] = array();
331 $setSection =& $setSection[$newName];
335 $setSection[$fieldname] = $field;
336 $this->mFlatFields
[$fieldname] = $field;
339 $this->mFieldTree
= $loadedDescriptor;
343 * Set format in which to display the form
345 * @param string $format The name of the format to use, must be one of
346 * $this->availableDisplayFormats
348 * @throws MWException
350 * @return HTMLForm $this for chaining calls (since 1.20)
352 public function setDisplayFormat( $format ) {
354 in_array( $format, $this->availableSubclassDisplayFormats
) ||
355 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
)
357 throw new MWException( 'Cannot change display format after creation, ' .
358 'use HTMLForm::factory() instead' );
361 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
362 throw new MWException( 'Display format must be one of ' .
363 print_r( $this->availableDisplayFormats
, true ) );
366 // Evil hack for mobile :(
367 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
371 $this->displayFormat
= $format;
377 * Getter for displayFormat
381 public function getDisplayFormat() {
382 return $this->displayFormat
;
386 * Test if displayFormat is 'vform'
388 * @deprecated since 1.25
391 public function isVForm() {
392 wfDeprecated( __METHOD__
, '1.25' );
397 * Get the HTMLFormField subclass for this descriptor.
399 * The descriptor can be passed either 'class' which is the name of
400 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
401 * This makes sure the 'class' is always set, and also is returned by
402 * this function for ease.
406 * @param string $fieldname Name of the field
407 * @param array $descriptor Input Descriptor, as described above
409 * @throws MWException
410 * @return string Name of a HTMLFormField subclass
412 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
413 if ( isset( $descriptor['class'] ) ) {
414 $class = $descriptor['class'];
415 } elseif ( isset( $descriptor['type'] ) ) {
416 $class = static::$typeMappings[$descriptor['type']];
417 $descriptor['class'] = $class;
423 throw new MWException( "Descriptor with no class for $fieldname: "
424 . print_r( $descriptor, true ) );
431 * Initialise a new Object for the field
433 * @param string $fieldname Name of the field
434 * @param array $descriptor Input Descriptor, as described above
435 * @param HTMLForm|null $parent Parent instance of HTMLForm
437 * @throws MWException
438 * @return HTMLFormField Instance of a subclass of HTMLFormField
440 public static function loadInputFromParameters( $fieldname, $descriptor,
441 HTMLForm
$parent = null
443 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
445 $descriptor['fieldname'] = $fieldname;
447 $descriptor['parent'] = $parent;
450 # @todo This will throw a fatal error whenever someone try to use
451 # 'class' to feed a CSS class instead of 'cssclass'. Would be
452 # great to avoid the fatal error and show a nice error.
453 $obj = new $class( $descriptor );
459 * Prepare form for submission.
461 * @attention When doing method chaining, that should be the very last
462 * method call before displayForm().
464 * @throws MWException
465 * @return HTMLForm $this for chaining calls (since 1.20)
467 function prepareForm() {
468 # Check if we have the info we need
469 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
470 throw new MWException( "You must call setTitle() on an HTMLForm" );
473 # Load data from the request.
480 * Try submitting, with edit token check first
481 * @return Status|bool
483 function tryAuthorizedSubmit() {
487 if ( $this->getMethod() != 'post' ) {
488 $submit = true; // no session check needed
489 } elseif ( $this->getRequest()->wasPosted() ) {
490 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
491 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
492 // Session tokens for logged-out users have no security value.
493 // However, if the user gave one, check it in order to give a nice
494 // "session expired" error instead of "permission denied" or such.
495 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
502 $this->mWasSubmitted
= true;
503 $result = $this->trySubmit();
510 * The here's-one-I-made-earlier option: do the submission if
511 * posted, or display the form with or without funky validation
513 * @return bool|Status Whether submission was successful.
516 $this->prepareForm();
518 $result = $this->tryAuthorizedSubmit();
519 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
523 $this->displayForm( $result );
529 * Validate all the fields, and call the submission callback
530 * function if everything is kosher.
531 * @throws MWException
532 * @return bool|string|array|Status
533 * - Bool true or a good Status object indicates success,
534 * - Bool false indicates no submission was attempted,
535 * - Anything else indicates failure. The value may be a fatal Status
536 * object, an HTML string, or an array of arrays (message keys and
537 * params) or strings (message keys)
539 function trySubmit() {
540 $this->mWasSubmitted
= true;
542 # Check for cancelled submission
543 foreach ( $this->mFlatFields
as $fieldname => $field ) {
544 if ( !empty( $field->mParams
['nodata'] ) ) {
547 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
548 $this->mWasSubmitted
= false;
553 # Check for validation
554 foreach ( $this->mFlatFields
as $fieldname => $field ) {
555 if ( !empty( $field->mParams
['nodata'] ) ) {
558 if ( $field->isHidden( $this->mFieldData
) ) {
561 if ( $field->validate(
562 $this->mFieldData
[$fieldname],
566 return isset( $this->mValidationErrorMessage
)
567 ?
$this->mValidationErrorMessage
568 : array( 'htmlform-invalid-input' );
572 $callback = $this->mSubmitCallback
;
573 if ( !is_callable( $callback ) ) {
574 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
575 'setSubmitCallback() to set one.' );
578 $data = $this->filterDataForSubmit( $this->mFieldData
);
580 $res = call_user_func( $callback, $data, $this );
581 if ( $res === false ) {
582 $this->mWasSubmitted
= false;
589 * Test whether the form was considered to have been submitted or not, i.e.
590 * whether the last call to tryAuthorizedSubmit or trySubmit returned
593 * This will return false until HTMLForm::tryAuthorizedSubmit or
594 * HTMLForm::trySubmit is called.
599 function wasSubmitted() {
600 return $this->mWasSubmitted
;
604 * Set a callback to a function to do something with the form
605 * once it's been successfully validated.
607 * @param callable $cb The function will be passed the output from
608 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
609 * return as documented for HTMLForm::trySubmit
611 * @return HTMLForm $this for chaining calls (since 1.20)
613 function setSubmitCallback( $cb ) {
614 $this->mSubmitCallback
= $cb;
620 * Set a message to display on a validation error.
622 * @param string|array $msg String or Array of valid inputs to wfMessage()
623 * (so each entry can be either a String or Array)
625 * @return HTMLForm $this for chaining calls (since 1.20)
627 function setValidationErrorMessage( $msg ) {
628 $this->mValidationErrorMessage
= $msg;
634 * Set the introductory message, overwriting any existing message.
636 * @param string $msg Complete text of message to display
638 * @return HTMLForm $this for chaining calls (since 1.20)
640 function setIntro( $msg ) {
641 $this->setPreText( $msg );
647 * Set the introductory message, overwriting any existing message.
650 * @param string $msg Complete text of message to display
652 * @return HTMLForm $this for chaining calls (since 1.20)
654 function setPreText( $msg ) {
661 * Add introductory text.
663 * @param string $msg Complete text of message to display
665 * @return HTMLForm $this for chaining calls (since 1.20)
667 function addPreText( $msg ) {
674 * Add header text, inside the form.
676 * @param string $msg Complete text of message to display
677 * @param string|null $section The section to add the header to
679 * @return HTMLForm $this for chaining calls (since 1.20)
681 function addHeaderText( $msg, $section = null ) {
682 if ( is_null( $section ) ) {
683 $this->mHeader
.= $msg;
685 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
686 $this->mSectionHeaders
[$section] = '';
688 $this->mSectionHeaders
[$section] .= $msg;
695 * Set header text, inside the form.
698 * @param string $msg Complete text of message to display
699 * @param string|null $section The section to add the header to
701 * @return HTMLForm $this for chaining calls (since 1.20)
703 function setHeaderText( $msg, $section = null ) {
704 if ( is_null( $section ) ) {
705 $this->mHeader
= $msg;
707 $this->mSectionHeaders
[$section] = $msg;
714 * Add footer text, inside the form.
716 * @param string $msg Complete text of message to display
717 * @param string|null $section The section to add the footer text to
719 * @return HTMLForm $this for chaining calls (since 1.20)
721 function addFooterText( $msg, $section = null ) {
722 if ( is_null( $section ) ) {
723 $this->mFooter
.= $msg;
725 if ( !isset( $this->mSectionFooters
[$section] ) ) {
726 $this->mSectionFooters
[$section] = '';
728 $this->mSectionFooters
[$section] .= $msg;
735 * Set footer text, inside the form.
738 * @param string $msg Complete text of message to display
739 * @param string|null $section The section to add the footer text to
741 * @return HTMLForm $this for chaining calls (since 1.20)
743 function setFooterText( $msg, $section = null ) {
744 if ( is_null( $section ) ) {
745 $this->mFooter
= $msg;
747 $this->mSectionFooters
[$section] = $msg;
754 * Add text to the end of the display.
756 * @param string $msg Complete text of message to display
758 * @return HTMLForm $this for chaining calls (since 1.20)
760 function addPostText( $msg ) {
761 $this->mPost
.= $msg;
767 * Set text at the end of the display.
769 * @param string $msg Complete text of message to display
771 * @return HTMLForm $this for chaining calls (since 1.20)
773 function setPostText( $msg ) {
780 * Add a hidden field to the output
782 * @param string $name Field name. This will be used exactly as entered
783 * @param string $value Field value
784 * @param array $attribs
786 * @return HTMLForm $this for chaining calls (since 1.20)
788 public function addHiddenField( $name, $value, $attribs = array() ) {
789 $attribs +
= array( 'name' => $name );
790 $this->mHiddenFields
[] = array( $value, $attribs );
796 * Add an array of hidden fields to the output
800 * @param array $fields Associative array of fields to add;
801 * mapping names to their values
803 * @return HTMLForm $this for chaining calls
805 public function addHiddenFields( array $fields ) {
806 foreach ( $fields as $name => $value ) {
807 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
814 * Add a button to the form
816 * @param string $name Field name.
817 * @param string $value Field value
818 * @param string $id DOM id for the button (default: null)
819 * @param array $attribs
821 * @return HTMLForm $this for chaining calls (since 1.20)
823 public function addButton( $name, $value, $id = null, $attribs = null ) {
824 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
830 * Set the salt for the edit token.
832 * Only useful when the method is "post".
835 * @param string|array $salt Salt to use
836 * @return HTMLForm $this For chaining calls
838 public function setTokenSalt( $salt ) {
839 $this->mTokenSalt
= $salt;
845 * Display the form (sending to the context's OutputPage object), with an
846 * appropriate error message or stack of messages, and any validation errors, etc.
848 * @attention You should call prepareForm() before calling this function.
849 * Moreover, when doing method chaining this should be the very last method
850 * call just after prepareForm().
852 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
854 * @return void Nothing, should be last call
856 function displayForm( $submitResult ) {
857 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
861 * Returns the raw HTML generated by the form
863 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
867 function getHTML( $submitResult ) {
868 # For good measure (it is the default)
869 $this->getOutput()->preventClickjacking();
870 $this->getOutput()->addModules( 'mediawiki.htmlform' );
873 . $this->getErrors( $submitResult )
874 // In OOUI forms, we handle mHeader elsewhere. FIXME This is horrible.
875 . ( $this->getDisplayFormat() === 'ooui' ?
'' : $this->mHeader
)
877 . $this->getHiddenFields()
878 . $this->getButtons()
881 $html = $this->wrapForm( $html );
883 return '' . $this->mPre
. $html . $this->mPost
;
887 * Get HTML attributes for the `<form>` tag.
890 protected function getFormAttributes() {
891 # Use multipart/form-data
892 $encType = $this->mUseMultipart
893 ?
'multipart/form-data'
894 : 'application/x-www-form-urlencoded';
897 'action' => $this->getAction(),
898 'method' => $this->getMethod(),
899 'enctype' => $encType,
901 if ( !empty( $this->mId
) ) {
902 $attribs['id'] = $this->mId
;
908 * Wrap the form innards in an actual "<form>" element
910 * @param string $html HTML contents to wrap.
912 * @return string Wrapped HTML.
914 function wrapForm( $html ) {
915 # Include a <fieldset> wrapper for style, if requested.
916 if ( $this->mWrapperLegend
!== false ) {
917 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
918 $html = Xml
::fieldset( $legend, $html );
921 return Html
::rawElement( 'form', $this->getFormAttributes() +
array( 'class' => 'visualClear' ), $html );
925 * Get the hidden fields that should go inside the form.
926 * @return string HTML.
928 function getHiddenFields() {
930 if ( $this->getMethod() == 'post' ) {
931 $html .= Html
::hidden(
933 $this->getUser()->getEditToken( $this->mTokenSalt
),
934 array( 'id' => 'wpEditToken' )
936 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
939 $articlePath = $this->getConfig()->get( 'ArticlePath' );
940 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
941 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
944 foreach ( $this->mHiddenFields
as $data ) {
945 list( $value, $attribs ) = $data;
946 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
953 * Get the submit and (potentially) reset buttons.
954 * @return string HTML.
956 function getButtons() {
958 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
960 if ( $this->mShowSubmit
) {
963 if ( isset( $this->mSubmitID
) ) {
964 $attribs['id'] = $this->mSubmitID
;
967 if ( isset( $this->mSubmitName
) ) {
968 $attribs['name'] = $this->mSubmitName
;
971 if ( isset( $this->mSubmitTooltip
) ) {
972 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
975 $attribs['class'] = array( 'mw-htmlform-submit' );
977 if ( $useMediaWikiUIEverywhere ) {
978 foreach ( $this->mSubmitFlags
as $flag ) {
979 array_push( $attribs['class'], 'mw-ui-' . $flag );
981 array_push( $attribs['class'], 'mw-ui-button' );
984 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
987 if ( $this->mShowReset
) {
988 $buttons .= Html
::element(
992 'value' => $this->msg( 'htmlform-reset' )->text(),
993 'class' => ( $useMediaWikiUIEverywhere ?
'mw-ui-button' : null ),
998 foreach ( $this->mButtons
as $button ) {
1001 'name' => $button['name'],
1002 'value' => $button['value']
1005 if ( $button['attribs'] ) {
1006 $attrs +
= $button['attribs'];
1009 if ( isset( $button['id'] ) ) {
1010 $attrs['id'] = $button['id'];
1013 if ( $useMediaWikiUIEverywhere ) {
1014 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : array();
1015 $attrs['class'][] = 'mw-ui-button';
1018 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1021 $html = Html
::rawElement( 'span',
1022 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1028 * Get the whole body of the form.
1031 function getBody() {
1032 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1036 * Format and display an error message stack.
1038 * @param string|array|Status $errors
1042 function getErrors( $errors ) {
1043 if ( $errors instanceof Status
) {
1044 if ( $errors->isOK() ) {
1047 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1049 } elseif ( is_array( $errors ) ) {
1050 $errorstr = $this->formatErrors( $errors );
1052 $errorstr = $errors;
1056 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1061 * Format a stack of error messages into a single HTML string
1063 * @param array $errors Array of message keys/values
1065 * @return string HTML, a "<ul>" list of errors
1067 public function formatErrors( $errors ) {
1070 foreach ( $errors as $error ) {
1071 if ( is_array( $error ) ) {
1072 $msg = array_shift( $error );
1078 $errorstr .= Html
::rawElement(
1081 $this->msg( $msg, $error )->parse()
1085 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
1091 * Set the text for the submit button
1093 * @param string $t Plaintext
1095 * @return HTMLForm $this for chaining calls (since 1.20)
1097 function setSubmitText( $t ) {
1098 $this->mSubmitText
= $t;
1104 * Identify that the submit button in the form has a destructive action
1107 public function setSubmitDestructive() {
1108 $this->mSubmitFlags
= array( 'destructive', 'primary' );
1112 * Identify that the submit button in the form has a progressive action
1115 public function setSubmitProgressive() {
1116 $this->mSubmitFlags
= array( 'progressive', 'primary' );
1120 * Set the text for the submit button to a message
1123 * @param string|Message $msg Message key or Message object
1125 * @return HTMLForm $this for chaining calls (since 1.20)
1127 public function setSubmitTextMsg( $msg ) {
1128 if ( !$msg instanceof Message
) {
1129 $msg = $this->msg( $msg );
1131 $this->setSubmitText( $msg->text() );
1137 * Get the text for the submit button, either customised or a default.
1140 function getSubmitText() {
1141 return $this->mSubmitText
1142 ?
$this->mSubmitText
1143 : $this->msg( 'htmlform-submit' )->text();
1147 * @param string $name Submit button name
1149 * @return HTMLForm $this for chaining calls (since 1.20)
1151 public function setSubmitName( $name ) {
1152 $this->mSubmitName
= $name;
1158 * @param string $name Tooltip for the submit button
1160 * @return HTMLForm $this for chaining calls (since 1.20)
1162 public function setSubmitTooltip( $name ) {
1163 $this->mSubmitTooltip
= $name;
1169 * Set the id for the submit button.
1173 * @todo FIXME: Integrity of $t is *not* validated
1174 * @return HTMLForm $this for chaining calls (since 1.20)
1176 function setSubmitID( $t ) {
1177 $this->mSubmitID
= $t;
1183 * Stop a default submit button being shown for this form. This implies that an
1184 * alternate submit method must be provided manually.
1188 * @param bool $suppressSubmit Set to false to re-enable the button again
1190 * @return HTMLForm $this for chaining calls
1192 function suppressDefaultSubmit( $suppressSubmit = true ) {
1193 $this->mShowSubmit
= !$suppressSubmit;
1199 * Set the id of the \<table\> or outermost \<div\> element.
1203 * @param string $id New value of the id attribute, or "" to remove
1205 * @return HTMLForm $this for chaining calls
1207 public function setTableId( $id ) {
1208 $this->mTableId
= $id;
1214 * @param string $id DOM id for the form
1216 * @return HTMLForm $this for chaining calls (since 1.20)
1218 public function setId( $id ) {
1225 * Prompt the whole form to be wrapped in a "<fieldset>", with
1226 * this text as its "<legend>" element.
1228 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1229 * If true, a wrapper will be displayed, but no legend.
1230 * If a string, a wrapper will be displayed with that string as a legend.
1231 * The string will be escaped before being output (this doesn't support HTML).
1233 * @return HTMLForm $this for chaining calls (since 1.20)
1235 public function setWrapperLegend( $legend ) {
1236 $this->mWrapperLegend
= $legend;
1242 * Prompt the whole form to be wrapped in a "<fieldset>", with
1243 * this message as its "<legend>" element.
1246 * @param string|Message $msg Message key or Message object
1248 * @return HTMLForm $this for chaining calls (since 1.20)
1250 public function setWrapperLegendMsg( $msg ) {
1251 if ( !$msg instanceof Message
) {
1252 $msg = $this->msg( $msg );
1254 $this->setWrapperLegend( $msg->text() );
1260 * Set the prefix for various default messages
1261 * @todo Currently only used for the "<fieldset>" legend on forms
1262 * with multiple sections; should be used elsewhere?
1266 * @return HTMLForm $this for chaining calls (since 1.20)
1268 function setMessagePrefix( $p ) {
1269 $this->mMessagePrefix
= $p;
1275 * Set the title for form submission
1277 * @param Title $t Title of page the form is on/should be posted to
1279 * @return HTMLForm $this for chaining calls (since 1.20)
1281 function setTitle( $t ) {
1291 function getTitle() {
1292 return $this->mTitle
=== false
1293 ?
$this->getContext()->getTitle()
1298 * Set the method used to submit the form
1300 * @param string $method
1302 * @return HTMLForm $this for chaining calls (since 1.20)
1304 public function setMethod( $method = 'post' ) {
1305 $this->mMethod
= strtolower( $method );
1311 * @return string Always lowercase
1313 public function getMethod() {
1314 return $this->mMethod
;
1320 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1322 * @param string $sectionName ID attribute of the "<table>" tag for this
1323 * section, ignored if empty.
1324 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1325 * each subsection, ignored if empty.
1326 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1330 public function displaySection( $fields,
1332 $fieldsetIDPrefix = '',
1333 &$hasUserVisibleFields = false ) {
1334 $displayFormat = $this->getDisplayFormat();
1337 $subsectionHtml = '';
1340 // Conveniently, PHP method names are case-insensitive.
1341 $getFieldHtmlMethod = $displayFormat == 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1343 foreach ( $fields as $key => $value ) {
1344 if ( $value instanceof HTMLFormField
) {
1345 $v = empty( $value->mParams
['nodata'] )
1346 ?
$this->mFieldData
[$key]
1347 : $value->getDefault();
1348 $html .= $value->$getFieldHtmlMethod( $v );
1350 $labelValue = trim( $value->getLabel() );
1351 if ( $labelValue != ' ' && $labelValue !== '' ) {
1355 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1356 get_class( $value ) !== 'HTMLApiField'
1358 $hasUserVisibleFields = true;
1360 } elseif ( is_array( $value ) ) {
1361 $subsectionHasVisibleFields = false;
1363 $this->displaySection( $value,
1365 "$fieldsetIDPrefix$key-",
1366 $subsectionHasVisibleFields );
1369 if ( $subsectionHasVisibleFields === true ) {
1370 // Display the section with various niceties.
1371 $hasUserVisibleFields = true;
1373 $legend = $this->getLegend( $key );
1375 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1376 $section = $this->mSectionHeaders
[$key] . $section;
1378 if ( isset( $this->mSectionFooters
[$key] ) ) {
1379 $section .= $this->mSectionFooters
[$key];
1382 $attributes = array();
1383 if ( $fieldsetIDPrefix ) {
1384 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1386 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1388 // Just return the inputs, nothing fancy.
1389 $subsectionHtml .= $section;
1394 if ( $displayFormat !== 'raw' ) {
1397 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1398 $classes[] = 'mw-htmlform-nolabel';
1402 'class' => implode( ' ', $classes ),
1405 if ( $sectionName ) {
1406 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1409 if ( $displayFormat === 'table' ) {
1410 $html = Html
::rawElement( 'table',
1412 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1413 } elseif ( $displayFormat === 'inline' ) {
1414 $html = Html
::rawElement( 'span', $attribs, "\n$html\n" );
1415 } elseif ( $displayFormat === 'ooui' ) {
1417 'classes' => $classes,
1419 if ( $sectionName ) {
1420 $config['id'] = Sanitizer
::escapeId( $sectionName );
1422 if ( is_string( $this->mWrapperLegend
) ) {
1423 $config['label'] = $this->mWrapperLegend
;
1425 $fieldset = new OOUI\
FieldsetLayout( $config );
1426 // Ewww. We should pass this as $config['items'], but there might be string snippets.
1427 $fieldset->group
->appendContent( new OOUI\
HtmlSnippet( $html ) );
1430 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1434 if ( $subsectionHtml ) {
1435 if ( $this->mSubSectionBeforeFields
) {
1436 return $subsectionHtml . "\n" . $html;
1438 return $html . "\n" . $subsectionHtml;
1446 * Construct the form fields from the Descriptor array
1448 function loadData() {
1449 $fieldData = array();
1451 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1452 if ( !empty( $field->mParams
['nodata'] ) ) {
1454 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1455 $fieldData[$fieldname] = $field->getDefault();
1457 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1462 foreach ( $fieldData as $name => &$value ) {
1463 $field = $this->mFlatFields
[$name];
1464 $value = $field->filter( $value, $this->mFlatFields
);
1467 $this->mFieldData
= $fieldData;
1471 * Stop a reset button being shown for this form
1473 * @param bool $suppressReset Set to false to re-enable the button again
1475 * @return HTMLForm $this for chaining calls (since 1.20)
1477 function suppressReset( $suppressReset = true ) {
1478 $this->mShowReset
= !$suppressReset;
1484 * Overload this if you want to apply special filtration routines
1485 * to the form as a whole, after it's submitted but before it's
1488 * @param array $data
1492 function filterDataForSubmit( $data ) {
1497 * Get a string to go in the "<legend>" of a section fieldset.
1498 * Override this if you want something more complicated.
1500 * @param string $key
1504 public function getLegend( $key ) {
1505 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1509 * Set the value for the action attribute of the form.
1510 * When set to false (which is the default state), the set title is used.
1514 * @param string|bool $action
1516 * @return HTMLForm $this for chaining calls (since 1.20)
1518 public function setAction( $action ) {
1519 $this->mAction
= $action;
1525 * Get the value for the action attribute of the form.
1531 public function getAction() {
1532 // If an action is alredy provided, return it
1533 if ( $this->mAction
!== false ) {
1534 return $this->mAction
;
1537 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1538 // Check whether we are in GET mode and the ArticlePath contains a "?"
1539 // meaning that getLocalURL() would return something like "index.php?title=...".
1540 // As browser remove the query string before submitting GET forms,
1541 // it means that the title would be lost. In such case use wfScript() instead
1542 // and put title in an hidden field (see getHiddenFields()).
1543 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1547 return $this->getTitle()->getLocalURL();