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()
660 $html = $this->wrapForm( $html );
662 return '' . $this->mPre
. $html . $this->mPost
;
666 * Wrap the form innards in an actual "<form>" element
667 * @param string $html HTML contents to wrap.
668 * @return String wrapped HTML.
670 function wrapForm( $html ) {
672 # Include a <fieldset> wrapper for style, if requested.
673 if ( $this->mWrapperLegend
!== false ) {
674 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
676 # Use multipart/form-data
677 $encType = $this->mUseMultipart
678 ?
'multipart/form-data'
679 : 'application/x-www-form-urlencoded';
682 'action' => $this->getAction(),
683 'method' => $this->getMethod(),
684 'class' => array( 'visualClear' ),
685 'enctype' => $encType,
687 if ( !empty( $this->mId
) ) {
688 $attribs['id'] = $this->mId
;
691 if ( $this->isVForm() ) {
692 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
694 return Html
::rawElement( 'form', $attribs, $html );
698 * Get the hidden fields that should go inside the form.
699 * @return String HTML.
701 function getHiddenFields() {
702 global $wgArticlePath;
705 if ( $this->getMethod() == 'post' ) {
706 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
707 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
710 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
711 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
714 foreach ( $this->mHiddenFields
as $data ) {
715 list( $value, $attribs ) = $data;
716 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
723 * Get the submit and (potentially) reset buttons.
724 * @return String HTML.
726 function getButtons() {
727 $html = '<span class="mw-htmlform-submit-buttons">';
729 if ( $this->mShowSubmit
) {
732 if ( isset( $this->mSubmitID
) ) {
733 $attribs['id'] = $this->mSubmitID
;
736 if ( isset( $this->mSubmitName
) ) {
737 $attribs['name'] = $this->mSubmitName
;
740 if ( isset( $this->mSubmitTooltip
) ) {
741 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
744 $attribs['class'] = array( 'mw-htmlform-submit' );
746 if ( $this->isVForm() ) {
747 // mw-ui-block is necessary because the buttons aren't necessarily in an
748 // immediate child div of the vform.
749 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-big', 'mw-ui-primary', 'mw-ui-block' );
752 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
754 // Buttons are top-level form elements in table and div layouts,
755 // but vform wants all elements inside divs to get spaced-out block
757 if ( $this->isVForm() ) {
758 $html = Html
::rawElement( 'div', null, "\n$html\n" );
762 if ( $this->mShowReset
) {
763 $html .= Html
::element(
767 'value' => $this->msg( 'htmlform-reset' )->text()
772 foreach ( $this->mButtons
as $button ) {
775 'name' => $button['name'],
776 'value' => $button['value']
779 if ( $button['attribs'] ) {
780 $attrs +
= $button['attribs'];
783 if ( isset( $button['id'] ) ) {
784 $attrs['id'] = $button['id'];
787 $html .= Html
::element( 'input', $attrs );
796 * Get the whole body of the form.
800 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
804 * Format and display an error message stack.
805 * @param $errors String|Array|Status
808 function getErrors( $errors ) {
809 if ( $errors instanceof Status
) {
810 if ( $errors->isOK() ) {
813 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
815 } elseif ( is_array( $errors ) ) {
816 $errorstr = $this->formatErrors( $errors );
822 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
827 * Format a stack of error messages into a single HTML string
828 * @param array $errors of message keys/values
829 * @return String HTML, a "<ul>" list of errors
831 public static function formatErrors( $errors ) {
834 foreach ( $errors as $error ) {
835 if ( is_array( $error ) ) {
836 $msg = array_shift( $error );
842 $errorstr .= Html
::rawElement(
845 wfMessage( $msg, $error )->parse()
849 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
855 * Set the text for the submit button
856 * @param string $t plaintext.
857 * @return HTMLForm $this for chaining calls (since 1.20)
859 function setSubmitText( $t ) {
860 $this->mSubmitText
= $t;
865 * Set the text for the submit button to a message
867 * @param string $msg message key
868 * @return HTMLForm $this for chaining calls (since 1.20)
870 public function setSubmitTextMsg( $msg ) {
871 $this->setSubmitText( $this->msg( $msg )->text() );
876 * Get the text for the submit button, either customised or a default.
879 function getSubmitText() {
880 return $this->mSubmitText
882 : $this->msg( 'htmlform-submit' )->text();
886 * @param string $name Submit button name
887 * @return HTMLForm $this for chaining calls (since 1.20)
889 public function setSubmitName( $name ) {
890 $this->mSubmitName
= $name;
895 * @param string $name Tooltip for the submit button
896 * @return HTMLForm $this for chaining calls (since 1.20)
898 public function setSubmitTooltip( $name ) {
899 $this->mSubmitTooltip
= $name;
904 * Set the id for the submit button.
906 * @todo FIXME: Integrity of $t is *not* validated
907 * @return HTMLForm $this for chaining calls (since 1.20)
909 function setSubmitID( $t ) {
910 $this->mSubmitID
= $t;
915 * Stop a default submit button being shown for this form. This implies that an
916 * alternate submit method must be provided manually.
920 * @param bool $suppressSubmit Set to false to re-enable the button again
922 * @return HTMLForm $this for chaining calls
924 function suppressDefaultSubmit( $suppressSubmit = true ) {
925 $this->mShowSubmit
= !$suppressSubmit;
930 * Set the id of the \<table\> or outermost \<div\> element.
933 * @param string $id new value of the id attribute, or "" to remove
934 * @return HTMLForm $this for chaining calls
936 public function setTableId( $id ) {
937 $this->mTableId
= $id;
942 * @param string $id DOM id for the form
943 * @return HTMLForm $this for chaining calls (since 1.20)
945 public function setId( $id ) {
951 * Prompt the whole form to be wrapped in a "<fieldset>", with
952 * this text as its "<legend>" element.
953 * @param string|false $legend HTML to go inside the "<legend>" element, or
954 * false for no <legend>
956 * @return HTMLForm $this for chaining calls (since 1.20)
958 public function setWrapperLegend( $legend ) {
959 $this->mWrapperLegend
= $legend;
964 * Prompt the whole form to be wrapped in a "<fieldset>", with
965 * this message as its "<legend>" element.
967 * @param string $msg message key
968 * @return HTMLForm $this for chaining calls (since 1.20)
970 public function setWrapperLegendMsg( $msg ) {
971 $this->setWrapperLegend( $this->msg( $msg )->text() );
976 * Set the prefix for various default messages
977 * @todo currently only used for the "<fieldset>" legend on forms
978 * with multiple sections; should be used elsewhere?
980 * @return HTMLForm $this for chaining calls (since 1.20)
982 function setMessagePrefix( $p ) {
983 $this->mMessagePrefix
= $p;
988 * Set the title for form submission
989 * @param $t Title of page the form is on/should be posted to
990 * @return HTMLForm $this for chaining calls (since 1.20)
992 function setTitle( $t ) {
1001 function getTitle() {
1002 return $this->mTitle
=== false
1003 ?
$this->getContext()->getTitle()
1008 * Set the method used to submit the form
1009 * @param $method String
1010 * @return HTMLForm $this for chaining calls (since 1.20)
1012 public function setMethod( $method = 'post' ) {
1013 $this->mMethod
= $method;
1017 public function getMethod() {
1018 return $this->mMethod
;
1023 * @param array[]|HTMLFormField[] $fields array of fields (either arrays or objects)
1024 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
1025 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
1026 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields
1029 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '', &$hasUserVisibleFields = false ) {
1030 $displayFormat = $this->getDisplayFormat();
1033 $subsectionHtml = '';
1036 switch ( $displayFormat ) {
1038 $getFieldHtmlMethod = 'getTableRow';
1041 // Close enough to a div.
1042 $getFieldHtmlMethod = 'getDiv';
1045 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1048 foreach ( $fields as $key => $value ) {
1049 if ( $value instanceof HTMLFormField
) {
1050 $v = empty( $value->mParams
['nodata'] )
1051 ?
$this->mFieldData
[$key]
1052 : $value->getDefault();
1053 $html .= $value->$getFieldHtmlMethod( $v );
1055 $labelValue = trim( $value->getLabel() );
1056 if ( $labelValue != ' ' && $labelValue !== '' ) {
1060 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1061 get_class( $value ) !== 'HTMLApiField' ) {
1062 $hasUserVisibleFields = true;
1064 } elseif ( is_array( $value ) ) {
1065 $subsectionHasVisibleFields = false;
1066 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-", $subsectionHasVisibleFields );
1069 if ( $subsectionHasVisibleFields === true ) {
1070 // Display the section with various niceties.
1071 $hasUserVisibleFields = true;
1073 $legend = $this->getLegend( $key );
1075 if ( isset( $this->mSectionHeaders
[$key] ) ) {
1076 $section = $this->mSectionHeaders
[$key] . $section;
1078 if ( isset( $this->mSectionFooters
[$key] ) ) {
1079 $section .= $this->mSectionFooters
[$key];
1082 $attributes = array();
1083 if ( $fieldsetIDPrefix ) {
1084 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1086 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1088 // Just return the inputs, nothing fancy.
1089 $subsectionHtml .= $section;
1094 if ( $displayFormat !== 'raw' ) {
1097 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1098 $classes[] = 'mw-htmlform-nolabel';
1102 'class' => implode( ' ', $classes ),
1105 if ( $sectionName ) {
1106 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1109 if ( $displayFormat === 'table' ) {
1110 $html = Html
::rawElement( 'table', $attribs,
1111 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1112 } elseif ( $displayFormat === 'div' ||
$displayFormat === 'vform' ) {
1113 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1117 if ( $this->mSubSectionBeforeFields
) {
1118 return $subsectionHtml . "\n" . $html;
1120 return $html . "\n" . $subsectionHtml;
1125 * Construct the form fields from the Descriptor array
1127 function loadData() {
1128 $fieldData = array();
1130 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1131 if ( !empty( $field->mParams
['nodata'] ) ) {
1133 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1134 $fieldData[$fieldname] = $field->getDefault();
1136 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1141 foreach ( $fieldData as $name => &$value ) {
1142 $field = $this->mFlatFields
[$name];
1143 $value = $field->filter( $value, $this->mFlatFields
);
1146 $this->mFieldData
= $fieldData;
1150 * Stop a reset button being shown for this form
1151 * @param bool $suppressReset set to false to re-enable the
1153 * @return HTMLForm $this for chaining calls (since 1.20)
1155 function suppressReset( $suppressReset = true ) {
1156 $this->mShowReset
= !$suppressReset;
1161 * Overload this if you want to apply special filtration routines
1162 * to the form as a whole, after it's submitted but before it's
1167 function filterDataForSubmit( $data ) {
1172 * Get a string to go in the "<legend>" of a section fieldset.
1173 * Override this if you want something more complicated.
1174 * @param $key String
1177 public function getLegend( $key ) {
1178 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1182 * Set the value for the action attribute of the form.
1183 * When set to false (which is the default state), the set title is used.
1187 * @param string|bool $action
1188 * @return HTMLForm $this for chaining calls (since 1.20)
1190 public function setAction( $action ) {
1191 $this->mAction
= $action;
1196 * Get the value for the action attribute of the form.
1202 public function getAction() {
1203 global $wgScript, $wgArticlePath;
1205 // If an action is alredy provided, return it
1206 if ( $this->mAction
!== false ) {
1207 return $this->mAction
;
1210 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1211 // meaning that getLocalURL() would return something like "index.php?title=...".
1212 // As browser remove the query string before submitting GET forms,
1213 // it means that the title would be lost. In such case use $wgScript instead
1214 // and put title in an hidden field (see getHiddenFields()).
1215 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1219 return $this->getTitle()->getLocalURL();
1224 * The parent class to generate form fields. Any field type should
1225 * be a subclass of this.
1227 abstract class HTMLFormField
{
1229 protected $mValidationCallback;
1230 protected $mFilterCallback;
1233 protected $mLabel; # String label. Set on construction
1235 protected $mClass = '';
1236 protected $mDefault;
1239 * @var bool If true will generate an empty div element with no label
1242 protected $mShowEmptyLabels = true;
1250 * This function must be implemented to return the HTML to generate
1251 * the input object itself. It should not implement the surrounding
1252 * table cells/rows, or labels/help messages.
1253 * @param string $value the value to set the input to; eg a default
1254 * text for a text input.
1255 * @return String valid HTML.
1257 abstract function getInputHTML( $value );
1260 * Get a translated interface message
1262 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1263 * and wfMessage() otherwise.
1265 * Parameters are the same as wfMessage().
1267 * @return Message object
1270 $args = func_get_args();
1272 if ( $this->mParent
) {
1273 $callback = array( $this->mParent
, 'msg' );
1275 $callback = 'wfMessage';
1278 return call_user_func_array( $callback, $args );
1282 * Override this function to add specific validation checks on the
1283 * field input. Don't forget to call parent::validate() to ensure
1284 * that the user-defined callback mValidationCallback is still run
1285 * @param string $value the value the field was submitted with
1286 * @param array $alldata the data collected from the form
1287 * @return Mixed Bool true on success, or String error to display.
1289 function validate( $value, $alldata ) {
1290 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value === '' ) {
1291 return $this->msg( 'htmlform-required' )->parse();
1294 if ( isset( $this->mValidationCallback
) ) {
1295 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
1301 function filter( $value, $alldata ) {
1302 if ( isset( $this->mFilterCallback
) ) {
1303 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
1310 * Should this field have a label, or is there no input element with the
1311 * appropriate id for the label to point to?
1313 * @return bool True to output a label, false to suppress
1315 protected function needsLabel() {
1320 * Tell the field whether to generate a separate label element if its label
1324 * @param bool $show Set to false to not generate a label.
1327 public function setShowEmptyLabel( $show ) {
1328 $this->mShowEmptyLabels
= $show;
1332 * Get the value that this input has been set to from a posted form,
1333 * or the input's default value if it has not been set.
1334 * @param $request WebRequest
1335 * @return String the value
1337 function loadDataFromRequest( $request ) {
1338 if ( $request->getCheck( $this->mName
) ) {
1339 return $request->getText( $this->mName
);
1341 return $this->getDefault();
1346 * Initialise the object
1347 * @param array $params Associative Array. See HTMLForm doc for syntax.
1349 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1350 * @throws MWException
1352 function __construct( $params ) {
1353 $this->mParams
= $params;
1355 # Generate the label from a message, if possible
1356 if ( isset( $params['label-message'] ) ) {
1357 $msgInfo = $params['label-message'];
1359 if ( is_array( $msgInfo ) ) {
1360 $msg = array_shift( $msgInfo );
1366 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
1367 } elseif ( isset( $params['label'] ) ) {
1368 if ( $params['label'] === ' ' ) {
1369 // Apparently some things set   directly and in an odd format
1370 $this->mLabel
= ' ';
1372 $this->mLabel
= htmlspecialchars( $params['label'] );
1374 } elseif ( isset( $params['label-raw'] ) ) {
1375 $this->mLabel
= $params['label-raw'];
1378 $this->mName
= "wp{$params['fieldname']}";
1379 if ( isset( $params['name'] ) ) {
1380 $this->mName
= $params['name'];
1383 $validName = Sanitizer
::escapeId( $this->mName
);
1384 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1385 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1388 $this->mID
= "mw-input-{$this->mName}";
1390 if ( isset( $params['default'] ) ) {
1391 $this->mDefault
= $params['default'];
1394 if ( isset( $params['id'] ) ) {
1395 $id = $params['id'];
1396 $validId = Sanitizer
::escapeId( $id );
1398 if ( $id != $validId ) {
1399 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1405 if ( isset( $params['cssclass'] ) ) {
1406 $this->mClass
= $params['cssclass'];
1409 if ( isset( $params['validation-callback'] ) ) {
1410 $this->mValidationCallback
= $params['validation-callback'];
1413 if ( isset( $params['filter-callback'] ) ) {
1414 $this->mFilterCallback
= $params['filter-callback'];
1417 if ( isset( $params['flatlist'] ) ) {
1418 $this->mClass
.= ' mw-htmlform-flatlist';
1421 if ( isset( $params['hidelabel'] ) ) {
1422 $this->mShowEmptyLabels
= false;
1427 * Get the complete table row for the input, including help text,
1428 * labels, and whatever.
1429 * @param string $value the value to set the input to.
1430 * @return String complete HTML table row.
1432 function getTableRow( $value ) {
1433 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1434 $inputHtml = $this->getInputHTML( $value );
1435 $fieldType = get_class( $this );
1436 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1437 $cellAttributes = array();
1439 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1440 $cellAttributes['colspan'] = 2;
1441 $verticalLabel = true;
1443 $verticalLabel = false;
1446 $label = $this->getLabelHtml( $cellAttributes );
1448 $field = Html
::rawElement(
1450 array( 'class' => 'mw-input' ) +
$cellAttributes,
1451 $inputHtml . "\n$errors"
1454 if ( $verticalLabel ) {
1455 $html = Html
::rawElement( 'tr',
1456 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1457 $html .= Html
::rawElement( 'tr',
1458 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1461 $html = Html
::rawElement( 'tr',
1462 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1466 return $html . $helptext;
1470 * Get the complete div for the input, including help text,
1471 * labels, and whatever.
1473 * @param string $value the value to set the input to.
1474 * @return String complete HTML table row.
1476 public function getDiv( $value ) {
1477 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1478 $inputHtml = $this->getInputHTML( $value );
1479 $fieldType = get_class( $this );
1480 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1481 $cellAttributes = array();
1482 $label = $this->getLabelHtml( $cellAttributes );
1484 $outerDivClass = array(
1486 'mw-htmlform-nolabel' => ( $label === '' )
1489 $field = Html
::rawElement(
1491 array( 'class' => $outerDivClass ) +
$cellAttributes,
1492 $inputHtml . "\n$errors"
1494 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
1495 if ( $this->mParent
->isVForm() ) {
1496 $divCssClasses[] = 'mw-ui-vform-div';
1498 $html = Html
::rawElement( 'div',
1499 array( 'class' => $divCssClasses ),
1506 * Get the complete raw fields for the input, including help text,
1507 * labels, and whatever.
1509 * @param string $value the value to set the input to.
1510 * @return String complete HTML table row.
1512 public function getRaw( $value ) {
1513 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1514 $inputHtml = $this->getInputHTML( $value );
1515 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1516 $cellAttributes = array();
1517 $label = $this->getLabelHtml( $cellAttributes );
1519 $html = "\n$errors";
1521 $html .= $inputHtml;
1527 * Generate help text HTML in table format
1529 * @param $helptext String|null
1532 public function getHelpTextHtmlTable( $helptext ) {
1533 if ( is_null( $helptext ) ) {
1537 $row = Html
::rawElement(
1539 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1542 $row = Html
::rawElement( 'tr', array(), $row );
1547 * Generate help text HTML in div format
1549 * @param $helptext String|null
1552 public function getHelpTextHtmlDiv( $helptext ) {
1553 if ( is_null( $helptext ) ) {
1557 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1562 * Generate help text HTML formatted for raw output
1564 * @param $helptext String|null
1567 public function getHelpTextHtmlRaw( $helptext ) {
1568 return $this->getHelpTextHtmlDiv( $helptext );
1572 * Determine the help text to display
1576 public function getHelpText() {
1579 if ( isset( $this->mParams
['help-message'] ) ) {
1580 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1583 if ( isset( $this->mParams
['help-messages'] ) ) {
1584 foreach ( $this->mParams
['help-messages'] as $name ) {
1585 $helpMessage = (array)$name;
1586 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1588 if ( $msg->exists() ) {
1589 if ( is_null( $helptext ) ) {
1592 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1594 $helptext .= $msg->parse(); // Append message
1598 elseif ( isset( $this->mParams
['help'] ) ) {
1599 $helptext = $this->mParams
['help'];
1605 * Determine form errors to display and their classes
1607 * @param string $value the value of the input
1610 public function getErrorsAndErrorClass( $value ) {
1611 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1613 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1617 $errors = self
::formatErrors( $errors );
1618 $errorClass = 'mw-htmlform-invalid-input';
1620 return array( $errors, $errorClass );
1623 function getLabel() {
1624 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
1627 function getLabelHtml( $cellAttributes = array() ) {
1628 # Don't output a for= attribute for labels with no associated input.
1629 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1632 if ( $this->needsLabel() ) {
1633 $for['for'] = $this->mID
;
1636 $labelValue = trim( $this->getLabel() );
1638 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1642 $displayFormat = $this->mParent
->getDisplayFormat();
1645 if ( $displayFormat === 'table' ) {
1646 $html = Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1647 Html
::rawElement( 'label', $for, $labelValue )
1649 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
1650 if ( $displayFormat === 'div' ) {
1651 $html = Html
::rawElement(
1653 array( 'class' => 'mw-label' ) +
$cellAttributes,
1654 Html
::rawElement( 'label', $for, $labelValue )
1657 $html = Html
::rawElement( 'label', $for, $labelValue );
1664 function getDefault() {
1665 if ( isset( $this->mDefault
) ) {
1666 return $this->mDefault
;
1673 * Returns the attributes required for the tooltip and accesskey.
1675 * @return array Attributes
1677 public function getTooltipAndAccessKey() {
1678 if ( empty( $this->mParams
['tooltip'] ) ) {
1681 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1685 * flatten an array of options to a single array, for instance,
1686 * a set of "<options>" inside "<optgroups>".
1687 * @param array $options Associative Array with values either Strings
1689 * @return Array flattened input
1691 public static function flattenOptions( $options ) {
1692 $flatOpts = array();
1694 foreach ( $options as $value ) {
1695 if ( is_array( $value ) ) {
1696 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1698 $flatOpts[] = $value;
1706 * Formats one or more errors as accepted by field validation-callback.
1707 * @param $errors String|Message|Array of strings or Message instances
1708 * @return String html
1711 protected static function formatErrors( $errors ) {
1712 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1713 $errors = array_shift( $errors );
1716 if ( is_array( $errors ) ) {
1718 foreach ( $errors as $error ) {
1719 if ( $error instanceof Message
) {
1720 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1722 $lines[] = Html
::rawElement( 'li', array(), $error );
1725 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1727 if ( $errors instanceof Message
) {
1728 $errors = $errors->parse();
1730 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1735 class HTMLTextField
extends HTMLFormField
{
1736 function getSize() {
1737 return isset( $this->mParams
['size'] )
1738 ?
$this->mParams
['size']
1742 function getInputHTML( $value ) {
1745 'name' => $this->mName
,
1746 'size' => $this->getSize(),
1748 ) +
$this->getTooltipAndAccessKey();
1750 if ( $this->mClass
!== '' ) {
1751 $attribs['class'] = $this->mClass
;
1754 if ( !empty( $this->mParams
['disabled'] ) ) {
1755 $attribs['disabled'] = 'disabled';
1758 # TODO: Enforce pattern, step, required, readonly on the server side as
1760 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1761 'placeholder', 'list', 'maxlength' );
1762 foreach ( $allowedParams as $param ) {
1763 if ( isset( $this->mParams
[$param] ) ) {
1764 $attribs[$param] = $this->mParams
[$param];
1768 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1769 if ( isset( $this->mParams
[$param] ) ) {
1770 $attribs[$param] = '';
1774 # Implement tiny differences between some field variants
1775 # here, rather than creating a new class for each one which
1776 # is essentially just a clone of this one.
1777 if ( isset( $this->mParams
['type'] ) ) {
1778 switch ( $this->mParams
['type'] ) {
1780 $attribs['type'] = 'email';
1783 $attribs['type'] = 'number';
1786 $attribs['type'] = 'number';
1787 $attribs['step'] = 'any';
1792 $attribs['type'] = $this->mParams
['type'];
1797 return Html
::element( 'input', $attribs );
1800 class HTMLTextAreaField
extends HTMLFormField
{
1801 const DEFAULT_COLS
= 80;
1802 const DEFAULT_ROWS
= 25;
1804 function getCols() {
1805 return isset( $this->mParams
['cols'] )
1806 ?
$this->mParams
['cols']
1807 : static::DEFAULT_COLS
;
1810 function getRows() {
1811 return isset( $this->mParams
['rows'] )
1812 ?
$this->mParams
['rows']
1813 : static::DEFAULT_ROWS
;
1816 function getInputHTML( $value ) {
1819 'name' => $this->mName
,
1820 'cols' => $this->getCols(),
1821 'rows' => $this->getRows(),
1822 ) +
$this->getTooltipAndAccessKey();
1824 if ( $this->mClass
!== '' ) {
1825 $attribs['class'] = $this->mClass
;
1828 if ( !empty( $this->mParams
['disabled'] ) ) {
1829 $attribs['disabled'] = 'disabled';
1832 if ( !empty( $this->mParams
['readonly'] ) ) {
1833 $attribs['readonly'] = 'readonly';
1836 if ( isset( $this->mParams
['placeholder'] ) ) {
1837 $attribs['placeholder'] = $this->mParams
['placeholder'];
1840 foreach ( array( 'required', 'autofocus' ) as $param ) {
1841 if ( isset( $this->mParams
[$param] ) ) {
1842 $attribs[$param] = '';
1846 return Html
::element( 'textarea', $attribs, $value );
1851 * A field that will contain a numeric value
1853 class HTMLFloatField
extends HTMLTextField
{
1854 function getSize() {
1855 return isset( $this->mParams
['size'] )
1856 ?
$this->mParams
['size']
1860 function validate( $value, $alldata ) {
1861 $p = parent
::validate( $value, $alldata );
1863 if ( $p !== true ) {
1867 $value = trim( $value );
1869 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1870 # with the addition that a leading '+' sign is ok.
1871 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1872 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1875 # The "int" part of these message names is rather confusing.
1876 # They make equal sense for all numbers.
1877 if ( isset( $this->mParams
['min'] ) ) {
1878 $min = $this->mParams
['min'];
1880 if ( $min > $value ) {
1881 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1885 if ( isset( $this->mParams
['max'] ) ) {
1886 $max = $this->mParams
['max'];
1888 if ( $max < $value ) {
1889 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1898 * A field that must contain a number
1900 class HTMLIntField
extends HTMLFloatField
{
1901 function validate( $value, $alldata ) {
1902 $p = parent
::validate( $value, $alldata );
1904 if ( $p !== true ) {
1908 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1909 # with the addition that a leading '+' sign is ok. Note that leading zeros
1910 # are fine, and will be left in the input, which is useful for things like
1911 # phone numbers when you know that they are integers (the HTML5 type=tel
1912 # input does not require its value to be numeric). If you want a tidier
1913 # value to, eg, save in the DB, clean it up with intval().
1914 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1916 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1926 class HTMLCheckField
extends HTMLFormField
{
1927 function getInputHTML( $value ) {
1928 if ( !empty( $this->mParams
['invert'] ) ) {
1932 $attr = $this->getTooltipAndAccessKey();
1933 $attr['id'] = $this->mID
;
1935 if ( !empty( $this->mParams
['disabled'] ) ) {
1936 $attr['disabled'] = 'disabled';
1939 if ( $this->mClass
!== '' ) {
1940 $attr['class'] = $this->mClass
;
1943 if ( $this->mParent
->isVForm() ) {
1944 // Nest checkbox inside label.
1945 return Html
::rawElement(
1948 'class' => 'mw-ui-checkbox-label'
1955 // Html:rawElement doesn't escape contents.
1956 htmlspecialchars( $this->mLabel
)
1959 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1960 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1965 * For a checkbox, the label goes on the right hand side, and is
1966 * added in getInputHTML(), rather than HTMLFormField::getRow()
1969 function getLabel() {
1974 * checkboxes don't need a label.
1976 protected function needsLabel() {
1981 * @param $request WebRequest
1984 function loadDataFromRequest( $request ) {
1986 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1990 // GetCheck won't work like we want for checks.
1991 // Fetch the value in either one of the two following case:
1992 // - we have a valid token (form got posted or GET forged by the user)
1993 // - checkbox name has a value (false or true), ie is not null
1994 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1995 // XOR has the following truth table, which is what we want
1996 // INVERT VALUE | OUTPUT
1997 // true true | false
1998 // false true | true
1999 // false false | false
2000 // true false | true
2001 return $request->getBool( $this->mName
) xor $invert;
2003 return $this->getDefault();
2010 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
2011 * options, uses an array of rows and an array of columns to dynamically
2012 * construct a matrix of options. The tags used to identify a particular cell
2013 * are of the form "columnName-rowName"
2017 * - Required list of columns in the matrix.
2019 * - Required list of rows in the matrix.
2020 * - force-options-on
2021 * - Accepts array of column-row tags to be displayed as enabled but unavailable to change
2022 * - force-options-off
2023 * - Accepts array of column-row tags to be displayed as disabled but unavailable to change.
2025 * - Optional array mapping row label to tooltip content
2027 * - Optional CSS class used on tooltip container span. Defaults to mw-icon-question.
2029 class HTMLCheckMatrix
extends HTMLFormField
implements HTMLNestedFilterable
{
2031 static private $requiredParams = array(
2032 // Required by underlying HTMLFormField
2034 // Required by HTMLCheckMatrix
2038 public function __construct( $params ) {
2039 $missing = array_diff( self
::$requiredParams, array_keys( $params ) );
2041 throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
2043 parent
::__construct( $params );
2046 function validate( $value, $alldata ) {
2047 $rows = $this->mParams
['rows'];
2048 $columns = $this->mParams
['columns'];
2050 // Make sure user-defined validation callback is run
2051 $p = parent
::validate( $value, $alldata );
2052 if ( $p !== true ) {
2056 // Make sure submitted value is an array
2057 if ( !is_array( $value ) ) {
2061 // If all options are valid, array_intersect of the valid options
2062 // and the provided options will return the provided options.
2063 $validOptions = array();
2064 foreach ( $rows as $rowTag ) {
2065 foreach ( $columns as $columnTag ) {
2066 $validOptions[] = $columnTag . '-' . $rowTag;
2069 $validValues = array_intersect( $value, $validOptions );
2070 if ( count( $validValues ) == count( $value ) ) {
2073 return $this->msg( 'htmlform-select-badoption' )->parse();
2078 * Build a table containing a matrix of checkbox options.
2079 * The value of each option is a combination of the row tag and column tag.
2080 * mParams['rows'] is an array with row labels as keys and row tags as values.
2081 * mParams['columns'] is an array with column labels as keys and column tags as values.
2082 * @param array $value of the options that should be checked
2085 function getInputHTML( $value ) {
2087 $tableContents = '';
2089 $rows = $this->mParams
['rows'];
2090 $columns = $this->mParams
['columns'];
2092 // If the disabled param is set, disable all the options
2093 if ( !empty( $this->mParams
['disabled'] ) ) {
2094 $attribs['disabled'] = 'disabled';
2097 // Build the column headers
2098 $headerContents = Html
::rawElement( 'td', array(), ' ' );
2099 foreach ( $columns as $columnLabel => $columnTag ) {
2100 $headerContents .= Html
::rawElement( 'td', array(), $columnLabel );
2102 $tableContents .= Html
::rawElement( 'tr', array(), "\n$headerContents\n" );
2104 $tooltipClass = 'mw-icon-question';
2105 if ( isset( $this->mParams
['tooltip-class'] ) ) {
2106 $tooltipClass = $this->mParams
['tooltip-class'];
2109 // Build the options matrix
2110 foreach ( $rows as $rowLabel => $rowTag ) {
2111 // Append tooltip if configured
2112 if ( isset( $this->mParams
['tooltips'][$rowLabel] ) ) {
2113 $tooltipAttribs = array(
2114 'class' => "mw-htmlform-tooltip $tooltipClass",
2115 'title' => $this->mParams
['tooltips'][$rowLabel],
2117 $rowLabel .= ' ' . Html
::element( 'span', $tooltipAttribs, '' );
2119 $rowContents = Html
::rawElement( 'td', array(), $rowLabel );
2120 foreach ( $columns as $columnTag ) {
2121 $thisTag = "$columnTag-$rowTag";
2122 // Construct the checkbox
2123 $thisAttribs = array(
2124 'id' => "{$this->mID}-$thisTag",
2125 'value' => $thisTag,
2127 $checked = in_array( $thisTag, (array)$value, true );
2128 if ( $this->isTagForcedOff( $thisTag ) ) {
2130 $thisAttribs['disabled'] = 1;
2131 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2133 $thisAttribs['disabled'] = 1;
2135 $rowContents .= Html
::rawElement(
2138 Xml
::check( "{$this->mName}[]", $checked, $attribs +
$thisAttribs )
2141 $tableContents .= Html
::rawElement( 'tr', array(), "\n$rowContents\n" );
2144 // Put it all in a table
2145 $html .= Html
::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
2146 Html
::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
2151 protected function isTagForcedOff( $tag ) {
2152 return isset( $this->mParams
['force-options-off'] )
2153 && in_array( $tag, $this->mParams
['force-options-off'] );
2156 protected function isTagForcedOn( $tag ) {
2157 return isset( $this->mParams
['force-options-on'] )
2158 && in_array( $tag, $this->mParams
['force-options-on'] );
2162 * Get the complete table row for the input, including help text,
2163 * labels, and whatever.
2164 * We override this function since the label should always be on a separate
2165 * line above the options in the case of a checkbox matrix, i.e. it's always
2166 * a "vertical-label".
2167 * @param string $value the value to set the input to
2168 * @return String complete HTML table row
2170 function getTableRow( $value ) {
2171 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
2172 $inputHtml = $this->getInputHTML( $value );
2173 $fieldType = get_class( $this );
2174 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
2175 $cellAttributes = array( 'colspan' => 2 );
2177 $label = $this->getLabelHtml( $cellAttributes );
2179 $field = Html
::rawElement(
2181 array( 'class' => 'mw-input' ) +
$cellAttributes,
2182 $inputHtml . "\n$errors"
2185 $html = Html
::rawElement( 'tr',
2186 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2187 $html .= Html
::rawElement( 'tr',
2188 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2191 return $html . $helptext;
2195 * @param $request WebRequest
2198 function loadDataFromRequest( $request ) {
2199 if ( $this->mParent
->getMethod() == 'post' ) {
2200 if ( $request->wasPosted() ) {
2201 // Checkboxes are not added to the request arrays if they're not checked,
2202 // so it's perfectly possible for there not to be an entry at all
2203 return $request->getArray( $this->mName
, array() );
2205 // That's ok, the user has not yet submitted the form, so show the defaults
2206 return $this->getDefault();
2209 // This is the impossible case: if we look at $_GET and see no data for our
2210 // field, is it because the user has not yet submitted the form, or that they
2211 // have submitted it with all the options unchecked. We will have to assume the
2212 // latter, which basically means that you can't specify 'positive' defaults
2214 return $request->getArray( $this->mName
, array() );
2218 function getDefault() {
2219 if ( isset( $this->mDefault
) ) {
2220 return $this->mDefault
;
2226 function filterDataForSubmit( $data ) {
2227 $columns = HTMLFormField
::flattenOptions( $this->mParams
['columns'] );
2228 $rows = HTMLFormField
::flattenOptions( $this->mParams
['rows'] );
2230 foreach ( $columns as $column ) {
2231 foreach ( $rows as $row ) {
2232 // Make sure option hasn't been forced
2233 $thisTag = "$column-$row";
2234 if ( $this->isTagForcedOff( $thisTag ) ) {
2235 $res[$thisTag] = false;
2236 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2237 $res[$thisTag] = true;
2239 $res[$thisTag] = in_array( $thisTag, $data );
2249 * A select dropdown field. Basically a wrapper for Xmlselect class
2251 class HTMLSelectField
extends HTMLFormField
{
2252 function validate( $value, $alldata ) {
2253 $p = parent
::validate( $value, $alldata );
2255 if ( $p !== true ) {
2259 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2261 if ( in_array( $value, $validOptions ) ) {
2264 return $this->msg( 'htmlform-select-badoption' )->parse();
2268 function getInputHTML( $value ) {
2269 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
2271 # If one of the options' 'name' is int(0), it is automatically selected.
2272 # because PHP sucks and thinks int(0) == 'some string'.
2273 # Working around this by forcing all of them to strings.
2274 foreach ( $this->mParams
['options'] as &$opt ) {
2275 if ( is_int( $opt ) ) {
2276 $opt = strval( $opt );
2279 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2281 if ( !empty( $this->mParams
['disabled'] ) ) {
2282 $select->setAttribute( 'disabled', 'disabled' );
2285 if ( $this->mClass
!== '' ) {
2286 $select->setAttribute( 'class', $this->mClass
);
2289 $select->addOptions( $this->mParams
['options'] );
2291 return $select->getHTML();
2296 * Select dropdown field, with an additional "other" textbox.
2298 class HTMLSelectOrOtherField
extends HTMLTextField
{
2300 function __construct( $params ) {
2301 if ( !in_array( 'other', $params['options'], true ) ) {
2302 $msg = isset( $params['other'] ) ?
2304 wfMessage( 'htmlform-selectorother-other' )->text();
2305 $params['options'][$msg] = 'other';
2308 parent
::__construct( $params );
2311 static function forceToStringRecursive( $array ) {
2312 if ( is_array( $array ) ) {
2313 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
2315 return strval( $array );
2319 function getInputHTML( $value ) {
2320 $valInSelect = false;
2322 if ( $value !== false ) {
2323 $valInSelect = in_array(
2325 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
2329 $selected = $valInSelect ?
$value : 'other';
2331 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
2333 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
2334 $select->addOptions( $opts );
2336 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2338 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
2340 if ( !empty( $this->mParams
['disabled'] ) ) {
2341 $select->setAttribute( 'disabled', 'disabled' );
2342 $tbAttribs['disabled'] = 'disabled';
2345 $select = $select->getHTML();
2347 if ( isset( $this->mParams
['maxlength'] ) ) {
2348 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
2351 if ( $this->mClass
!== '' ) {
2352 $tbAttribs['class'] = $this->mClass
;
2355 $textbox = Html
::input(
2356 $this->mName
. '-other',
2357 $valInSelect ?
'' : $value,
2362 return "$select<br />\n$textbox";
2366 * @param $request WebRequest
2369 function loadDataFromRequest( $request ) {
2370 if ( $request->getCheck( $this->mName
) ) {
2371 $val = $request->getText( $this->mName
);
2373 if ( $val == 'other' ) {
2374 $val = $request->getText( $this->mName
. '-other' );
2379 return $this->getDefault();
2385 * Multi-select field
2387 class HTMLMultiSelectField
extends HTMLFormField
implements HTMLNestedFilterable
{
2389 function validate( $value, $alldata ) {
2390 $p = parent
::validate( $value, $alldata );
2392 if ( $p !== true ) {
2396 if ( !is_array( $value ) ) {
2400 # If all options are valid, array_intersect of the valid options
2401 # and the provided options will return the provided options.
2402 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2404 $validValues = array_intersect( $value, $validOptions );
2405 if ( count( $validValues ) == count( $value ) ) {
2408 return $this->msg( 'htmlform-select-badoption' )->parse();
2412 function getInputHTML( $value ) {
2413 $html = $this->formatOptions( $this->mParams
['options'], $value );
2418 function formatOptions( $options, $value ) {
2423 if ( !empty( $this->mParams
['disabled'] ) ) {
2424 $attribs['disabled'] = 'disabled';
2427 foreach ( $options as $label => $info ) {
2428 if ( is_array( $info ) ) {
2429 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2430 $html .= $this->formatOptions( $info, $value );
2432 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2434 $checkbox = Xml
::check(
2435 $this->mName
. '[]',
2436 in_array( $info, $value, true ),
2437 $attribs +
$thisAttribs );
2438 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2440 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2448 * @param $request WebRequest
2451 function loadDataFromRequest( $request ) {
2452 if ( $this->mParent
->getMethod() == 'post' ) {
2453 if ( $request->wasPosted() ) {
2454 # Checkboxes are just not added to the request arrays if they're not checked,
2455 # so it's perfectly possible for there not to be an entry at all
2456 return $request->getArray( $this->mName
, array() );
2458 # That's ok, the user has not yet submitted the form, so show the defaults
2459 return $this->getDefault();
2462 # This is the impossible case: if we look at $_GET and see no data for our
2463 # field, is it because the user has not yet submitted the form, or that they
2464 # have submitted it with all the options unchecked? We will have to assume the
2465 # latter, which basically means that you can't specify 'positive' defaults
2468 return $request->getArray( $this->mName
, array() );
2472 function getDefault() {
2473 if ( isset( $this->mDefault
) ) {
2474 return $this->mDefault
;
2480 function filterDataForSubmit( $data ) {
2481 $options = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2484 foreach ( $options as $opt ) {
2485 $res["$opt"] = in_array( $opt, $data );
2491 protected function needsLabel() {
2497 * Double field with a dropdown list constructed from a system message in the format
2500 * * New Optgroup header
2501 * Plus a text field underneath for an additional reason. The 'value' of the field is
2502 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2504 * @todo FIXME: If made 'required', only the text field should be compulsory.
2506 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2508 function __construct( $params ) {
2509 if ( array_key_exists( 'other', $params ) ) {
2510 } elseif ( array_key_exists( 'other-message', $params ) ) {
2511 $params['other'] = wfMessage( $params['other-message'] )->plain();
2513 $params['other'] = null;
2516 if ( array_key_exists( 'options', $params ) ) {
2517 # Options array already specified
2518 } elseif ( array_key_exists( 'options-message', $params ) ) {
2519 # Generate options array from a system message
2520 $params['options'] = self
::parseMessage(
2521 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2526 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2528 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2530 parent
::__construct( $params );
2534 * Build a drop-down box from a textual list.
2535 * @param string $string message text
2536 * @param string $otherName name of "other reason" option
2538 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2540 public static function parseMessage( $string, $otherName = null ) {
2541 if ( $otherName === null ) {
2542 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2546 $options = array( $otherName => 'other' );
2548 foreach ( explode( "\n", $string ) as $option ) {
2549 $value = trim( $option );
2550 if ( $value == '' ) {
2552 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2553 # A new group is starting...
2554 $value = trim( substr( $value, 1 ) );
2556 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2558 $opt = trim( substr( $value, 2 ) );
2559 if ( $optgroup === false ) {
2560 $options[$opt] = $opt;
2562 $options[$optgroup][$opt] = $opt;
2565 # groupless reason list
2567 $options[$option] = $option;
2574 function getInputHTML( $value ) {
2575 $select = parent
::getInputHTML( $value[1] );
2577 $textAttribs = array(
2578 'id' => $this->mID
. '-other',
2579 'size' => $this->getSize(),
2582 if ( $this->mClass
!== '' ) {
2583 $textAttribs['class'] = $this->mClass
;
2586 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2587 if ( isset( $this->mParams
[$param] ) ) {
2588 $textAttribs[$param] = '';
2592 $textbox = Html
::input(
2593 $this->mName
. '-other',
2599 return "$select<br />\n$textbox";
2603 * @param $request WebRequest
2604 * @return Array("<overall message>","<select value>","<text field value>")
2606 function loadDataFromRequest( $request ) {
2607 if ( $request->getCheck( $this->mName
) ) {
2609 $list = $request->getText( $this->mName
);
2610 $text = $request->getText( $this->mName
. '-other' );
2612 if ( $list == 'other' ) {
2614 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2615 # User has spoofed the select form to give an option which wasn't
2616 # in the original offer. Sulk...
2618 } elseif ( $text == '' ) {
2621 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2625 $final = $this->getDefault();
2629 foreach ( $this->mFlatOptions
as $option ) {
2630 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2631 if ( strpos( $text, $match ) === 0 ) {
2633 $text = substr( $text, strlen( $match ) );
2638 return array( $final, $list, $text );
2641 function getSize() {
2642 return isset( $this->mParams
['size'] )
2643 ?
$this->mParams
['size']
2647 function validate( $value, $alldata ) {
2648 # HTMLSelectField forces $value to be one of the options in the select
2649 # field, which is not useful here. But we do want the validation further up
2651 $p = parent
::validate( $value[1], $alldata );
2653 if ( $p !== true ) {
2657 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value[1] === '' ) {
2658 return $this->msg( 'htmlform-required' )->parse();
2666 * Radio checkbox fields.
2668 class HTMLRadioField
extends HTMLFormField
{
2670 function validate( $value, $alldata ) {
2671 $p = parent
::validate( $value, $alldata );
2673 if ( $p !== true ) {
2677 if ( !is_string( $value ) && !is_int( $value ) ) {
2681 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2683 if ( in_array( $value, $validOptions ) ) {
2686 return $this->msg( 'htmlform-select-badoption' )->parse();
2691 * This returns a block of all the radio options, in one cell.
2692 * @see includes/HTMLFormField#getInputHTML()
2693 * @param $value String
2696 function getInputHTML( $value ) {
2697 $html = $this->formatOptions( $this->mParams
['options'], $value );
2702 function formatOptions( $options, $value ) {
2706 if ( !empty( $this->mParams
['disabled'] ) ) {
2707 $attribs['disabled'] = 'disabled';
2710 # TODO: should this produce an unordered list perhaps?
2711 foreach ( $options as $label => $info ) {
2712 if ( is_array( $info ) ) {
2713 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2714 $html .= $this->formatOptions( $info, $value );
2716 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2717 $radio = Xml
::radio(
2721 $attribs +
array( 'id' => $id )
2723 $radio .= ' ' .
2724 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2726 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2733 protected function needsLabel() {
2739 * An information field (text blob), not a proper input.
2741 class HTMLInfoField
extends HTMLFormField
{
2742 public function __construct( $info ) {
2743 $info['nodata'] = true;
2745 parent
::__construct( $info );
2748 public function getInputHTML( $value ) {
2749 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2752 public function getTableRow( $value ) {
2753 if ( !empty( $this->mParams
['rawrow'] ) ) {
2757 return parent
::getTableRow( $value );
2763 public function getDiv( $value ) {
2764 if ( !empty( $this->mParams
['rawrow'] ) ) {
2768 return parent
::getDiv( $value );
2774 public function getRaw( $value ) {
2775 if ( !empty( $this->mParams
['rawrow'] ) ) {
2779 return parent
::getRaw( $value );
2782 protected function needsLabel() {
2787 class HTMLHiddenField
extends HTMLFormField
{
2788 public function __construct( $params ) {
2789 parent
::__construct( $params );
2791 # Per HTML5 spec, hidden fields cannot be 'required'
2792 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2793 unset( $this->mParams
['required'] );
2796 public function getTableRow( $value ) {
2799 $params['id'] = $this->mID
;
2802 $this->mParent
->addHiddenField(
2814 public function getDiv( $value ) {
2815 return $this->getTableRow( $value );
2821 public function getRaw( $value ) {
2822 return $this->getTableRow( $value );
2825 public function getInputHTML( $value ) {
2831 * Add a submit button inline in the form (as opposed to
2832 * HTMLForm::addButton(), which will add it at the end).
2834 class HTMLSubmitField
extends HTMLButtonField
{
2835 protected $buttonType = 'submit';
2839 * Adds a generic button inline to the form. Does not do anything, you must add
2840 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2841 * wish to add a submit button to a form.
2845 class HTMLButtonField
extends HTMLFormField
{
2846 protected $buttonType = 'button';
2848 public function __construct( $info ) {
2849 $info['nodata'] = true;
2850 parent
::__construct( $info );
2853 public function getInputHTML( $value ) {
2855 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2859 if ( !empty( $this->mParams
['disabled'] ) ) {
2860 $attr['disabled'] = 'disabled';
2871 protected function needsLabel() {
2876 * Button cannot be invalid
2877 * @param $value String
2878 * @param $alldata Array
2881 public function validate( $value, $alldata ) {
2886 class HTMLEditTools
extends HTMLFormField
{
2887 public function getInputHTML( $value ) {
2891 public function getTableRow( $value ) {
2892 $msg = $this->formatMsg();
2894 return '<tr><td></td><td class="mw-input">'
2895 . '<div class="mw-editTools">'
2896 . $msg->parseAsBlock()
2897 . "</div></td></tr>\n";
2903 public function getDiv( $value ) {
2904 $msg = $this->formatMsg();
2905 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2911 public function getRaw( $value ) {
2912 return $this->getDiv( $value );
2915 protected function formatMsg() {
2916 if ( empty( $this->mParams
['message'] ) ) {
2917 $msg = $this->msg( 'edittools' );
2919 $msg = $this->msg( $this->mParams
['message'] );
2920 if ( $msg->isDisabled() ) {
2921 $msg = $this->msg( 'edittools' );
2924 $msg->inContentLanguage();
2929 class HTMLApiField
extends HTMLFormField
{
2930 public function getTableRow( $value ) {
2934 public function getDiv( $value ) {
2935 return $this->getTableRow( $value );
2938 public function getRaw( $value ) {
2939 return $this->getTableRow( $value );
2942 public function getInputHTML( $value ) {
2947 interface HTMLNestedFilterable
{
2949 * Support for seperating multi-option preferences into multiple preferences
2950 * Due to lack of array support.
2951 * @param $data array
2953 function filterDataForSubmit( $data );
2956 class HTMLFormFieldRequiredOptionsException
extends MWException
{
2957 public function __construct( HTMLFormField
$field, array $missing ) {
2958 parent
::__construct( sprintf(
2959 "Form type `%s` expected the following parameters to be set: %s",
2960 get_class( $field ),
2961 implode( ', ', $missing )