3 * HTML form generation and submission handling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
27 * In order to generate the form, the HTMLForm object takes an array
28 * structure detailing the form fields available. Each element of the
29 * array is a basic property-list, including the type of field, the
30 * label it is to be given in the form, callbacks for validation and
31 * 'filtering', and other pertinent information.
33 * Field types are implemented as subclasses of the generic HTMLFormField
34 * object, and typically implement at least getInputHTML, which generates
35 * the HTML for the input field to be placed in the table.
37 * You can find extensive documentation on the www.mediawiki.org wiki:
38 * - http://www.mediawiki.org/wiki/HTMLForm
39 * - http://www.mediawiki.org/wiki/HTMLForm/tutorial
41 * The constructor input is an associative array of $fieldname => $info,
42 * where $info is an Associative Array with any of the following:
44 * 'class' -- the subclass of HTMLFormField that will be used
45 * to create the object. *NOT* the CSS class!
46 * 'type' -- roughly translates into the <select> type attribute.
47 * if 'class' is not specified, this is used as a map
48 * through HTMLForm::$typeMappings to get the class name.
49 * 'default' -- default value when the form is displayed
50 * 'id' -- HTML id attribute
51 * 'cssclass' -- CSS class
52 * 'options' -- varies according to the specific object.
53 * 'label-message' -- message key for a message to use as the label.
54 * can be an array of msg key and then parameters to
56 * 'label' -- alternatively, a raw text message. Overridden by
58 * 'help' -- message text for a message to use as a help text.
59 * 'help-message' -- message key for a message to use as a help text.
60 * can be an array of msg key and then parameters to
62 * Overwrites 'help-messages' and 'help'.
63 * 'help-messages' -- array of message key. As above, each item can
64 * be an array of msg key and then parameters.
66 * 'required' -- passed through to the object, indicating that it
67 * is a required field.
68 * 'size' -- the length of text fields
69 * 'filter-callback -- a function name to give you the chance to
70 * massage the inputted value before it's processed.
71 * @see HTMLForm::filter()
72 * 'validation-callback' -- a function name to give you the chance
73 * to impose extra validation on the field input.
74 * @see HTMLForm::validate()
75 * 'name' -- By default, the 'name' attribute of the input field
76 * is "wp{$fieldname}". If you want a different name
77 * (eg one without the "wp" prefix), specify it here and
78 * it will be used without modification.
80 * Since 1.20, you can chain mutators to ease the form generation:
83 * $form = new HTMLForm( $someFields );
84 * $form->setMethod( 'get' )
85 * ->setWrapperLegendMsg( 'message-key' )
87 * ->displayForm( '' );
89 * Note that you will have prepareForm and displayForm at the end. Other
90 * methods call done after that would simply not be part of the form :(
92 * TODO: Document 'section' / 'subsection' stuff
94 class HTMLForm
extends ContextSource
{
96 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
97 public static $typeMappings = array(
98 'api' => 'HTMLApiField',
99 'text' => 'HTMLTextField',
100 'textarea' => 'HTMLTextAreaField',
101 'select' => 'HTMLSelectField',
102 'radio' => 'HTMLRadioField',
103 'multiselect' => 'HTMLMultiSelectField',
104 'check' => 'HTMLCheckField',
105 'toggle' => 'HTMLCheckField',
106 'int' => 'HTMLIntField',
107 'float' => 'HTMLFloatField',
108 'info' => 'HTMLInfoField',
109 'selectorother' => 'HTMLSelectOrOtherField',
110 'selectandother' => 'HTMLSelectAndOtherField',
111 'submit' => 'HTMLSubmitField',
112 'hidden' => 'HTMLHiddenField',
113 'edittools' => 'HTMLEditTools',
114 'checkmatrix' => 'HTMLCheckMatrix',
116 // HTMLTextField will output the correct type="" attribute automagically.
117 // There are about four zillion other HTML5 input types, like url, but
118 // we don't use those at the moment, so no point in adding all of them.
119 'email' => 'HTMLTextField',
120 'password' => 'HTMLTextField',
123 protected $mMessagePrefix;
125 /** @var HTMLFormField[] */
126 protected $mFlatFields;
128 protected $mFieldTree;
129 protected $mShowReset = false;
130 protected $mShowSubmit = true;
133 protected $mSubmitCallback;
134 protected $mValidationErrorMessage;
136 protected $mPre = '';
137 protected $mHeader = '';
138 protected $mFooter = '';
139 protected $mSectionHeaders = array();
140 protected $mSectionFooters = array();
141 protected $mPost = '';
143 protected $mTableId = '';
145 protected $mSubmitID;
146 protected $mSubmitName;
147 protected $mSubmitText;
148 protected $mSubmitTooltip;
151 protected $mMethod = 'post';
154 * Form action URL. false means we will use the URL to set Title
158 protected $mAction = false;
160 protected $mUseMultipart = false;
161 protected $mHiddenFields = array();
162 protected $mButtons = array();
164 protected $mWrapperLegend = false;
167 * If true, sections that contain both fields and subsections will
168 * render their subsections before their fields.
170 * Subclasses may set this to false to render subsections after fields
173 protected $mSubSectionBeforeFields = true;
176 * Format in which to display form. For viable options,
177 * @see $availableDisplayFormats
180 protected $displayFormat = 'table';
183 * Available formats in which to display the form
186 protected $availableDisplayFormats = array(
194 * Build a new HTMLForm from an array of field attributes
195 * @param array $descriptor of Field constructs, as described above
196 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
197 * Obviates the need to call $form->setTitle()
198 * @param string $messagePrefix a prefix to go in front of default messages
200 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
201 if ( $context instanceof IContextSource
) {
202 $this->setContext( $context );
203 $this->mTitle
= false; // We don't need them to set a title
204 $this->mMessagePrefix
= $messagePrefix;
205 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
206 $this->mMessagePrefix
= $messagePrefix;
207 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
209 // it's actually $messagePrefix
210 $this->mMessagePrefix
= $context;
213 // Expand out into a tree.
214 $loadedDescriptor = array();
215 $this->mFlatFields
= array();
217 foreach ( $descriptor as $fieldname => $info ) {
218 $section = isset( $info['section'] )
222 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
223 $this->mUseMultipart
= true;
226 $field = self
::loadInputFromParameters( $fieldname, $info );
227 // FIXME During field's construct, the parent form isn't available!
228 // could add a 'parent' name-value to $info, could add a third parameter.
229 $field->mParent
= $this;
231 // vform gets too much space if empty labels generate HTML.
232 if ( $this->isVForm() ) {
233 $field->setShowEmptyLabel( false );
236 $setSection =& $loadedDescriptor;
238 $sectionParts = explode( '/', $section );
240 while ( count( $sectionParts ) ) {
241 $newName = array_shift( $sectionParts );
243 if ( !isset( $setSection[$newName] ) ) {
244 $setSection[$newName] = array();
247 $setSection =& $setSection[$newName];
251 $setSection[$fieldname] = $field;
252 $this->mFlatFields
[$fieldname] = $field;
255 $this->mFieldTree
= $loadedDescriptor;
259 * Set format in which to display the form
260 * @param string $format the name of the format to use, must be one of
261 * $this->availableDisplayFormats
262 * @throws MWException
264 * @return HTMLForm $this for chaining calls (since 1.20)
266 public function setDisplayFormat( $format ) {
267 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
268 throw new MWException( 'Display format must be one of ' . print_r( $this->availableDisplayFormats
, true ) );
270 $this->displayFormat
= $format;
275 * Getter for displayFormat
279 public function getDisplayFormat() {
280 return $this->displayFormat
;
284 * Test if displayFormat is 'vform'
288 public function isVForm() {
289 return $this->displayFormat
=== 'vform';
293 * Add the HTMLForm-specific JavaScript, if it hasn't been
295 * @deprecated since 1.18 load modules with ResourceLoader instead
297 static function addJS() {
298 wfDeprecated( __METHOD__
, '1.18' );
302 * Initialise a new Object for the field
303 * @param $fieldname string
304 * @param string $descriptor input Descriptor, as described above
305 * @throws MWException
306 * @return HTMLFormField subclass
308 static function loadInputFromParameters( $fieldname, $descriptor ) {
309 if ( isset( $descriptor['class'] ) ) {
310 $class = $descriptor['class'];
311 } elseif ( isset( $descriptor['type'] ) ) {
312 $class = self
::$typeMappings[$descriptor['type']];
313 $descriptor['class'] = $class;
319 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
322 $descriptor['fieldname'] = $fieldname;
325 # This will throw a fatal error whenever someone try to use
326 # 'class' to feed a CSS class instead of 'cssclass'. Would be
327 # great to avoid the fatal error and show a nice error.
328 $obj = new $class( $descriptor );
334 * Prepare form for submission.
336 * @attention When doing method chaining, that should be the very last
337 * method call before displayForm().
339 * @throws MWException
340 * @return HTMLForm $this for chaining calls (since 1.20)
342 function prepareForm() {
343 # Check if we have the info we need
344 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
345 throw new MWException( "You must call setTitle() on an HTMLForm" );
348 # Load data from the request.
354 * Try submitting, with edit token check first
355 * @return Status|boolean
357 function tryAuthorizedSubmit() {
361 if ( $this->getMethod() != 'post' ) {
362 $submit = true; // no session check needed
363 } elseif ( $this->getRequest()->wasPosted() ) {
364 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
365 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
366 // Session tokens for logged-out users have no security value.
367 // However, if the user gave one, check it in order to give a nice
368 // "session expired" error instead of "permission denied" or such.
369 $submit = $this->getUser()->matchEditToken( $editToken );
376 $result = $this->trySubmit();
383 * The here's-one-I-made-earlier option: do the submission if
384 * posted, or display the form with or without funky validation
386 * @return Bool or Status whether submission was successful.
389 $this->prepareForm();
391 $result = $this->tryAuthorizedSubmit();
392 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
396 $this->displayForm( $result );
401 * Validate all the fields, and call the submission callback
402 * function if everything is kosher.
403 * @throws MWException
404 * @return Mixed Bool true == Successful submission, Bool false
405 * == No submission attempted, anything else == Error to
408 function trySubmit() {
409 # Check for validation
410 foreach ( $this->mFlatFields
as $fieldname => $field ) {
411 if ( !empty( $field->mParams
['nodata'] ) ) {
414 if ( $field->validate(
415 $this->mFieldData
[$fieldname],
419 return isset( $this->mValidationErrorMessage
)
420 ?
$this->mValidationErrorMessage
421 : array( 'htmlform-invalid-input' );
425 $callback = $this->mSubmitCallback
;
426 if ( !is_callable( $callback ) ) {
427 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
430 $data = $this->filterDataForSubmit( $this->mFieldData
);
432 $res = call_user_func( $callback, $data, $this );
438 * Set a callback to a function to do something with the form
439 * once it's been successfully validated.
440 * @param string $cb function name. The function will be passed
441 * the output from HTMLForm::filterDataForSubmit, and must
442 * return Bool true on success, Bool false if no submission
443 * was attempted, or String HTML output to display on error.
444 * @return HTMLForm $this for chaining calls (since 1.20)
446 function setSubmitCallback( $cb ) {
447 $this->mSubmitCallback
= $cb;
452 * Set a message to display on a validation error.
453 * @param $msg Mixed String or Array of valid inputs to wfMessage()
454 * (so each entry can be either a String or Array)
455 * @return HTMLForm $this for chaining calls (since 1.20)
457 function setValidationErrorMessage( $msg ) {
458 $this->mValidationErrorMessage
= $msg;
463 * Set the introductory message, overwriting any existing message.
464 * @param string $msg complete text of message to display
465 * @return HTMLForm $this for chaining calls (since 1.20)
467 function setIntro( $msg ) {
468 $this->setPreText( $msg );
473 * Set the introductory message, overwriting any existing message.
475 * @param string $msg complete text of message to display
476 * @return HTMLForm $this for chaining calls (since 1.20)
478 function setPreText( $msg ) {
484 * Add introductory text.
485 * @param string $msg complete text of message to display
486 * @return HTMLForm $this for chaining calls (since 1.20)
488 function addPreText( $msg ) {
494 * Add header text, inside the form.
495 * @param string $msg complete text of message to display
496 * @param string $section The section to add the header to
497 * @return HTMLForm $this for chaining calls (since 1.20)
499 function addHeaderText( $msg, $section = null ) {
500 if ( is_null( $section ) ) {
501 $this->mHeader
.= $msg;
503 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
504 $this->mSectionHeaders
[$section] = '';
506 $this->mSectionHeaders
[$section] .= $msg;
512 * Set header text, inside the form.
514 * @param string $msg complete text of message to display
515 * @param $section The section to add the header to
516 * @return HTMLForm $this for chaining calls (since 1.20)
518 function setHeaderText( $msg, $section = null ) {
519 if ( is_null( $section ) ) {
520 $this->mHeader
= $msg;
522 $this->mSectionHeaders
[$section] = $msg;
528 * Add footer text, inside the form.
529 * @param string $msg complete text of message to display
530 * @param string $section The section to add the footer text to
531 * @return HTMLForm $this for chaining calls (since 1.20)
533 function addFooterText( $msg, $section = null ) {
534 if ( is_null( $section ) ) {
535 $this->mFooter
.= $msg;
537 if ( !isset( $this->mSectionFooters
[$section] ) ) {
538 $this->mSectionFooters
[$section] = '';
540 $this->mSectionFooters
[$section] .= $msg;
546 * Set footer text, inside the form.
548 * @param string $msg complete text of message to display
549 * @param string $section The section to add the footer text to
550 * @return HTMLForm $this for chaining calls (since 1.20)
552 function setFooterText( $msg, $section = null ) {
553 if ( is_null( $section ) ) {
554 $this->mFooter
= $msg;
556 $this->mSectionFooters
[$section] = $msg;
562 * Add text to the end of the display.
563 * @param string $msg complete text of message to display
564 * @return HTMLForm $this for chaining calls (since 1.20)
566 function addPostText( $msg ) {
567 $this->mPost
.= $msg;
572 * Set text at the end of the display.
573 * @param string $msg complete text of message to display
574 * @return HTMLForm $this for chaining calls (since 1.20)
576 function setPostText( $msg ) {
582 * Add a hidden field to the output
583 * @param string $name field name. This will be used exactly as entered
584 * @param string $value field value
585 * @param $attribs Array
586 * @return HTMLForm $this for chaining calls (since 1.20)
588 public function addHiddenField( $name, $value, $attribs = array() ) {
589 $attribs +
= array( 'name' => $name );
590 $this->mHiddenFields
[] = array( $value, $attribs );
595 * Add an array of hidden fields to the output
598 * @param array $fields Associative array of fields to add;
599 * mapping names to their values
600 * @return HTMLForm $this for chaining calls
602 public function addHiddenFields( array $fields ) {
603 foreach ( $fields as $name => $value ) {
604 $this->mHiddenFields
[] = array( $value, array( 'name' => $name ) );
610 * Add a button to the form
611 * @param string $name field name.
612 * @param string $value field value
613 * @param string $id DOM id for the button (default: null)
614 * @param $attribs Array
615 * @return HTMLForm $this for chaining calls (since 1.20)
617 public function addButton( $name, $value, $id = null, $attribs = null ) {
618 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
623 * Display the form (sending to the context's OutputPage object), with an
624 * appropriate error message or stack of messages, and any validation errors, etc.
626 * @attention You should call prepareForm() before calling this function.
627 * Moreover, when doing method chaining this should be the very last method
628 * call just after prepareForm().
630 * @param $submitResult Mixed output from HTMLForm::trySubmit()
631 * @return Nothing, should be last call
633 function displayForm( $submitResult ) {
634 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
638 * Returns the raw HTML generated by the form
639 * @param $submitResult Mixed output from HTMLForm::trySubmit()
642 function getHTML( $submitResult ) {
643 # For good measure (it is the default)
644 $this->getOutput()->preventClickjacking();
645 $this->getOutput()->addModules( 'mediawiki.htmlform' );
646 if ( $this->isVForm() ) {
647 $this->getOutput()->addModuleStyles( 'mediawiki.ui' );
648 // TODO should vertical form set setWrapperLegend( false )
649 // to hide ugly fieldsets?
653 . $this->getErrors( $submitResult )
656 . $this->getHiddenFields()
657 . $this->getButtons()
661 $html = $this->wrapForm( $html );
663 return '' . $this->mPre
. $html . $this->mPost
;
667 * Wrap the form innards in an actual "<form>" element
668 * @param string $html HTML contents to wrap.
669 * @return String wrapped HTML.
671 function wrapForm( $html ) {
673 # Include a <fieldset> wrapper for style, if requested.
674 if ( $this->mWrapperLegend
!== false ) {
675 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
677 # Use multipart/form-data
678 $encType = $this->mUseMultipart
679 ?
'multipart/form-data'
680 : 'application/x-www-form-urlencoded';
683 'action' => $this->getAction(),
684 'method' => $this->getMethod(),
685 'class' => array( 'visualClear' ),
686 'enctype' => $encType,
688 if ( !empty( $this->mId
) ) {
689 $attribs['id'] = $this->mId
;
692 if ( $this->isVForm() ) {
693 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
695 return Html
::rawElement( 'form', $attribs, $html );
699 * Get the hidden fields that should go inside the form.
700 * @return String HTML.
702 function getHiddenFields() {
703 global $wgArticlePath;
706 if ( $this->getMethod() == 'post' ) {
707 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
708 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
711 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
712 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
715 foreach ( $this->mHiddenFields
as $data ) {
716 list( $value, $attribs ) = $data;
717 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
724 * Get the submit and (potentially) reset buttons.
725 * @return String HTML.
727 function getButtons() {
728 $html = '<span class="mw-htmlform-submit-buttons">';
730 if ( $this->mShowSubmit
) {
733 if ( isset( $this->mSubmitID
) ) {
734 $attribs['id'] = $this->mSubmitID
;
737 if ( isset( $this->mSubmitName
) ) {
738 $attribs['name'] = $this->mSubmitName
;
741 if ( isset( $this->mSubmitTooltip
) ) {
742 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
745 $attribs['class'] = array( 'mw-htmlform-submit' );
747 if ( $this->isVForm() ) {
748 // mw-ui-block is necessary because the buttons aren't necessarily in an
749 // immediate child div of the vform.
750 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-big', 'mw-ui-primary', 'mw-ui-block' );
753 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
755 // Buttons are top-level form elements in table and div layouts,
756 // but vform wants all elements inside divs to get spaced-out block
758 if ( $this->isVForm() ) {
759 $html = Html
::rawElement( 'div', null, "\n$html\n" );
763 if ( $this->mShowReset
) {
764 $html .= Html
::element(
768 'value' => $this->msg( 'htmlform-reset' )->text()
773 foreach ( $this->mButtons
as $button ) {
776 'name' => $button['name'],
777 'value' => $button['value']
780 if ( $button['attribs'] ) {
781 $attrs +
= $button['attribs'];
784 if ( isset( $button['id'] ) ) {
785 $attrs['id'] = $button['id'];
788 $html .= Html
::element( 'input', $attrs );
797 * Get the whole body of the form.
801 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
805 * Format and display an error message stack.
806 * @param $errors String|Array|Status
809 function getErrors( $errors ) {
810 if ( $errors instanceof Status
) {
811 if ( $errors->isOK() ) {
814 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
816 } elseif ( is_array( $errors ) ) {
817 $errorstr = $this->formatErrors( $errors );
823 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
828 * Format a stack of error messages into a single HTML string
829 * @param array $errors of message keys/values
830 * @return String HTML, a "<ul>" list of errors
832 public static function formatErrors( $errors ) {
835 foreach ( $errors as $error ) {
836 if ( is_array( $error ) ) {
837 $msg = array_shift( $error );
843 $errorstr .= Html
::rawElement(
846 wfMessage( $msg, $error )->parse()
850 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
856 * Set the text for the submit button
857 * @param string $t plaintext.
858 * @return HTMLForm $this for chaining calls (since 1.20)
860 function setSubmitText( $t ) {
861 $this->mSubmitText
= $t;
866 * Set the text for the submit button to a message
868 * @param string $msg message key
869 * @return HTMLForm $this for chaining calls (since 1.20)
871 public function setSubmitTextMsg( $msg ) {
872 $this->setSubmitText( $this->msg( $msg )->text() );
877 * Get the text for the submit button, either customised or a default.
880 function getSubmitText() {
881 return $this->mSubmitText
883 : $this->msg( 'htmlform-submit' )->text();
887 * @param string $name Submit button name
888 * @return HTMLForm $this for chaining calls (since 1.20)
890 public function setSubmitName( $name ) {
891 $this->mSubmitName
= $name;
896 * @param string $name Tooltip for the submit button
897 * @return HTMLForm $this for chaining calls (since 1.20)
899 public function setSubmitTooltip( $name ) {
900 $this->mSubmitTooltip
= $name;
905 * Set the id for the submit button.
907 * @todo FIXME: Integrity of $t is *not* validated
908 * @return HTMLForm $this for chaining calls (since 1.20)
910 function setSubmitID( $t ) {
911 $this->mSubmitID
= $t;
916 * Stop a default submit button being shown for this form. This implies that an
917 * alternate submit method must be provided manually.
921 * @param bool $suppressSubmit Set to false to re-enable the button again
923 * @return HTMLForm $this for chaining calls
925 function suppressDefaultSubmit( $suppressSubmit = true ) {
926 $this->mShowSubmit
= !$suppressSubmit;
931 * Set the id of the \<table\> or outermost \<div\> element.
934 * @param string $id new value of the id attribute, or "" to remove
935 * @return HTMLForm $this for chaining calls
937 public function setTableId( $id ) {
938 $this->mTableId
= $id;
943 * @param string $id DOM id for the form
944 * @return HTMLForm $this for chaining calls (since 1.20)
946 public function setId( $id ) {
952 * Prompt the whole form to be wrapped in a "<fieldset>", with
953 * this text as its "<legend>" element.
954 * @param string|false $legend HTML to go inside the "<legend>" element, or
955 * false for no <legend>
957 * @return HTMLForm $this for chaining calls (since 1.20)
959 public function setWrapperLegend( $legend ) {
960 $this->mWrapperLegend
= $legend;
965 * Prompt the whole form to be wrapped in a "<fieldset>", with
966 * this message as its "<legend>" element.
968 * @param string $msg message key
969 * @return HTMLForm $this for chaining calls (since 1.20)
971 public function setWrapperLegendMsg( $msg ) {
972 $this->setWrapperLegend( $this->msg( $msg )->text() );
977 * Set the prefix for various default messages
978 * @todo currently only used for the "<fieldset>" legend on forms
979 * with multiple sections; should be used elsewhere?
981 * @return HTMLForm $this for chaining calls (since 1.20)
983 function setMessagePrefix( $p ) {
984 $this->mMessagePrefix
= $p;
989 * Set the title for form submission
990 * @param $t Title of page the form is on/should be posted to
991 * @return HTMLForm $this for chaining calls (since 1.20)
993 function setTitle( $t ) {
1002 function getTitle() {
1003 return $this->mTitle
=== false
1004 ?
$this->getContext()->getTitle()
1009 * Set the method used to submit the form
1010 * @param $method String
1011 * @return HTMLForm $this for chaining calls (since 1.20)
1013 public function setMethod( $method = 'post' ) {
1014 $this->mMethod
= $method;
1018 public function getMethod() {
1019 return $this->mMethod
;
1024 * @param array[]|HTMLFormField[] $fields array of fields (either arrays or objects)
1025 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
1026 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
1027 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields
1030 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '', &$hasUserVisibleFields = false ) {
1031 $displayFormat = $this->getDisplayFormat();
1034 $subsectionHtml = '';
1037 switch( $displayFormat ) {
1039 $getFieldHtmlMethod = 'getTableRow';
1042 // Close enough to a div.
1043 $getFieldHtmlMethod = 'getDiv';
1046 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1049 foreach ( $fields as $key => $value ) {
1050 if ( $value instanceof HTMLFormField
) {
1051 $v = empty( $value->mParams
['nodata'] )
1052 ?
$this->mFieldData
[$key]
1053 : $value->getDefault();
1054 $html .= $value->$getFieldHtmlMethod( $v );
1056 $labelValue = trim( $value->getLabel() );
1057 if ( $labelValue != ' ' && $labelValue !== '' ) {
1061 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1062 get_class( $value ) !== 'HTMLApiField' ) {
1063 $hasUserVisibleFields = true;
1065 } elseif ( is_array( $value ) ) {
1066 $subsectionHasVisibleFields = false;
1067 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-", $subsectionHasVisibleFields );
1070 if ( $subsectionHasVisibleFields === true ) {
1071 // Display the section with various niceties.
1072 $hasUserVisibleFields = true;
1074 $legend = $this->getLegend( $key );
1076 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1077 $section = $this->mSectionHeaders
[$key] . $section;
1079 if ( isset( $this->mSectionFooters
[$key] ) ) {
1080 $section .= $this->mSectionFooters
[$key];
1083 $attributes = array();
1084 if ( $fieldsetIDPrefix ) {
1085 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1087 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1089 // Just return the inputs, nothing fancy.
1090 $subsectionHtml .= $section;
1095 if ( $displayFormat !== 'raw' ) {
1098 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1099 $classes[] = 'mw-htmlform-nolabel';
1103 'class' => implode( ' ', $classes ),
1106 if ( $sectionName ) {
1107 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1110 if ( $displayFormat === 'table' ) {
1111 $html = Html
::rawElement( 'table', $attribs,
1112 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1113 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1114 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1118 if ( $this->mSubSectionBeforeFields
) {
1119 return $subsectionHtml . "\n" . $html;
1121 return $html . "\n" . $subsectionHtml;
1126 * Construct the form fields from the Descriptor array
1128 function loadData() {
1129 $fieldData = array();
1131 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1132 if ( !empty( $field->mParams
['nodata'] ) ) {
1134 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1135 $fieldData[$fieldname] = $field->getDefault();
1137 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1142 foreach ( $fieldData as $name => &$value ) {
1143 $field = $this->mFlatFields
[$name];
1144 $value = $field->filter( $value, $this->mFlatFields
);
1147 $this->mFieldData
= $fieldData;
1151 * Stop a reset button being shown for this form
1152 * @param bool $suppressReset set to false to re-enable the
1154 * @return HTMLForm $this for chaining calls (since 1.20)
1156 function suppressReset( $suppressReset = true ) {
1157 $this->mShowReset
= !$suppressReset;
1162 * Overload this if you want to apply special filtration routines
1163 * to the form as a whole, after it's submitted but before it's
1168 function filterDataForSubmit( $data ) {
1173 * Get a string to go in the "<legend>" of a section fieldset.
1174 * Override this if you want something more complicated.
1175 * @param $key String
1178 public function getLegend( $key ) {
1179 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1183 * Set the value for the action attribute of the form.
1184 * When set to false (which is the default state), the set title is used.
1188 * @param string|bool $action
1189 * @return HTMLForm $this for chaining calls (since 1.20)
1191 public function setAction( $action ) {
1192 $this->mAction
= $action;
1197 * Get the value for the action attribute of the form.
1203 public function getAction() {
1204 global $wgScript, $wgArticlePath;
1206 // If an action is alredy provided, return it
1207 if ( $this->mAction
!== false ) {
1208 return $this->mAction
;
1211 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1212 // meaning that getLocalURL() would return something like "index.php?title=...".
1213 // As browser remove the query string before submitting GET forms,
1214 // it means that the title would be lost. In such case use $wgScript instead
1215 // and put title in an hidden field (see getHiddenFields()).
1216 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1220 return $this->getTitle()->getLocalURL();
1225 * The parent class to generate form fields. Any field type should
1226 * be a subclass of this.
1228 abstract class HTMLFormField
{
1230 protected $mValidationCallback;
1231 protected $mFilterCallback;
1234 protected $mLabel; # String label. Set on construction
1236 protected $mClass = '';
1237 protected $mDefault;
1240 * @var bool If true will generate an empty div element with no label
1243 protected $mShowEmptyLabels = true;
1251 * This function must be implemented to return the HTML to generate
1252 * the input object itself. It should not implement the surrounding
1253 * table cells/rows, or labels/help messages.
1254 * @param string $value the value to set the input to; eg a default
1255 * text for a text input.
1256 * @return String valid HTML.
1258 abstract function getInputHTML( $value );
1261 * Get a translated interface message
1263 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1264 * and wfMessage() otherwise.
1266 * Parameters are the same as wfMessage().
1268 * @return Message object
1271 $args = func_get_args();
1273 if ( $this->mParent
) {
1274 $callback = array( $this->mParent
, 'msg' );
1276 $callback = 'wfMessage';
1279 return call_user_func_array( $callback, $args );
1283 * Override this function to add specific validation checks on the
1284 * field input. Don't forget to call parent::validate() to ensure
1285 * that the user-defined callback mValidationCallback is still run
1286 * @param string $value the value the field was submitted with
1287 * @param array $alldata the data collected from the form
1288 * @return Mixed Bool true on success, or String error to display.
1290 function validate( $value, $alldata ) {
1291 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value === '' ) {
1292 return $this->msg( 'htmlform-required' )->parse();
1295 if ( isset( $this->mValidationCallback
) ) {
1296 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
1302 function filter( $value, $alldata ) {
1303 if ( isset( $this->mFilterCallback
) ) {
1304 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
1311 * Should this field have a label, or is there no input element with the
1312 * appropriate id for the label to point to?
1314 * @return bool True to output a label, false to suppress
1316 protected function needsLabel() {
1321 * Tell the field whether to generate a separate label element if its label
1325 * @param bool $show Set to false to not generate a label.
1328 public function setShowEmptyLabel( $show ) {
1329 $this->mShowEmptyLabels
= $show;
1333 * Get the value that this input has been set to from a posted form,
1334 * or the input's default value if it has not been set.
1335 * @param $request WebRequest
1336 * @return String the value
1338 function loadDataFromRequest( $request ) {
1339 if ( $request->getCheck( $this->mName
) ) {
1340 return $request->getText( $this->mName
);
1342 return $this->getDefault();
1347 * Initialise the object
1348 * @param array $params Associative Array. See HTMLForm doc for syntax.
1350 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1351 * @throws MWException
1353 function __construct( $params ) {
1354 $this->mParams
= $params;
1356 # Generate the label from a message, if possible
1357 if ( isset( $params['label-message'] ) ) {
1358 $msgInfo = $params['label-message'];
1360 if ( is_array( $msgInfo ) ) {
1361 $msg = array_shift( $msgInfo );
1367 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
1368 } elseif ( isset( $params['label'] ) ) {
1369 if ( $params['label'] === ' ' ) {
1370 // Apparently some things set   directly and in an odd format
1371 $this->mLabel
= ' ';
1373 $this->mLabel
= htmlspecialchars( $params['label'] );
1375 } elseif ( isset( $params['label-raw'] ) ) {
1376 $this->mLabel
= $params['label-raw'];
1379 $this->mName
= "wp{$params['fieldname']}";
1380 if ( isset( $params['name'] ) ) {
1381 $this->mName
= $params['name'];
1384 $validName = Sanitizer
::escapeId( $this->mName
);
1385 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1386 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1389 $this->mID
= "mw-input-{$this->mName}";
1391 if ( isset( $params['default'] ) ) {
1392 $this->mDefault
= $params['default'];
1395 if ( isset( $params['id'] ) ) {
1396 $id = $params['id'];
1397 $validId = Sanitizer
::escapeId( $id );
1399 if ( $id != $validId ) {
1400 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1406 if ( isset( $params['cssclass'] ) ) {
1407 $this->mClass
= $params['cssclass'];
1410 if ( isset( $params['validation-callback'] ) ) {
1411 $this->mValidationCallback
= $params['validation-callback'];
1414 if ( isset( $params['filter-callback'] ) ) {
1415 $this->mFilterCallback
= $params['filter-callback'];
1418 if ( isset( $params['flatlist'] ) ) {
1419 $this->mClass
.= ' mw-htmlform-flatlist';
1422 if ( isset( $params['hidelabel'] ) ) {
1423 $this->mShowEmptyLabels
= false;
1428 * Get the complete table row for the input, including help text,
1429 * labels, and whatever.
1430 * @param string $value the value to set the input to.
1431 * @return String complete HTML table row.
1433 function getTableRow( $value ) {
1434 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1435 $inputHtml = $this->getInputHTML( $value );
1436 $fieldType = get_class( $this );
1437 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1438 $cellAttributes = array();
1440 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1441 $cellAttributes['colspan'] = 2;
1442 $verticalLabel = true;
1444 $verticalLabel = false;
1447 $label = $this->getLabelHtml( $cellAttributes );
1449 $field = Html
::rawElement(
1451 array( 'class' => 'mw-input' ) +
$cellAttributes,
1452 $inputHtml . "\n$errors"
1455 if ( $verticalLabel ) {
1456 $html = Html
::rawElement( 'tr',
1457 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1458 $html .= Html
::rawElement( 'tr',
1459 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1462 $html = Html
::rawElement( 'tr',
1463 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1467 return $html . $helptext;
1471 * Get the complete div for the input, including help text,
1472 * labels, and whatever.
1474 * @param string $value the value to set the input to.
1475 * @return String complete HTML table row.
1477 public function getDiv( $value ) {
1478 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1479 $inputHtml = $this->getInputHTML( $value );
1480 $fieldType = get_class( $this );
1481 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1482 $cellAttributes = array();
1483 $label = $this->getLabelHtml( $cellAttributes );
1485 $outerDivClass = array(
1487 'mw-htmlform-nolabel' => ( $label === '' )
1490 $field = Html
::rawElement(
1492 array( 'class' => $outerDivClass ) +
$cellAttributes,
1493 $inputHtml . "\n$errors"
1495 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
1496 if ( $this->mParent
->isVForm() ) {
1497 $divCssClasses[] = 'mw-ui-vform-div';
1499 $html = Html
::rawElement( 'div',
1500 array( 'class' => $divCssClasses ),
1507 * Get the complete raw fields for the input, including help text,
1508 * labels, and whatever.
1510 * @param string $value the value to set the input to.
1511 * @return String complete HTML table row.
1513 public function getRaw( $value ) {
1514 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1515 $inputHtml = $this->getInputHTML( $value );
1516 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1517 $cellAttributes = array();
1518 $label = $this->getLabelHtml( $cellAttributes );
1520 $html = "\n$errors";
1522 $html .= $inputHtml;
1528 * Generate help text HTML in table format
1530 * @param $helptext String|null
1533 public function getHelpTextHtmlTable( $helptext ) {
1534 if ( is_null( $helptext ) ) {
1538 $row = Html
::rawElement(
1540 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1543 $row = Html
::rawElement( 'tr', array(), $row );
1548 * Generate help text HTML in div format
1550 * @param $helptext String|null
1553 public function getHelpTextHtmlDiv( $helptext ) {
1554 if ( is_null( $helptext ) ) {
1558 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1563 * Generate help text HTML formatted for raw output
1565 * @param $helptext String|null
1568 public function getHelpTextHtmlRaw( $helptext ) {
1569 return $this->getHelpTextHtmlDiv( $helptext );
1573 * Determine the help text to display
1577 public function getHelpText() {
1580 if ( isset( $this->mParams
['help-message'] ) ) {
1581 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1584 if ( isset( $this->mParams
['help-messages'] ) ) {
1585 foreach ( $this->mParams
['help-messages'] as $name ) {
1586 $helpMessage = (array)$name;
1587 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1589 if ( $msg->exists() ) {
1590 if ( is_null( $helptext ) ) {
1593 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1595 $helptext .= $msg->parse(); // Append message
1599 elseif ( isset( $this->mParams
['help'] ) ) {
1600 $helptext = $this->mParams
['help'];
1606 * Determine form errors to display and their classes
1608 * @param string $value the value of the input
1611 public function getErrorsAndErrorClass( $value ) {
1612 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1614 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1618 $errors = self
::formatErrors( $errors );
1619 $errorClass = 'mw-htmlform-invalid-input';
1621 return array( $errors, $errorClass );
1624 function getLabel() {
1625 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
1628 function getLabelHtml( $cellAttributes = array() ) {
1629 # Don't output a for= attribute for labels with no associated input.
1630 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1633 if ( $this->needsLabel() ) {
1634 $for['for'] = $this->mID
;
1637 $labelValue = trim( $this->getLabel() );
1639 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1643 $displayFormat = $this->mParent
->getDisplayFormat();
1646 if ( $displayFormat === 'table' ) {
1647 $html = Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1648 Html
::rawElement( 'label', $for, $labelValue )
1650 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
1651 if ( $displayFormat === 'div' ) {
1652 $html = Html
::rawElement(
1654 array( 'class' => 'mw-label' ) +
$cellAttributes,
1655 Html
::rawElement( 'label', $for, $labelValue )
1658 $html = Html
::rawElement( 'label', $for, $labelValue );
1665 function getDefault() {
1666 if ( isset( $this->mDefault
) ) {
1667 return $this->mDefault
;
1674 * Returns the attributes required for the tooltip and accesskey.
1676 * @return array Attributes
1678 public function getTooltipAndAccessKey() {
1679 if ( empty( $this->mParams
['tooltip'] ) ) {
1682 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1686 * flatten an array of options to a single array, for instance,
1687 * a set of "<options>" inside "<optgroups>".
1688 * @param array $options Associative Array with values either Strings
1690 * @return Array flattened input
1692 public static function flattenOptions( $options ) {
1693 $flatOpts = array();
1695 foreach ( $options as $value ) {
1696 if ( is_array( $value ) ) {
1697 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1699 $flatOpts[] = $value;
1707 * Formats one or more errors as accepted by field validation-callback.
1708 * @param $errors String|Message|Array of strings or Message instances
1709 * @return String html
1712 protected static function formatErrors( $errors ) {
1713 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1714 $errors = array_shift( $errors );
1717 if ( is_array( $errors ) ) {
1719 foreach ( $errors as $error ) {
1720 if ( $error instanceof Message
) {
1721 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1723 $lines[] = Html
::rawElement( 'li', array(), $error );
1726 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1728 if ( $errors instanceof Message
) {
1729 $errors = $errors->parse();
1731 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1736 class HTMLTextField
extends HTMLFormField
{
1737 function getSize() {
1738 return isset( $this->mParams
['size'] )
1739 ?
$this->mParams
['size']
1743 function getInputHTML( $value ) {
1746 'name' => $this->mName
,
1747 'size' => $this->getSize(),
1749 ) +
$this->getTooltipAndAccessKey();
1751 if ( $this->mClass
!== '' ) {
1752 $attribs['class'] = $this->mClass
;
1755 if ( !empty( $this->mParams
['disabled'] ) ) {
1756 $attribs['disabled'] = 'disabled';
1759 # TODO: Enforce pattern, step, required, readonly on the server side as
1761 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1762 'placeholder', 'list', 'maxlength' );
1763 foreach ( $allowedParams as $param ) {
1764 if ( isset( $this->mParams
[$param] ) ) {
1765 $attribs[$param] = $this->mParams
[$param];
1769 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1770 if ( isset( $this->mParams
[$param] ) ) {
1771 $attribs[$param] = '';
1775 # Implement tiny differences between some field variants
1776 # here, rather than creating a new class for each one which
1777 # is essentially just a clone of this one.
1778 if ( isset( $this->mParams
['type'] ) ) {
1779 switch ( $this->mParams
['type'] ) {
1781 $attribs['type'] = 'email';
1784 $attribs['type'] = 'number';
1787 $attribs['type'] = 'number';
1788 $attribs['step'] = 'any';
1793 $attribs['type'] = $this->mParams
['type'];
1798 return Html
::element( 'input', $attribs );
1801 class HTMLTextAreaField
extends HTMLFormField
{
1802 const DEFAULT_COLS
= 80;
1803 const DEFAULT_ROWS
= 25;
1805 function getCols() {
1806 return isset( $this->mParams
['cols'] )
1807 ?
$this->mParams
['cols']
1808 : static::DEFAULT_COLS
;
1811 function getRows() {
1812 return isset( $this->mParams
['rows'] )
1813 ?
$this->mParams
['rows']
1814 : static::DEFAULT_ROWS
;
1817 function getInputHTML( $value ) {
1820 'name' => $this->mName
,
1821 'cols' => $this->getCols(),
1822 'rows' => $this->getRows(),
1823 ) +
$this->getTooltipAndAccessKey();
1825 if ( $this->mClass
!== '' ) {
1826 $attribs['class'] = $this->mClass
;
1829 if ( !empty( $this->mParams
['disabled'] ) ) {
1830 $attribs['disabled'] = 'disabled';
1833 if ( !empty( $this->mParams
['readonly'] ) ) {
1834 $attribs['readonly'] = 'readonly';
1837 if ( isset( $this->mParams
['placeholder'] ) ) {
1838 $attribs['placeholder'] = $this->mParams
['placeholder'];
1841 foreach ( array( 'required', 'autofocus' ) as $param ) {
1842 if ( isset( $this->mParams
[$param] ) ) {
1843 $attribs[$param] = '';
1847 return Html
::element( 'textarea', $attribs, $value );
1852 * A field that will contain a numeric value
1854 class HTMLFloatField
extends HTMLTextField
{
1855 function getSize() {
1856 return isset( $this->mParams
['size'] )
1857 ?
$this->mParams
['size']
1861 function validate( $value, $alldata ) {
1862 $p = parent
::validate( $value, $alldata );
1864 if ( $p !== true ) {
1868 $value = trim( $value );
1870 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1871 # with the addition that a leading '+' sign is ok.
1872 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1873 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1876 # The "int" part of these message names is rather confusing.
1877 # They make equal sense for all numbers.
1878 if ( isset( $this->mParams
['min'] ) ) {
1879 $min = $this->mParams
['min'];
1881 if ( $min > $value ) {
1882 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1886 if ( isset( $this->mParams
['max'] ) ) {
1887 $max = $this->mParams
['max'];
1889 if ( $max < $value ) {
1890 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1899 * A field that must contain a number
1901 class HTMLIntField
extends HTMLFloatField
{
1902 function validate( $value, $alldata ) {
1903 $p = parent
::validate( $value, $alldata );
1905 if ( $p !== true ) {
1909 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1910 # with the addition that a leading '+' sign is ok. Note that leading zeros
1911 # are fine, and will be left in the input, which is useful for things like
1912 # phone numbers when you know that they are integers (the HTML5 type=tel
1913 # input does not require its value to be numeric). If you want a tidier
1914 # value to, eg, save in the DB, clean it up with intval().
1915 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1917 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1927 class HTMLCheckField
extends HTMLFormField
{
1928 function getInputHTML( $value ) {
1929 if ( !empty( $this->mParams
['invert'] ) ) {
1933 $attr = $this->getTooltipAndAccessKey();
1934 $attr['id'] = $this->mID
;
1936 if ( !empty( $this->mParams
['disabled'] ) ) {
1937 $attr['disabled'] = 'disabled';
1940 if ( $this->mClass
!== '' ) {
1941 $attr['class'] = $this->mClass
;
1944 if ( $this->mParent
->isVForm() ) {
1945 // Nest checkbox inside label.
1946 return Html
::rawElement(
1949 'class' => 'mw-ui-checkbox-label'
1956 // Html:rawElement doesn't escape contents.
1957 htmlspecialchars( $this->mLabel
)
1960 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1961 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1966 * For a checkbox, the label goes on the right hand side, and is
1967 * added in getInputHTML(), rather than HTMLFormField::getRow()
1970 function getLabel() {
1975 * checkboxes don't need a label.
1977 protected function needsLabel() {
1982 * @param $request WebRequest
1985 function loadDataFromRequest( $request ) {
1987 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1991 // GetCheck won't work like we want for checks.
1992 // Fetch the value in either one of the two following case:
1993 // - we have a valid token (form got posted or GET forged by the user)
1994 // - checkbox name has a value (false or true), ie is not null
1995 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1996 // XOR has the following truth table, which is what we want
1997 // INVERT VALUE | OUTPUT
1998 // true true | false
1999 // false true | true
2000 // false false | false
2001 // true false | true
2002 return $request->getBool( $this->mName
) xor $invert;
2004 return $this->getDefault();
2011 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
2012 * options, uses an array of rows and an array of columns to dynamically
2013 * construct a matrix of options. The tags used to identify a particular cell
2014 * are of the form "columnName-rowName"
2018 * - Required list of columns in the matrix.
2020 * - Required list of rows in the matrix.
2021 * - force-options-on
2022 * - Accepts array of column-row tags to be displayed as enabled but unavailable to change
2023 * - force-options-off
2024 * - Accepts array of column-row tags to be displayed as disabled but unavailable to change.
2026 * - Optional array mapping row label to tooltip content
2028 * - Optional CSS class used on tooltip container span. Defaults to mw-icon-question.
2030 class HTMLCheckMatrix
extends HTMLFormField
implements HTMLNestedFilterable
{
2032 static private $requiredParams = array(
2033 // Required by underlying HTMLFormField
2035 // Required by HTMLCheckMatrix
2039 public function __construct( $params ) {
2040 $missing = array_diff( self
::$requiredParams, array_keys( $params ) );
2042 throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
2044 parent
::__construct( $params );
2047 function validate( $value, $alldata ) {
2048 $rows = $this->mParams
['rows'];
2049 $columns = $this->mParams
['columns'];
2051 // Make sure user-defined validation callback is run
2052 $p = parent
::validate( $value, $alldata );
2053 if ( $p !== true ) {
2057 // Make sure submitted value is an array
2058 if ( !is_array( $value ) ) {
2062 // If all options are valid, array_intersect of the valid options
2063 // and the provided options will return the provided options.
2064 $validOptions = array();
2065 foreach ( $rows as $rowTag ) {
2066 foreach ( $columns as $columnTag ) {
2067 $validOptions[] = $columnTag . '-' . $rowTag;
2070 $validValues = array_intersect( $value, $validOptions );
2071 if ( count( $validValues ) == count( $value ) ) {
2074 return $this->msg( 'htmlform-select-badoption' )->parse();
2079 * Build a table containing a matrix of checkbox options.
2080 * The value of each option is a combination of the row tag and column tag.
2081 * mParams['rows'] is an array with row labels as keys and row tags as values.
2082 * mParams['columns'] is an array with column labels as keys and column tags as values.
2083 * @param array $value of the options that should be checked
2086 function getInputHTML( $value ) {
2088 $tableContents = '';
2090 $rows = $this->mParams
['rows'];
2091 $columns = $this->mParams
['columns'];
2093 // If the disabled param is set, disable all the options
2094 if ( !empty( $this->mParams
['disabled'] ) ) {
2095 $attribs['disabled'] = 'disabled';
2098 // Build the column headers
2099 $headerContents = Html
::rawElement( 'td', array(), ' ' );
2100 foreach ( $columns as $columnLabel => $columnTag ) {
2101 $headerContents .= Html
::rawElement( 'td', array(), $columnLabel );
2103 $tableContents .= Html
::rawElement( 'tr', array(), "\n$headerContents\n" );
2105 $tooltipClass = 'mw-icon-question';
2106 if ( isset( $this->mParams
['tooltip-class'] ) ) {
2107 $tooltipClass = $this->mParams
['tooltip-class'];
2110 // Build the options matrix
2111 foreach ( $rows as $rowLabel => $rowTag ) {
2112 // Append tooltip if configured
2113 if ( isset( $this->mParams
['tooltips'][$rowLabel] ) ) {
2114 $tooltipAttribs = array(
2115 'class' => "mw-htmlform-tooltip $tooltipClass",
2116 'title' => $this->mParams
['tooltips'][$rowLabel],
2118 $rowLabel .= ' ' . Html
::element( 'span', $tooltipAttribs, '' );
2120 $rowContents = Html
::rawElement( 'td', array(), $rowLabel );
2121 foreach ( $columns as $columnTag ) {
2122 $thisTag = "$columnTag-$rowTag";
2123 // Construct the checkbox
2124 $thisAttribs = array(
2125 'id' => "{$this->mID}-$thisTag",
2126 'value' => $thisTag,
2128 $checked = in_array( $thisTag, (array)$value, true );
2129 if ( $this->isTagForcedOff( $thisTag ) ) {
2131 $thisAttribs['disabled'] = 1;
2132 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2134 $thisAttribs['disabled'] = 1;
2136 $rowContents .= Html
::rawElement(
2139 Xml
::check( "{$this->mName}[]", $checked, $attribs +
$thisAttribs )
2142 $tableContents .= Html
::rawElement( 'tr', array(), "\n$rowContents\n" );
2145 // Put it all in a table
2146 $html .= Html
::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
2147 Html
::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
2152 protected function isTagForcedOff( $tag ) {
2153 return isset( $this->mParams
['force-options-off'] )
2154 && in_array( $tag, $this->mParams
['force-options-off'] );
2157 protected function isTagForcedOn( $tag ) {
2158 return isset( $this->mParams
['force-options-on'] )
2159 && in_array( $tag, $this->mParams
['force-options-on'] );
2163 * Get the complete table row for the input, including help text,
2164 * labels, and whatever.
2165 * We override this function since the label should always be on a separate
2166 * line above the options in the case of a checkbox matrix, i.e. it's always
2167 * a "vertical-label".
2168 * @param string $value the value to set the input to
2169 * @return String complete HTML table row
2171 function getTableRow( $value ) {
2172 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
2173 $inputHtml = $this->getInputHTML( $value );
2174 $fieldType = get_class( $this );
2175 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
2176 $cellAttributes = array( 'colspan' => 2 );
2178 $label = $this->getLabelHtml( $cellAttributes );
2180 $field = Html
::rawElement(
2182 array( 'class' => 'mw-input' ) +
$cellAttributes,
2183 $inputHtml . "\n$errors"
2186 $html = Html
::rawElement( 'tr',
2187 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2188 $html .= Html
::rawElement( 'tr',
2189 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2192 return $html . $helptext;
2196 * @param $request WebRequest
2199 function loadDataFromRequest( $request ) {
2200 if ( $this->mParent
->getMethod() == 'post' ) {
2201 if ( $request->wasPosted() ) {
2202 // Checkboxes are not added to the request arrays if they're not checked,
2203 // so it's perfectly possible for there not to be an entry at all
2204 return $request->getArray( $this->mName
, array() );
2206 // That's ok, the user has not yet submitted the form, so show the defaults
2207 return $this->getDefault();
2210 // This is the impossible case: if we look at $_GET and see no data for our
2211 // field, is it because the user has not yet submitted the form, or that they
2212 // have submitted it with all the options unchecked. We will have to assume the
2213 // latter, which basically means that you can't specify 'positive' defaults
2215 return $request->getArray( $this->mName
, array() );
2219 function getDefault() {
2220 if ( isset( $this->mDefault
) ) {
2221 return $this->mDefault
;
2227 function filterDataForSubmit( $data ) {
2228 $columns = HTMLFormField
::flattenOptions( $this->mParams
['columns'] );
2229 $rows = HTMLFormField
::flattenOptions( $this->mParams
['rows'] );
2231 foreach ( $columns as $column ) {
2232 foreach ( $rows as $row ) {
2233 // Make sure option hasn't been forced
2234 $thisTag = "$column-$row";
2235 if ( $this->isTagForcedOff( $thisTag ) ) {
2236 $res[$thisTag] = false;
2237 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2238 $res[$thisTag] = true;
2240 $res[$thisTag] = in_array( $thisTag, $data );
2250 * A select dropdown field. Basically a wrapper for Xmlselect class
2252 class HTMLSelectField
extends HTMLFormField
{
2253 function validate( $value, $alldata ) {
2254 $p = parent
::validate( $value, $alldata );
2256 if ( $p !== true ) {
2260 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2262 if ( in_array( $value, $validOptions ) ) {
2265 return $this->msg( 'htmlform-select-badoption' )->parse();
2269 function getInputHTML( $value ) {
2270 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
2272 # If one of the options' 'name' is int(0), it is automatically selected.
2273 # because PHP sucks and thinks int(0) == 'some string'.
2274 # Working around this by forcing all of them to strings.
2275 foreach ( $this->mParams
['options'] as &$opt ) {
2276 if ( is_int( $opt ) ) {
2277 $opt = strval( $opt );
2280 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2282 if ( !empty( $this->mParams
['disabled'] ) ) {
2283 $select->setAttribute( 'disabled', 'disabled' );
2286 if ( $this->mClass
!== '' ) {
2287 $select->setAttribute( 'class', $this->mClass
);
2290 $select->addOptions( $this->mParams
['options'] );
2292 return $select->getHTML();
2297 * Select dropdown field, with an additional "other" textbox.
2299 class HTMLSelectOrOtherField
extends HTMLTextField
{
2301 function __construct( $params ) {
2302 if ( !in_array( 'other', $params['options'], true ) ) {
2303 $msg = isset( $params['other'] ) ?
2305 wfMessage( 'htmlform-selectorother-other' )->text();
2306 $params['options'][$msg] = 'other';
2309 parent
::__construct( $params );
2312 static function forceToStringRecursive( $array ) {
2313 if ( is_array( $array ) ) {
2314 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
2316 return strval( $array );
2320 function getInputHTML( $value ) {
2321 $valInSelect = false;
2323 if ( $value !== false ) {
2324 $valInSelect = in_array(
2326 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
2330 $selected = $valInSelect ?
$value : 'other';
2332 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
2334 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
2335 $select->addOptions( $opts );
2337 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2339 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
2341 if ( !empty( $this->mParams
['disabled'] ) ) {
2342 $select->setAttribute( 'disabled', 'disabled' );
2343 $tbAttribs['disabled'] = 'disabled';
2346 $select = $select->getHTML();
2348 if ( isset( $this->mParams
['maxlength'] ) ) {
2349 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
2352 if ( $this->mClass
!== '' ) {
2353 $tbAttribs['class'] = $this->mClass
;
2356 $textbox = Html
::input(
2357 $this->mName
. '-other',
2358 $valInSelect ?
'' : $value,
2363 return "$select<br />\n$textbox";
2367 * @param $request WebRequest
2370 function loadDataFromRequest( $request ) {
2371 if ( $request->getCheck( $this->mName
) ) {
2372 $val = $request->getText( $this->mName
);
2374 if ( $val == 'other' ) {
2375 $val = $request->getText( $this->mName
. '-other' );
2380 return $this->getDefault();
2386 * Multi-select field
2388 class HTMLMultiSelectField
extends HTMLFormField
implements HTMLNestedFilterable
{
2390 function validate( $value, $alldata ) {
2391 $p = parent
::validate( $value, $alldata );
2393 if ( $p !== true ) {
2397 if ( !is_array( $value ) ) {
2401 # If all options are valid, array_intersect of the valid options
2402 # and the provided options will return the provided options.
2403 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2405 $validValues = array_intersect( $value, $validOptions );
2406 if ( count( $validValues ) == count( $value ) ) {
2409 return $this->msg( 'htmlform-select-badoption' )->parse();
2413 function getInputHTML( $value ) {
2414 $html = $this->formatOptions( $this->mParams
['options'], $value );
2419 function formatOptions( $options, $value ) {
2424 if ( !empty( $this->mParams
['disabled'] ) ) {
2425 $attribs['disabled'] = 'disabled';
2428 foreach ( $options as $label => $info ) {
2429 if ( is_array( $info ) ) {
2430 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2431 $html .= $this->formatOptions( $info, $value );
2433 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2435 $checkbox = Xml
::check(
2436 $this->mName
. '[]',
2437 in_array( $info, $value, true ),
2438 $attribs +
$thisAttribs );
2439 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2441 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2449 * @param $request WebRequest
2452 function loadDataFromRequest( $request ) {
2453 if ( $this->mParent
->getMethod() == 'post' ) {
2454 if ( $request->wasPosted() ) {
2455 # Checkboxes are just not added to the request arrays if they're not checked,
2456 # so it's perfectly possible for there not to be an entry at all
2457 return $request->getArray( $this->mName
, array() );
2459 # That's ok, the user has not yet submitted the form, so show the defaults
2460 return $this->getDefault();
2463 # This is the impossible case: if we look at $_GET and see no data for our
2464 # field, is it because the user has not yet submitted the form, or that they
2465 # have submitted it with all the options unchecked? We will have to assume the
2466 # latter, which basically means that you can't specify 'positive' defaults
2469 return $request->getArray( $this->mName
, array() );
2473 function getDefault() {
2474 if ( isset( $this->mDefault
) ) {
2475 return $this->mDefault
;
2481 function filterDataForSubmit( $data ) {
2482 $options = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2485 foreach ( $options as $opt ) {
2486 $res["$opt"] = in_array( $opt, $data );
2492 protected function needsLabel() {
2498 * Double field with a dropdown list constructed from a system message in the format
2501 * * New Optgroup header
2502 * Plus a text field underneath for an additional reason. The 'value' of the field is
2503 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2505 * @todo FIXME: If made 'required', only the text field should be compulsory.
2507 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2509 function __construct( $params ) {
2510 if ( array_key_exists( 'other', $params ) ) {
2511 } elseif ( array_key_exists( 'other-message', $params ) ) {
2512 $params['other'] = wfMessage( $params['other-message'] )->plain();
2514 $params['other'] = null;
2517 if ( array_key_exists( 'options', $params ) ) {
2518 # Options array already specified
2519 } elseif ( array_key_exists( 'options-message', $params ) ) {
2520 # Generate options array from a system message
2521 $params['options'] = self
::parseMessage(
2522 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2527 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2529 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2531 parent
::__construct( $params );
2535 * Build a drop-down box from a textual list.
2536 * @param string $string message text
2537 * @param string $otherName name of "other reason" option
2539 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2541 public static function parseMessage( $string, $otherName = null ) {
2542 if ( $otherName === null ) {
2543 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2547 $options = array( $otherName => 'other' );
2549 foreach ( explode( "\n", $string ) as $option ) {
2550 $value = trim( $option );
2551 if ( $value == '' ) {
2553 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2554 # A new group is starting...
2555 $value = trim( substr( $value, 1 ) );
2557 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2559 $opt = trim( substr( $value, 2 ) );
2560 if ( $optgroup === false ) {
2561 $options[$opt] = $opt;
2563 $options[$optgroup][$opt] = $opt;
2566 # groupless reason list
2568 $options[$option] = $option;
2575 function getInputHTML( $value ) {
2576 $select = parent
::getInputHTML( $value[1] );
2578 $textAttribs = array(
2579 'id' => $this->mID
. '-other',
2580 'size' => $this->getSize(),
2583 if ( $this->mClass
!== '' ) {
2584 $textAttribs['class'] = $this->mClass
;
2587 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2588 if ( isset( $this->mParams
[$param] ) ) {
2589 $textAttribs[$param] = '';
2593 $textbox = Html
::input(
2594 $this->mName
. '-other',
2600 return "$select<br />\n$textbox";
2604 * @param $request WebRequest
2605 * @return Array("<overall message>","<select value>","<text field value>")
2607 function loadDataFromRequest( $request ) {
2608 if ( $request->getCheck( $this->mName
) ) {
2610 $list = $request->getText( $this->mName
);
2611 $text = $request->getText( $this->mName
. '-other' );
2613 if ( $list == 'other' ) {
2615 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2616 # User has spoofed the select form to give an option which wasn't
2617 # in the original offer. Sulk...
2619 } elseif ( $text == '' ) {
2622 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2626 $final = $this->getDefault();
2630 foreach ( $this->mFlatOptions
as $option ) {
2631 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2632 if ( strpos( $text, $match ) === 0 ) {
2634 $text = substr( $text, strlen( $match ) );
2639 return array( $final, $list, $text );
2642 function getSize() {
2643 return isset( $this->mParams
['size'] )
2644 ?
$this->mParams
['size']
2648 function validate( $value, $alldata ) {
2649 # HTMLSelectField forces $value to be one of the options in the select
2650 # field, which is not useful here. But we do want the validation further up
2652 $p = parent
::validate( $value[1], $alldata );
2654 if ( $p !== true ) {
2658 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value[1] === '' ) {
2659 return $this->msg( 'htmlform-required' )->parse();
2667 * Radio checkbox fields.
2669 class HTMLRadioField
extends HTMLFormField
{
2671 function validate( $value, $alldata ) {
2672 $p = parent
::validate( $value, $alldata );
2674 if ( $p !== true ) {
2678 if ( !is_string( $value ) && !is_int( $value ) ) {
2682 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2684 if ( in_array( $value, $validOptions ) ) {
2687 return $this->msg( 'htmlform-select-badoption' )->parse();
2692 * This returns a block of all the radio options, in one cell.
2693 * @see includes/HTMLFormField#getInputHTML()
2694 * @param $value String
2697 function getInputHTML( $value ) {
2698 $html = $this->formatOptions( $this->mParams
['options'], $value );
2703 function formatOptions( $options, $value ) {
2707 if ( !empty( $this->mParams
['disabled'] ) ) {
2708 $attribs['disabled'] = 'disabled';
2711 # TODO: should this produce an unordered list perhaps?
2712 foreach ( $options as $label => $info ) {
2713 if ( is_array( $info ) ) {
2714 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2715 $html .= $this->formatOptions( $info, $value );
2717 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2718 $radio = Xml
::radio(
2722 $attribs +
array( 'id' => $id )
2724 $radio .= ' ' .
2725 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2727 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2734 protected function needsLabel() {
2740 * An information field (text blob), not a proper input.
2742 class HTMLInfoField
extends HTMLFormField
{
2743 public function __construct( $info ) {
2744 $info['nodata'] = true;
2746 parent
::__construct( $info );
2749 public function getInputHTML( $value ) {
2750 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2753 public function getTableRow( $value ) {
2754 if ( !empty( $this->mParams
['rawrow'] ) ) {
2758 return parent
::getTableRow( $value );
2764 public function getDiv( $value ) {
2765 if ( !empty( $this->mParams
['rawrow'] ) ) {
2769 return parent
::getDiv( $value );
2775 public function getRaw( $value ) {
2776 if ( !empty( $this->mParams
['rawrow'] ) ) {
2780 return parent
::getRaw( $value );
2783 protected function needsLabel() {
2788 class HTMLHiddenField
extends HTMLFormField
{
2789 public function __construct( $params ) {
2790 parent
::__construct( $params );
2792 # Per HTML5 spec, hidden fields cannot be 'required'
2793 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2794 unset( $this->mParams
['required'] );
2797 public function getTableRow( $value ) {
2800 $params['id'] = $this->mID
;
2803 $this->mParent
->addHiddenField(
2815 public function getDiv( $value ) {
2816 return $this->getTableRow( $value );
2822 public function getRaw( $value ) {
2823 return $this->getTableRow( $value );
2826 public function getInputHTML( $value ) {
2832 * Add a submit button inline in the form (as opposed to
2833 * HTMLForm::addButton(), which will add it at the end).
2835 class HTMLSubmitField
extends HTMLButtonField
{
2836 protected $buttonType = 'submit';
2840 * Adds a generic button inline to the form. Does not do anything, you must add
2841 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2842 * wish to add a submit button to a form.
2846 class HTMLButtonField
extends HTMLFormField
{
2847 protected $buttonType = 'button';
2849 public function __construct( $info ) {
2850 $info['nodata'] = true;
2851 parent
::__construct( $info );
2854 public function getInputHTML( $value ) {
2856 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2860 if ( !empty( $this->mParams
['disabled'] ) ) {
2861 $attr['disabled'] = 'disabled';
2872 protected function needsLabel() {
2877 * Button cannot be invalid
2878 * @param $value String
2879 * @param $alldata Array
2882 public function validate( $value, $alldata ) {
2887 class HTMLEditTools
extends HTMLFormField
{
2888 public function getInputHTML( $value ) {
2892 public function getTableRow( $value ) {
2893 $msg = $this->formatMsg();
2895 return '<tr><td></td><td class="mw-input">'
2896 . '<div class="mw-editTools">'
2897 . $msg->parseAsBlock()
2898 . "</div></td></tr>\n";
2904 public function getDiv( $value ) {
2905 $msg = $this->formatMsg();
2906 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2912 public function getRaw( $value ) {
2913 return $this->getDiv( $value );
2916 protected function formatMsg() {
2917 if ( empty( $this->mParams
['message'] ) ) {
2918 $msg = $this->msg( 'edittools' );
2920 $msg = $this->msg( $this->mParams
['message'] );
2921 if ( $msg->isDisabled() ) {
2922 $msg = $this->msg( 'edittools' );
2925 $msg->inContentLanguage();
2930 class HTMLApiField
extends HTMLFormField
{
2931 public function getTableRow( $value ) {
2935 public function getDiv( $value ) {
2936 return $this->getTableRow( $value );
2939 public function getRaw( $value ) {
2940 return $this->getTableRow( $value );
2943 public function getInputHTML( $value ) {
2948 interface HTMLNestedFilterable
{
2950 * Support for seperating multi-option preferences into multiple preferences
2951 * Due to lack of array support.
2952 * @param $data array
2954 function filterDataForSubmit( $data );
2957 class HTMLFormFieldRequiredOptionsException
extends MWException
{
2958 public function __construct( HTMLFormField
$field, array $missing ) {
2959 parent
::__construct( sprintf(
2960 "Form type `%s` expected the following parameters to be set: %s",
2961 get_class( $field ),
2962 implode( ', ', $missing )