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' )
90 * Note that you will have prepareForm and displayForm at the end. Other
91 * methods call done after that would simply not be part of the form :(
93 * TODO: Document 'section' / 'subsection' stuff
95 class HTMLForm
extends ContextSource
{
97 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
98 static $typeMappings = array(
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',
115 // HTMLTextField will output the correct type="" attribute automagically.
116 // There are about four zillion other HTML5 input types, like url, but
117 // we don't use those at the moment, so no point in adding all of them.
118 'email' => 'HTMLTextField',
119 'password' => 'HTMLTextField',
122 protected $mMessagePrefix;
124 /** @var HTMLFormField[] */
125 protected $mFlatFields;
127 protected $mFieldTree;
128 protected $mShowReset = false;
131 protected $mSubmitCallback;
132 protected $mValidationErrorMessage;
134 protected $mPre = '';
135 protected $mHeader = '';
136 protected $mFooter = '';
137 protected $mSectionHeaders = array();
138 protected $mSectionFooters = array();
139 protected $mPost = '';
142 protected $mSubmitID;
143 protected $mSubmitName;
144 protected $mSubmitText;
145 protected $mSubmitTooltip;
148 protected $mMethod = 'post';
151 * Form action URL. false means we will use the URL to set Title
155 protected $mAction = false;
157 protected $mUseMultipart = false;
158 protected $mHiddenFields = array();
159 protected $mButtons = array();
161 protected $mWrapperLegend = false;
164 * If true, sections that contain both fields and subsections will
165 * render their subsections before their fields.
167 * Subclasses may set this to false to render subsections after fields
170 protected $mSubSectionBeforeFields = true;
173 * Format in which to display form. For viable options,
174 * @see $availableDisplayFormats
177 protected $displayFormat = 'table';
180 * Available formats in which to display the form
183 protected $availableDisplayFormats = array(
190 * Build a new HTMLForm from an array of field attributes
191 * @param $descriptor Array of Field constructs, as described above
192 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
193 * Obviates the need to call $form->setTitle()
194 * @param $messagePrefix String a prefix to go in front of default messages
196 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
197 if ( $context instanceof IContextSource
) {
198 $this->setContext( $context );
199 $this->mTitle
= false; // We don't need them to set a title
200 $this->mMessagePrefix
= $messagePrefix;
203 if ( is_string( $context ) && $messagePrefix === '' ) {
204 // it's actually $messagePrefix
205 $this->mMessagePrefix
= $context;
209 // Expand out into a tree.
210 $loadedDescriptor = array();
211 $this->mFlatFields
= array();
213 foreach ( $descriptor as $fieldname => $info ) {
214 $section = isset( $info['section'] )
218 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
219 $this->mUseMultipart
= true;
222 $field = self
::loadInputFromParameters( $fieldname, $info );
223 $field->mParent
= $this;
225 $setSection =& $loadedDescriptor;
227 $sectionParts = explode( '/', $section );
229 while ( count( $sectionParts ) ) {
230 $newName = array_shift( $sectionParts );
232 if ( !isset( $setSection[$newName] ) ) {
233 $setSection[$newName] = array();
236 $setSection =& $setSection[$newName];
240 $setSection[$fieldname] = $field;
241 $this->mFlatFields
[$fieldname] = $field;
244 $this->mFieldTree
= $loadedDescriptor;
248 * Set format in which to display the form
249 * @param $format String the name of the format to use, must be one of
250 * $this->availableDisplayFormats
252 * @return HTMLForm $this for chaining calls (since 1.20)
254 public function setDisplayFormat( $format ) {
255 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
256 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats
, true ) );
258 $this->displayFormat
= $format;
263 * Getter for displayFormat
267 public function getDisplayFormat() {
268 return $this->displayFormat
;
272 * Add the HTMLForm-specific JavaScript, if it hasn't been
274 * @deprecated since 1.18 load modules with ResourceLoader instead
276 static function addJS() { wfDeprecated( __METHOD__
, '1.18' ); }
279 * Initialise a new Object for the field
280 * @param $fieldname string
281 * @param $descriptor string input Descriptor, as described above
282 * @return HTMLFormField subclass
284 static function loadInputFromParameters( $fieldname, $descriptor ) {
285 if ( isset( $descriptor['class'] ) ) {
286 $class = $descriptor['class'];
287 } elseif ( isset( $descriptor['type'] ) ) {
288 $class = self
::$typeMappings[$descriptor['type']];
289 $descriptor['class'] = $class;
295 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
298 $descriptor['fieldname'] = $fieldname;
301 # This will throw a fatal error whenever someone try to use
302 # 'class' to feed a CSS class instead of 'cssclass'. Would be
303 # great to avoid the fatal error and show a nice error.
304 $obj = new $class( $descriptor );
310 * Prepare form for submission.
312 * @attention When doing method chaining, that should be the very last
313 * method call before displayForm().
315 * @return HTMLForm $this for chaining calls (since 1.20)
317 function prepareForm() {
318 # Check if we have the info we need
319 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
320 throw new MWException( "You must call setTitle() on an HTMLForm" );
323 # Load data from the request.
329 * Try submitting, with edit token check first
330 * @return Status|boolean
332 function tryAuthorizedSubmit() {
336 if ( $this->getMethod() != 'post' ) {
337 $submit = true; // no session check needed
338 } elseif ( $this->getRequest()->wasPosted() ) {
339 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
340 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
341 // Session tokens for logged-out users have no security value.
342 // However, if the user gave one, check it in order to give a nice
343 // "session expired" error instead of "permission denied" or such.
344 $submit = $this->getUser()->matchEditToken( $editToken );
351 $result = $this->trySubmit();
358 * The here's-one-I-made-earlier option: do the submission if
359 * posted, or display the form with or without funky validation
361 * @return Bool or Status whether submission was successful.
364 $this->prepareForm();
366 $result = $this->tryAuthorizedSubmit();
367 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
371 $this->displayForm( $result );
376 * Validate all the fields, and call the submision callback
377 * function if everything is kosher.
378 * @return Mixed Bool true == Successful submission, Bool false
379 * == No submission attempted, anything else == Error to
382 function trySubmit() {
383 # Check for validation
384 foreach ( $this->mFlatFields
as $fieldname => $field ) {
385 if ( !empty( $field->mParams
['nodata'] ) ) {
388 if ( $field->validate(
389 $this->mFieldData
[$fieldname],
393 return isset( $this->mValidationErrorMessage
)
394 ?
$this->mValidationErrorMessage
395 : array( 'htmlform-invalid-input' );
399 $callback = $this->mSubmitCallback
;
400 if ( !is_callable( $callback ) ) {
401 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
404 $data = $this->filterDataForSubmit( $this->mFieldData
);
406 $res = call_user_func( $callback, $data, $this );
412 * Set a callback to a function to do something with the form
413 * once it's been successfully validated.
414 * @param $cb String function name. The function will be passed
415 * the output from HTMLForm::filterDataForSubmit, and must
416 * return Bool true on success, Bool false if no submission
417 * was attempted, or String HTML output to display on error.
418 * @return HTMLForm $this for chaining calls (since 1.20)
420 function setSubmitCallback( $cb ) {
421 $this->mSubmitCallback
= $cb;
426 * Set a message to display on a validation error.
427 * @param $msg Mixed String or Array of valid inputs to wfMessage()
428 * (so each entry can be either a String or Array)
429 * @return HTMLForm $this for chaining calls (since 1.20)
431 function setValidationErrorMessage( $msg ) {
432 $this->mValidationErrorMessage
= $msg;
437 * Set the introductory message, overwriting any existing message.
438 * @param $msg String complete text of message to display
439 * @return HTMLForm $this for chaining calls (since 1.20)
441 function setIntro( $msg ) {
442 $this->setPreText( $msg );
447 * Set the introductory message, overwriting any existing message.
449 * @param $msg String complete text of message to display
450 * @return HTMLForm $this for chaining calls (since 1.20)
452 function setPreText( $msg ) {
458 * Add introductory text.
459 * @param $msg String complete text of message to display
460 * @return HTMLForm $this for chaining calls (since 1.20)
462 function addPreText( $msg ) {
468 * Add header text, inside the form.
469 * @param $msg String complete text of message to display
470 * @param $section string The section to add the header to
471 * @return HTMLForm $this for chaining calls (since 1.20)
473 function addHeaderText( $msg, $section = null ) {
474 if ( is_null( $section ) ) {
475 $this->mHeader
.= $msg;
477 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
478 $this->mSectionHeaders
[$section] = '';
480 $this->mSectionHeaders
[$section] .= $msg;
486 * Set header text, inside the form.
488 * @param $msg String complete text of message to display
489 * @param $section The section to add the header to
490 * @return HTMLForm $this for chaining calls (since 1.20)
492 function setHeaderText( $msg, $section = null ) {
493 if ( is_null( $section ) ) {
494 $this->mHeader
= $msg;
496 $this->mSectionHeaders
[$section] = $msg;
502 * Add footer text, inside the form.
503 * @param $msg String complete text of message to display
504 * @param $section string The section to add the footer text to
505 * @return HTMLForm $this for chaining calls (since 1.20)
507 function addFooterText( $msg, $section = null ) {
508 if ( is_null( $section ) ) {
509 $this->mFooter
.= $msg;
511 if ( !isset( $this->mSectionFooters
[$section] ) ) {
512 $this->mSectionFooters
[$section] = '';
514 $this->mSectionFooters
[$section] .= $msg;
520 * Set footer text, inside the form.
522 * @param $msg String complete text of message to display
523 * @param $section string The section to add the footer text to
524 * @return HTMLForm $this for chaining calls (since 1.20)
526 function setFooterText( $msg, $section = null ) {
527 if ( is_null( $section ) ) {
528 $this->mFooter
= $msg;
530 $this->mSectionFooters
[$section] = $msg;
536 * Add text to the end of the display.
537 * @param $msg String complete text of message to display
538 * @return HTMLForm $this for chaining calls (since 1.20)
540 function addPostText( $msg ) {
541 $this->mPost
.= $msg;
546 * Set text at the end of the display.
547 * @param $msg String complete text of message to display
548 * @return HTMLForm $this for chaining calls (since 1.20)
550 function setPostText( $msg ) {
556 * Add a hidden field to the output
557 * @param $name String field name. This will be used exactly as entered
558 * @param $value String field value
559 * @param $attribs Array
560 * @return HTMLForm $this for chaining calls (since 1.20)
562 public function addHiddenField( $name, $value, $attribs = array() ) {
563 $attribs +
= array( 'name' => $name );
564 $this->mHiddenFields
[] = array( $value, $attribs );
569 * Add a button to the form
570 * @param $name String field name.
571 * @param $value String field value
572 * @param $id String DOM id for the button (default: null)
573 * @param $attribs Array
574 * @return HTMLForm $this for chaining calls (since 1.20)
576 public function addButton( $name, $value, $id = null, $attribs = null ) {
577 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
582 * Display the form (sending to $wgOut), with an appropriate error
583 * message or stack of messages, and any validation errors, etc.
585 * @attention You should call prepareForm() before calling this function.
586 * Moreover, when doing method chaining this should be the very last method
587 * call just after prepareForm().
589 * @param $submitResult Mixed output from HTMLForm::trySubmit()
590 * @return Nothing, should be last call
592 function displayForm( $submitResult ) {
593 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
597 * Returns the raw HTML generated by the form
598 * @param $submitResult Mixed output from HTMLForm::trySubmit()
601 function getHTML( $submitResult ) {
602 # For good measure (it is the default)
603 $this->getOutput()->preventClickjacking();
604 $this->getOutput()->addModules( 'mediawiki.htmlform' );
607 . $this->getErrors( $submitResult )
610 . $this->getHiddenFields()
611 . $this->getButtons()
615 $html = $this->wrapForm( $html );
617 return '' . $this->mPre
. $html . $this->mPost
;
621 * Wrap the form innards in an actual "<form>" element
622 * @param $html String HTML contents to wrap.
623 * @return String wrapped HTML.
625 function wrapForm( $html ) {
627 # Include a <fieldset> wrapper for style, if requested.
628 if ( $this->mWrapperLegend
!== false ) {
629 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
631 # Use multipart/form-data
632 $encType = $this->mUseMultipart
633 ?
'multipart/form-data'
634 : 'application/x-www-form-urlencoded';
637 'action' => $this->mAction
=== false ?
$this->getTitle()->getFullURL() : $this->mAction
,
638 'method' => $this->mMethod
,
639 'class' => 'visualClear',
640 'enctype' => $encType,
642 if ( !empty( $this->mId
) ) {
643 $attribs['id'] = $this->mId
;
646 return Html
::rawElement( 'form', $attribs, $html );
650 * Get the hidden fields that should go inside the form.
651 * @return String HTML.
653 function getHiddenFields() {
654 global $wgArticlePath;
657 if ( $this->getMethod() == 'post' ) {
658 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
659 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
662 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
663 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
666 foreach ( $this->mHiddenFields
as $data ) {
667 list( $value, $attribs ) = $data;
668 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
675 * Get the submit and (potentially) reset buttons.
676 * @return String HTML.
678 function getButtons() {
682 if ( isset( $this->mSubmitID
) ) {
683 $attribs['id'] = $this->mSubmitID
;
686 if ( isset( $this->mSubmitName
) ) {
687 $attribs['name'] = $this->mSubmitName
;
690 if ( isset( $this->mSubmitTooltip
) ) {
691 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
694 $attribs['class'] = 'mw-htmlform-submit';
696 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
698 if ( $this->mShowReset
) {
699 $html .= Html
::element(
703 'value' => $this->msg( 'htmlform-reset' )->text()
708 foreach ( $this->mButtons
as $button ) {
711 'name' => $button['name'],
712 'value' => $button['value']
715 if ( $button['attribs'] ) {
716 $attrs +
= $button['attribs'];
719 if ( isset( $button['id'] ) ) {
720 $attrs['id'] = $button['id'];
723 $html .= Html
::element( 'input', $attrs );
730 * Get the whole body of the form.
734 return $this->displaySection( $this->mFieldTree
);
738 * Format and display an error message stack.
739 * @param $errors String|Array|Status
742 function getErrors( $errors ) {
743 if ( $errors instanceof Status
) {
744 if ( $errors->isOK() ) {
747 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
749 } elseif ( is_array( $errors ) ) {
750 $errorstr = $this->formatErrors( $errors );
756 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
761 * Format a stack of error messages into a single HTML string
762 * @param $errors Array of message keys/values
763 * @return String HTML, a "<ul>" list of errors
765 public static function formatErrors( $errors ) {
768 foreach ( $errors as $error ) {
769 if ( is_array( $error ) ) {
770 $msg = array_shift( $error );
776 $errorstr .= Html
::rawElement(
779 wfMessage( $msg, $error )->parse()
783 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
789 * Set the text for the submit button
790 * @param $t String plaintext.
791 * @return HTMLForm $this for chaining calls (since 1.20)
793 function setSubmitText( $t ) {
794 $this->mSubmitText
= $t;
799 * Set the text for the submit button to a message
801 * @param $msg String message key
802 * @return HTMLForm $this for chaining calls (since 1.20)
804 public function setSubmitTextMsg( $msg ) {
805 $this->setSubmitText( $this->msg( $msg )->text() );
810 * Get the text for the submit button, either customised or a default.
813 function getSubmitText() {
814 return $this->mSubmitText
816 : $this->msg( 'htmlform-submit' )->text();
820 * @param $name String Submit button name
821 * @return HTMLForm $this for chaining calls (since 1.20)
823 public function setSubmitName( $name ) {
824 $this->mSubmitName
= $name;
829 * @param $name String Tooltip for the submit button
830 * @return HTMLForm $this for chaining calls (since 1.20)
832 public function setSubmitTooltip( $name ) {
833 $this->mSubmitTooltip
= $name;
838 * Set the id for the submit button.
840 * @todo FIXME: Integrity of $t is *not* validated
841 * @return HTMLForm $this for chaining calls (since 1.20)
843 function setSubmitID( $t ) {
844 $this->mSubmitID
= $t;
849 * @param $id String DOM id for the form
850 * @return HTMLForm $this for chaining calls (since 1.20)
852 public function setId( $id ) {
857 * Prompt the whole form to be wrapped in a "<fieldset>", with
858 * this text as its "<legend>" element.
859 * @param $legend String HTML to go inside the "<legend>" element.
861 * @return HTMLForm $this for chaining calls (since 1.20)
863 public function setWrapperLegend( $legend ) {
864 $this->mWrapperLegend
= $legend;
869 * Prompt the whole form to be wrapped in a "<fieldset>", with
870 * this message as its "<legend>" element.
872 * @param $msg String message key
873 * @return HTMLForm $this for chaining calls (since 1.20)
875 public function setWrapperLegendMsg( $msg ) {
876 $this->setWrapperLegend( $this->msg( $msg )->text() );
881 * Set the prefix for various default messages
882 * @todo currently only used for the "<fieldset>" legend on forms
883 * with multiple sections; should be used elsewhre?
885 * @return HTMLForm $this for chaining calls (since 1.20)
887 function setMessagePrefix( $p ) {
888 $this->mMessagePrefix
= $p;
893 * Set the title for form submission
894 * @param $t Title of page the form is on/should be posted to
895 * @return HTMLForm $this for chaining calls (since 1.20)
897 function setTitle( $t ) {
906 function getTitle() {
907 return $this->mTitle
=== false
908 ?
$this->getContext()->getTitle()
913 * Set the method used to submit the form
914 * @param $method String
915 * @return HTMLForm $this for chaining calls (since 1.20)
917 public function setMethod( $method = 'post' ) {
918 $this->mMethod
= $method;
922 public function getMethod() {
923 return $this->mMethod
;
928 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
929 * @param $sectionName string ID attribute of the "<table>" tag for this section, ignored if empty
930 * @param $fieldsetIDPrefix string ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
933 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
934 $displayFormat = $this->getDisplayFormat();
937 $subsectionHtml = '';
940 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ?
'getTableRow' : 'get' . ucfirst( $displayFormat );
942 foreach ( $fields as $key => $value ) {
943 if ( $value instanceof HTMLFormField
) {
944 $v = empty( $value->mParams
['nodata'] )
945 ?
$this->mFieldData
[$key]
946 : $value->getDefault();
947 $html .= $value->$getFieldHtmlMethod( $v );
949 $labelValue = trim( $value->getLabel() );
950 if ( $labelValue != ' ' && $labelValue !== '' ) {
953 } elseif ( is_array( $value ) ) {
954 $section = $this->displaySection( $value, $key );
955 $legend = $this->getLegend( $key );
956 if ( isset( $this->mSectionHeaders
[$key] ) ) {
957 $section = $this->mSectionHeaders
[$key] . $section;
959 if ( isset( $this->mSectionFooters
[$key] ) ) {
960 $section .= $this->mSectionFooters
[$key];
962 $attributes = array();
963 if ( $fieldsetIDPrefix ) {
964 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
966 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
970 if ( $displayFormat !== 'raw' ) {
973 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
974 $classes[] = 'mw-htmlform-nolabel';
978 'class' => implode( ' ', $classes ),
981 if ( $sectionName ) {
982 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
985 if ( $displayFormat === 'table' ) {
986 $html = Html
::rawElement( 'table', $attribs,
987 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
988 } elseif ( $displayFormat === 'div' ) {
989 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
993 if ( $this->mSubSectionBeforeFields
) {
994 return $subsectionHtml . "\n" . $html;
996 return $html . "\n" . $subsectionHtml;
1001 * Construct the form fields from the Descriptor array
1003 function loadData() {
1004 $fieldData = array();
1006 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1007 if ( !empty( $field->mParams
['nodata'] ) ) {
1009 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1010 $fieldData[$fieldname] = $field->getDefault();
1012 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1017 foreach ( $fieldData as $name => &$value ) {
1018 $field = $this->mFlatFields
[$name];
1019 $value = $field->filter( $value, $this->mFlatFields
);
1022 $this->mFieldData
= $fieldData;
1026 * Stop a reset button being shown for this form
1027 * @param $suppressReset Bool set to false to re-enable the
1029 * @return HTMLForm $this for chaining calls (since 1.20)
1031 function suppressReset( $suppressReset = true ) {
1032 $this->mShowReset
= !$suppressReset;
1037 * Overload this if you want to apply special filtration routines
1038 * to the form as a whole, after it's submitted but before it's
1043 function filterDataForSubmit( $data ) {
1048 * Get a string to go in the "<legend>" of a section fieldset.
1049 * Override this if you want something more complicated.
1050 * @param $key String
1053 public function getLegend( $key ) {
1054 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1058 * Set the value for the action attribute of the form.
1059 * When set to false (which is the default state), the set title is used.
1063 * @param string|bool $action
1064 * @return HTMLForm $this for chaining calls (since 1.20)
1066 public function setAction( $action ) {
1067 $this->mAction
= $action;
1074 * The parent class to generate form fields. Any field type should
1075 * be a subclass of this.
1077 abstract class HTMLFormField
{
1079 protected $mValidationCallback;
1080 protected $mFilterCallback;
1083 protected $mLabel; # String label. Set on construction
1085 protected $mClass = '';
1086 protected $mDefault;
1094 * This function must be implemented to return the HTML to generate
1095 * the input object itself. It should not implement the surrounding
1096 * table cells/rows, or labels/help messages.
1097 * @param $value String the value to set the input to; eg a default
1098 * text for a text input.
1099 * @return String valid HTML.
1101 abstract function getInputHTML( $value );
1104 * Get a translated interface message
1106 * This is a wrapper arround $this->mParent->msg() if $this->mParent is set
1107 * and wfMessage() otherwise.
1109 * Parameters are the same as wfMessage().
1111 * @return Message object
1114 $args = func_get_args();
1116 if ( $this->mParent
) {
1117 $callback = array( $this->mParent
, 'msg' );
1119 $callback = 'wfMessage';
1122 return call_user_func_array( $callback, $args );
1126 * Override this function to add specific validation checks on the
1127 * field input. Don't forget to call parent::validate() to ensure
1128 * that the user-defined callback mValidationCallback is still run
1129 * @param $value String the value the field was submitted with
1130 * @param $alldata Array the data collected from the form
1131 * @return Mixed Bool true on success, or String error to display.
1133 function validate( $value, $alldata ) {
1134 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value === '' ) {
1135 return $this->msg( 'htmlform-required' )->parse();
1138 if ( isset( $this->mValidationCallback
) ) {
1139 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
1145 function filter( $value, $alldata ) {
1146 if ( isset( $this->mFilterCallback
) ) {
1147 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
1154 * Should this field have a label, or is there no input element with the
1155 * appropriate id for the label to point to?
1157 * @return bool True to output a label, false to suppress
1159 protected function needsLabel() {
1164 * Get the value that this input has been set to from a posted form,
1165 * or the input's default value if it has not been set.
1166 * @param $request WebRequest
1167 * @return String the value
1169 function loadDataFromRequest( $request ) {
1170 if ( $request->getCheck( $this->mName
) ) {
1171 return $request->getText( $this->mName
);
1173 return $this->getDefault();
1178 * Initialise the object
1179 * @param $params array Associative Array. See HTMLForm doc for syntax.
1181 function __construct( $params ) {
1182 $this->mParams
= $params;
1184 # Generate the label from a message, if possible
1185 if ( isset( $params['label-message'] ) ) {
1186 $msgInfo = $params['label-message'];
1188 if ( is_array( $msgInfo ) ) {
1189 $msg = array_shift( $msgInfo );
1195 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
1196 } elseif ( isset( $params['label'] ) ) {
1197 $this->mLabel
= $params['label'];
1200 $this->mName
= "wp{$params['fieldname']}";
1201 if ( isset( $params['name'] ) ) {
1202 $this->mName
= $params['name'];
1205 $validName = Sanitizer
::escapeId( $this->mName
);
1206 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1207 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1210 $this->mID
= "mw-input-{$this->mName}";
1212 if ( isset( $params['default'] ) ) {
1213 $this->mDefault
= $params['default'];
1216 if ( isset( $params['id'] ) ) {
1217 $id = $params['id'];
1218 $validId = Sanitizer
::escapeId( $id );
1220 if ( $id != $validId ) {
1221 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1227 if ( isset( $params['cssclass'] ) ) {
1228 $this->mClass
= $params['cssclass'];
1231 if ( isset( $params['validation-callback'] ) ) {
1232 $this->mValidationCallback
= $params['validation-callback'];
1235 if ( isset( $params['filter-callback'] ) ) {
1236 $this->mFilterCallback
= $params['filter-callback'];
1239 if ( isset( $params['flatlist'] ) ) {
1240 $this->mClass
.= ' mw-htmlform-flatlist';
1245 * Get the complete table row for the input, including help text,
1246 * labels, and whatever.
1247 * @param $value String the value to set the input to.
1248 * @return String complete HTML table row.
1250 function getTableRow( $value ) {
1251 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1252 $inputHtml = $this->getInputHTML( $value );
1253 $fieldType = get_class( $this );
1254 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1255 $cellAttributes = array();
1257 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1258 $cellAttributes['colspan'] = 2;
1259 $verticalLabel = true;
1261 $verticalLabel = false;
1264 $label = $this->getLabelHtml( $cellAttributes );
1266 $field = Html
::rawElement(
1268 array( 'class' => 'mw-input' ) +
$cellAttributes,
1269 $inputHtml . "\n$errors"
1272 if ( $verticalLabel ) {
1273 $html = Html
::rawElement( 'tr',
1274 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1275 $html .= Html
::rawElement( 'tr',
1276 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1279 $html = Html
::rawElement( 'tr',
1280 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1284 return $html . $helptext;
1288 * Get the complete div for the input, including help text,
1289 * labels, and whatever.
1291 * @param $value String the value to set the input to.
1292 * @return String complete HTML table row.
1294 public function getDiv( $value ) {
1295 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1296 $inputHtml = $this->getInputHTML( $value );
1297 $fieldType = get_class( $this );
1298 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1299 $cellAttributes = array();
1300 $label = $this->getLabelHtml( $cellAttributes );
1302 $field = Html
::rawElement(
1304 array( 'class' => 'mw-input' ) +
$cellAttributes,
1305 $inputHtml . "\n$errors"
1307 $html = Html
::rawElement( 'div',
1308 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1315 * Get the complete raw fields for the input, including help text,
1316 * labels, and whatever.
1318 * @param $value String the value to set the input to.
1319 * @return String complete HTML table row.
1321 public function getRaw( $value ) {
1322 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1323 $inputHtml = $this->getInputHTML( $value );
1324 $fieldType = get_class( $this );
1325 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1326 $cellAttributes = array();
1327 $label = $this->getLabelHtml( $cellAttributes );
1329 $html = "\n$errors";
1331 $html .= $inputHtml;
1337 * Generate help text HTML in table format
1339 * @param $helptext String|null
1342 public function getHelpTextHtmlTable( $helptext ) {
1343 if ( is_null( $helptext ) ) {
1347 $row = Html
::rawElement(
1349 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1352 $row = Html
::rawElement( 'tr', array(), $row );
1357 * Generate help text HTML in div format
1359 * @param $helptext String|null
1362 public function getHelpTextHtmlDiv( $helptext ) {
1363 if ( is_null( $helptext ) ) {
1367 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1372 * Generate help text HTML formatted for raw output
1374 * @param $helptext String|null
1377 public function getHelpTextHtmlRaw( $helptext ) {
1378 return $this->getHelpTextHtmlDiv( $helptext );
1382 * Determine the help text to display
1386 public function getHelpText() {
1389 if ( isset( $this->mParams
['help-message'] ) ) {
1390 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1393 if ( isset( $this->mParams
['help-messages'] ) ) {
1394 foreach ( $this->mParams
['help-messages'] as $name ) {
1395 $helpMessage = (array)$name;
1396 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1398 if ( $msg->exists() ) {
1399 if ( is_null( $helptext ) ) {
1402 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1404 $helptext .= $msg->parse(); // Append message
1408 elseif ( isset( $this->mParams
['help'] ) ) {
1409 $helptext = $this->mParams
['help'];
1415 * Determine form errors to display and their classes
1417 * @param $value String the value of the input
1420 public function getErrorsAndErrorClass( $value ) {
1421 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1423 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1427 $errors = self
::formatErrors( $errors );
1428 $errorClass = 'mw-htmlform-invalid-input';
1430 return array( $errors, $errorClass );
1433 function getLabel() {
1434 return $this->mLabel
;
1437 function getLabelHtml( $cellAttributes = array() ) {
1438 # Don't output a for= attribute for labels with no associated input.
1439 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1442 if ( $this->needsLabel() ) {
1443 $for['for'] = $this->mID
;
1446 $displayFormat = $this->mParent
->getDisplayFormat();
1447 $labelElement = Html
::rawElement( 'label', $for, $this->getLabel() );
1449 if ( $displayFormat == 'table' ) {
1450 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1451 Html
::rawElement( 'label', $for, $this->getLabel() )
1453 } elseif ( $displayFormat == 'div' ) {
1454 return Html
::rawElement( 'div', array( 'class' => 'mw-label' ) +
$cellAttributes,
1455 Html
::rawElement( 'label', $for, $this->getLabel() )
1458 return $labelElement;
1462 function getDefault() {
1463 if ( isset( $this->mDefault
) ) {
1464 return $this->mDefault
;
1471 * Returns the attributes required for the tooltip and accesskey.
1473 * @return array Attributes
1475 public function getTooltipAndAccessKey() {
1476 if ( empty( $this->mParams
['tooltip'] ) ) {
1479 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1483 * flatten an array of options to a single array, for instance,
1484 * a set of "<options>" inside "<optgroups>".
1485 * @param $options array Associative Array with values either Strings
1487 * @return Array flattened input
1489 public static function flattenOptions( $options ) {
1490 $flatOpts = array();
1492 foreach ( $options as $value ) {
1493 if ( is_array( $value ) ) {
1494 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1496 $flatOpts[] = $value;
1504 * Formats one or more errors as accepted by field validation-callback.
1505 * @param $errors String|Message|Array of strings or Message instances
1506 * @return String html
1509 protected static function formatErrors( $errors ) {
1510 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1511 $errors = array_shift( $errors );
1514 if ( is_array( $errors ) ) {
1516 foreach ( $errors as $error ) {
1517 if ( $error instanceof Message
) {
1518 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1520 $lines[] = Html
::rawElement( 'li', array(), $error );
1523 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1525 if ( $errors instanceof Message
) {
1526 $errors = $errors->parse();
1528 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1533 class HTMLTextField
extends HTMLFormField
{
1534 function getSize() {
1535 return isset( $this->mParams
['size'] )
1536 ?
$this->mParams
['size']
1540 function getInputHTML( $value ) {
1543 'name' => $this->mName
,
1544 'size' => $this->getSize(),
1546 ) +
$this->getTooltipAndAccessKey();
1548 if ( $this->mClass
!== '' ) {
1549 $attribs['class'] = $this->mClass
;
1552 if ( !empty( $this->mParams
['disabled'] ) ) {
1553 $attribs['disabled'] = 'disabled';
1556 # TODO: Enforce pattern, step, required, readonly on the server side as
1558 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1559 'placeholder', 'list', 'maxlength' );
1560 foreach ( $allowedParams as $param ) {
1561 if ( isset( $this->mParams
[$param] ) ) {
1562 $attribs[$param] = $this->mParams
[$param];
1566 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1567 if ( isset( $this->mParams
[$param] ) ) {
1568 $attribs[$param] = '';
1572 # Implement tiny differences between some field variants
1573 # here, rather than creating a new class for each one which
1574 # is essentially just a clone of this one.
1575 if ( isset( $this->mParams
['type'] ) ) {
1576 switch ( $this->mParams
['type'] ) {
1578 $attribs['type'] = 'email';
1581 $attribs['type'] = 'number';
1584 $attribs['type'] = 'number';
1585 $attribs['step'] = 'any';
1590 $attribs['type'] = $this->mParams
['type'];
1595 return Html
::element( 'input', $attribs );
1598 class HTMLTextAreaField
extends HTMLFormField
{
1599 function getCols() {
1600 return isset( $this->mParams
['cols'] )
1601 ?
$this->mParams
['cols']
1605 function getRows() {
1606 return isset( $this->mParams
['rows'] )
1607 ?
$this->mParams
['rows']
1611 function getInputHTML( $value ) {
1614 'name' => $this->mName
,
1615 'cols' => $this->getCols(),
1616 'rows' => $this->getRows(),
1617 ) +
$this->getTooltipAndAccessKey();
1619 if ( $this->mClass
!== '' ) {
1620 $attribs['class'] = $this->mClass
;
1623 if ( !empty( $this->mParams
['disabled'] ) ) {
1624 $attribs['disabled'] = 'disabled';
1627 if ( !empty( $this->mParams
['readonly'] ) ) {
1628 $attribs['readonly'] = 'readonly';
1631 if ( isset( $this->mParams
['placeholder'] ) ) {
1632 $attribs['placeholder'] = $this->mParams
['placeholder'];
1635 foreach ( array( 'required', 'autofocus' ) as $param ) {
1636 if ( isset( $this->mParams
[$param] ) ) {
1637 $attribs[$param] = '';
1641 return Html
::element( 'textarea', $attribs, $value );
1646 * A field that will contain a numeric value
1648 class HTMLFloatField
extends HTMLTextField
{
1649 function getSize() {
1650 return isset( $this->mParams
['size'] )
1651 ?
$this->mParams
['size']
1655 function validate( $value, $alldata ) {
1656 $p = parent
::validate( $value, $alldata );
1658 if ( $p !== true ) {
1662 $value = trim( $value );
1664 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1665 # with the addition that a leading '+' sign is ok.
1666 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1667 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1670 # The "int" part of these message names is rather confusing.
1671 # They make equal sense for all numbers.
1672 if ( isset( $this->mParams
['min'] ) ) {
1673 $min = $this->mParams
['min'];
1675 if ( $min > $value ) {
1676 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1680 if ( isset( $this->mParams
['max'] ) ) {
1681 $max = $this->mParams
['max'];
1683 if ( $max < $value ) {
1684 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1693 * A field that must contain a number
1695 class HTMLIntField
extends HTMLFloatField
{
1696 function validate( $value, $alldata ) {
1697 $p = parent
::validate( $value, $alldata );
1699 if ( $p !== true ) {
1703 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1704 # with the addition that a leading '+' sign is ok. Note that leading zeros
1705 # are fine, and will be left in the input, which is useful for things like
1706 # phone numbers when you know that they are integers (the HTML5 type=tel
1707 # input does not require its value to be numeric). If you want a tidier
1708 # value to, eg, save in the DB, clean it up with intval().
1709 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1711 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1721 class HTMLCheckField
extends HTMLFormField
{
1722 function getInputHTML( $value ) {
1723 if ( !empty( $this->mParams
['invert'] ) ) {
1727 $attr = $this->getTooltipAndAccessKey();
1728 $attr['id'] = $this->mID
;
1730 if ( !empty( $this->mParams
['disabled'] ) ) {
1731 $attr['disabled'] = 'disabled';
1734 if ( $this->mClass
!== '' ) {
1735 $attr['class'] = $this->mClass
;
1738 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1739 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1743 * For a checkbox, the label goes on the right hand side, and is
1744 * added in getInputHTML(), rather than HTMLFormField::getRow()
1747 function getLabel() {
1752 * @param $request WebRequest
1755 function loadDataFromRequest( $request ) {
1757 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1761 // GetCheck won't work like we want for checks.
1762 // Fetch the value in either one of the two following case:
1763 // - we have a valid token (form got posted or GET forged by the user)
1764 // - checkbox name has a value (false or true), ie is not null
1765 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1766 // XOR has the following truth table, which is what we want
1767 // INVERT VALUE | OUTPUT
1768 // true true | false
1769 // false true | true
1770 // false false | false
1771 // true false | true
1772 return $request->getBool( $this->mName
) xor $invert;
1774 return $this->getDefault();
1780 * A select dropdown field. Basically a wrapper for Xmlselect class
1782 class HTMLSelectField
extends HTMLFormField
{
1783 function validate( $value, $alldata ) {
1784 $p = parent
::validate( $value, $alldata );
1786 if ( $p !== true ) {
1790 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1792 if ( in_array( $value, $validOptions ) )
1795 return $this->msg( 'htmlform-select-badoption' )->parse();
1798 function getInputHTML( $value ) {
1799 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1801 # If one of the options' 'name' is int(0), it is automatically selected.
1802 # because PHP sucks and thinks int(0) == 'some string'.
1803 # Working around this by forcing all of them to strings.
1804 foreach ( $this->mParams
['options'] as &$opt ) {
1805 if ( is_int( $opt ) ) {
1806 $opt = strval( $opt );
1809 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1811 if ( !empty( $this->mParams
['disabled'] ) ) {
1812 $select->setAttribute( 'disabled', 'disabled' );
1815 if ( $this->mClass
!== '' ) {
1816 $select->setAttribute( 'class', $this->mClass
);
1819 $select->addOptions( $this->mParams
['options'] );
1821 return $select->getHTML();
1826 * Select dropdown field, with an additional "other" textbox.
1828 class HTMLSelectOrOtherField
extends HTMLTextField
{
1829 static $jsAdded = false;
1831 function __construct( $params ) {
1832 if ( !in_array( 'other', $params['options'], true ) ) {
1833 $msg = isset( $params['other'] ) ?
1835 wfMessage( 'htmlform-selectorother-other' )->text();
1836 $params['options'][$msg] = 'other';
1839 parent
::__construct( $params );
1842 static function forceToStringRecursive( $array ) {
1843 if ( is_array( $array ) ) {
1844 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1846 return strval( $array );
1850 function getInputHTML( $value ) {
1851 $valInSelect = false;
1853 if ( $value !== false ) {
1854 $valInSelect = in_array(
1856 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1860 $selected = $valInSelect ?
$value : 'other';
1862 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1864 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1865 $select->addOptions( $opts );
1867 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1869 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1871 if ( !empty( $this->mParams
['disabled'] ) ) {
1872 $select->setAttribute( 'disabled', 'disabled' );
1873 $tbAttribs['disabled'] = 'disabled';
1876 $select = $select->getHTML();
1878 if ( isset( $this->mParams
['maxlength'] ) ) {
1879 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1882 if ( $this->mClass
!== '' ) {
1883 $tbAttribs['class'] = $this->mClass
;
1886 $textbox = Html
::input(
1887 $this->mName
. '-other',
1888 $valInSelect ?
'' : $value,
1893 return "$select<br />\n$textbox";
1897 * @param $request WebRequest
1900 function loadDataFromRequest( $request ) {
1901 if ( $request->getCheck( $this->mName
) ) {
1902 $val = $request->getText( $this->mName
);
1904 if ( $val == 'other' ) {
1905 $val = $request->getText( $this->mName
. '-other' );
1910 return $this->getDefault();
1916 * Multi-select field
1918 class HTMLMultiSelectField
extends HTMLFormField
{
1920 function validate( $value, $alldata ) {
1921 $p = parent
::validate( $value, $alldata );
1923 if ( $p !== true ) {
1927 if ( !is_array( $value ) ) {
1931 # If all options are valid, array_intersect of the valid options
1932 # and the provided options will return the provided options.
1933 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1935 $validValues = array_intersect( $value, $validOptions );
1936 if ( count( $validValues ) == count( $value ) ) {
1939 return $this->msg( 'htmlform-select-badoption' )->parse();
1943 function getInputHTML( $value ) {
1944 $html = $this->formatOptions( $this->mParams
['options'], $value );
1949 function formatOptions( $options, $value ) {
1954 if ( !empty( $this->mParams
['disabled'] ) ) {
1955 $attribs['disabled'] = 'disabled';
1958 foreach ( $options as $label => $info ) {
1959 if ( is_array( $info ) ) {
1960 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1961 $html .= $this->formatOptions( $info, $value );
1963 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1965 $checkbox = Xml
::check(
1966 $this->mName
. '[]',
1967 in_array( $info, $value, true ),
1968 $attribs +
$thisAttribs );
1969 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1971 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1979 * @param $request WebRequest
1982 function loadDataFromRequest( $request ) {
1983 if ( $this->mParent
->getMethod() == 'post' ) {
1984 if ( $request->wasPosted() ) {
1985 # Checkboxes are just not added to the request arrays if they're not checked,
1986 # so it's perfectly possible for there not to be an entry at all
1987 return $request->getArray( $this->mName
, array() );
1989 # That's ok, the user has not yet submitted the form, so show the defaults
1990 return $this->getDefault();
1993 # This is the impossible case: if we look at $_GET and see no data for our
1994 # field, is it because the user has not yet submitted the form, or that they
1995 # have submitted it with all the options unchecked? We will have to assume the
1996 # latter, which basically means that you can't specify 'positive' defaults
1999 return $request->getArray( $this->mName
, array() );
2003 function getDefault() {
2004 if ( isset( $this->mDefault
) ) {
2005 return $this->mDefault
;
2011 protected function needsLabel() {
2017 * Double field with a dropdown list constructed from a system message in the format
2020 * * New Optgroup header
2021 * Plus a text field underneath for an additional reason. The 'value' of the field is
2022 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2024 * @todo FIXME: If made 'required', only the text field should be compulsory.
2026 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2028 function __construct( $params ) {
2029 if ( array_key_exists( 'other', $params ) ) {
2030 } elseif ( array_key_exists( 'other-message', $params ) ) {
2031 $params['other'] = wfMessage( $params['other-message'] )->plain();
2033 $params['other'] = null;
2036 if ( array_key_exists( 'options', $params ) ) {
2037 # Options array already specified
2038 } elseif ( array_key_exists( 'options-message', $params ) ) {
2039 # Generate options array from a system message
2040 $params['options'] = self
::parseMessage(
2041 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2046 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2048 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2050 parent
::__construct( $params );
2054 * Build a drop-down box from a textual list.
2055 * @param $string String message text
2056 * @param $otherName String name of "other reason" option
2058 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2060 public static function parseMessage( $string, $otherName = null ) {
2061 if ( $otherName === null ) {
2062 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2066 $options = array( $otherName => 'other' );
2068 foreach ( explode( "\n", $string ) as $option ) {
2069 $value = trim( $option );
2070 if ( $value == '' ) {
2072 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2073 # A new group is starting...
2074 $value = trim( substr( $value, 1 ) );
2076 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2078 $opt = trim( substr( $value, 2 ) );
2079 if ( $optgroup === false ) {
2080 $options[$opt] = $opt;
2082 $options[$optgroup][$opt] = $opt;
2085 # groupless reason list
2087 $options[$option] = $option;
2094 function getInputHTML( $value ) {
2095 $select = parent
::getInputHTML( $value[1] );
2097 $textAttribs = array(
2098 'id' => $this->mID
. '-other',
2099 'size' => $this->getSize(),
2102 if ( $this->mClass
!== '' ) {
2103 $textAttribs['class'] = $this->mClass
;
2106 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2107 if ( isset( $this->mParams
[$param] ) ) {
2108 $textAttribs[$param] = '';
2112 $textbox = Html
::input(
2113 $this->mName
. '-other',
2119 return "$select<br />\n$textbox";
2123 * @param $request WebRequest
2124 * @return Array("<overall message>","<select value>","<text field value>")
2126 function loadDataFromRequest( $request ) {
2127 if ( $request->getCheck( $this->mName
) ) {
2129 $list = $request->getText( $this->mName
);
2130 $text = $request->getText( $this->mName
. '-other' );
2132 if ( $list == 'other' ) {
2134 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2135 # User has spoofed the select form to give an option which wasn't
2136 # in the original offer. Sulk...
2138 } elseif ( $text == '' ) {
2141 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2145 $final = $this->getDefault();
2149 foreach ( $this->mFlatOptions
as $option ) {
2150 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2151 if ( strpos( $text, $match ) === 0 ) {
2153 $text = substr( $text, strlen( $match ) );
2158 return array( $final, $list, $text );
2161 function getSize() {
2162 return isset( $this->mParams
['size'] )
2163 ?
$this->mParams
['size']
2167 function validate( $value, $alldata ) {
2168 # HTMLSelectField forces $value to be one of the options in the select
2169 # field, which is not useful here. But we do want the validation further up
2171 $p = parent
::validate( $value[1], $alldata );
2173 if ( $p !== true ) {
2177 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value[1] === '' ) {
2178 return $this->msg( 'htmlform-required' )->parse();
2186 * Radio checkbox fields.
2188 class HTMLRadioField
extends HTMLFormField
{
2191 function validate( $value, $alldata ) {
2192 $p = parent
::validate( $value, $alldata );
2194 if ( $p !== true ) {
2198 if ( !is_string( $value ) && !is_int( $value ) ) {
2202 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2204 if ( in_array( $value, $validOptions ) ) {
2207 return $this->msg( 'htmlform-select-badoption' )->parse();
2212 * This returns a block of all the radio options, in one cell.
2213 * @see includes/HTMLFormField#getInputHTML()
2214 * @param $value String
2217 function getInputHTML( $value ) {
2218 $html = $this->formatOptions( $this->mParams
['options'], $value );
2223 function formatOptions( $options, $value ) {
2227 if ( !empty( $this->mParams
['disabled'] ) ) {
2228 $attribs['disabled'] = 'disabled';
2231 # TODO: should this produce an unordered list perhaps?
2232 foreach ( $options as $label => $info ) {
2233 if ( is_array( $info ) ) {
2234 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2235 $html .= $this->formatOptions( $info, $value );
2237 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2238 $radio = Xml
::radio(
2242 $attribs +
array( 'id' => $id )
2244 $radio .= ' ' .
2245 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2247 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2254 protected function needsLabel() {
2260 * An information field (text blob), not a proper input.
2262 class HTMLInfoField
extends HTMLFormField
{
2263 public function __construct( $info ) {
2264 $info['nodata'] = true;
2266 parent
::__construct( $info );
2269 public function getInputHTML( $value ) {
2270 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2273 public function getTableRow( $value ) {
2274 if ( !empty( $this->mParams
['rawrow'] ) ) {
2278 return parent
::getTableRow( $value );
2284 public function getDiv( $value ) {
2285 if ( !empty( $this->mParams
['rawrow'] ) ) {
2289 return parent
::getDiv( $value );
2295 public function getRaw( $value ) {
2296 if ( !empty( $this->mParams
['rawrow'] ) ) {
2300 return parent
::getRaw( $value );
2303 protected function needsLabel() {
2308 class HTMLHiddenField
extends HTMLFormField
{
2309 public function __construct( $params ) {
2310 parent
::__construct( $params );
2312 # Per HTML5 spec, hidden fields cannot be 'required'
2313 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2314 unset( $this->mParams
['required'] );
2317 public function getTableRow( $value ) {
2320 $params['id'] = $this->mID
;
2323 $this->mParent
->addHiddenField(
2335 public function getDiv( $value ) {
2336 return $this->getTableRow( $value );
2342 public function getRaw( $value ) {
2343 return $this->getTableRow( $value );
2346 public function getInputHTML( $value ) { return ''; }
2350 * Add a submit button inline in the form (as opposed to
2351 * HTMLForm::addButton(), which will add it at the end).
2353 class HTMLSubmitField
extends HTMLFormField
{
2355 public function __construct( $info ) {
2356 $info['nodata'] = true;
2357 parent
::__construct( $info );
2360 public function getInputHTML( $value ) {
2361 return Xml
::submitButton(
2364 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2365 'name' => $this->mName
,
2371 protected function needsLabel() {
2376 * Button cannot be invalid
2377 * @param $value String
2378 * @param $alldata Array
2381 public function validate( $value, $alldata ) {
2386 class HTMLEditTools
extends HTMLFormField
{
2387 public function getInputHTML( $value ) {
2391 public function getTableRow( $value ) {
2392 $msg = $this->formatMsg();
2394 return '<tr><td></td><td class="mw-input">'
2395 . '<div class="mw-editTools">'
2396 . $msg->parseAsBlock()
2397 . "</div></td></tr>\n";
2403 public function getDiv( $value ) {
2404 $msg = $this->formatMsg();
2405 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2411 public function getRaw( $value ) {
2412 return $this->getDiv( $value );
2415 protected function formatMsg() {
2416 if ( empty( $this->mParams
['message'] ) ) {
2417 $msg = $this->msg( 'edittools' );
2419 $msg = $this->msg( $this->mParams
['message'] );
2420 if ( $msg->isDisabled() ) {
2421 $msg = $this->msg( 'edittools' );
2424 $msg->inContentLanguage();