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 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1325 $cellAttributes = array();
1326 $label = $this->getLabelHtml( $cellAttributes );
1328 $html = "\n$errors";
1330 $html .= $inputHtml;
1336 * Generate help text HTML in table format
1338 * @param $helptext String|null
1341 public function getHelpTextHtmlTable( $helptext ) {
1342 if ( is_null( $helptext ) ) {
1346 $row = Html
::rawElement(
1348 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1351 $row = Html
::rawElement( 'tr', array(), $row );
1356 * Generate help text HTML in div format
1358 * @param $helptext String|null
1361 public function getHelpTextHtmlDiv( $helptext ) {
1362 if ( is_null( $helptext ) ) {
1366 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1371 * Generate help text HTML formatted for raw output
1373 * @param $helptext String|null
1376 public function getHelpTextHtmlRaw( $helptext ) {
1377 return $this->getHelpTextHtmlDiv( $helptext );
1381 * Determine the help text to display
1385 public function getHelpText() {
1388 if ( isset( $this->mParams
['help-message'] ) ) {
1389 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1392 if ( isset( $this->mParams
['help-messages'] ) ) {
1393 foreach ( $this->mParams
['help-messages'] as $name ) {
1394 $helpMessage = (array)$name;
1395 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1397 if ( $msg->exists() ) {
1398 if ( is_null( $helptext ) ) {
1401 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1403 $helptext .= $msg->parse(); // Append message
1407 elseif ( isset( $this->mParams
['help'] ) ) {
1408 $helptext = $this->mParams
['help'];
1414 * Determine form errors to display and their classes
1416 * @param $value String the value of the input
1419 public function getErrorsAndErrorClass( $value ) {
1420 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1422 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1426 $errors = self
::formatErrors( $errors );
1427 $errorClass = 'mw-htmlform-invalid-input';
1429 return array( $errors, $errorClass );
1432 function getLabel() {
1433 return $this->mLabel
;
1436 function getLabelHtml( $cellAttributes = array() ) {
1437 # Don't output a for= attribute for labels with no associated input.
1438 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1441 if ( $this->needsLabel() ) {
1442 $for['for'] = $this->mID
;
1445 $displayFormat = $this->mParent
->getDisplayFormat();
1446 $labelElement = Html
::rawElement( 'label', $for, $this->getLabel() );
1448 if ( $displayFormat == 'table' ) {
1449 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1450 Html
::rawElement( 'label', $for, $this->getLabel() )
1452 } elseif ( $displayFormat == 'div' ) {
1453 return Html
::rawElement( 'div', array( 'class' => 'mw-label' ) +
$cellAttributes,
1454 Html
::rawElement( 'label', $for, $this->getLabel() )
1457 return $labelElement;
1461 function getDefault() {
1462 if ( isset( $this->mDefault
) ) {
1463 return $this->mDefault
;
1470 * Returns the attributes required for the tooltip and accesskey.
1472 * @return array Attributes
1474 public function getTooltipAndAccessKey() {
1475 if ( empty( $this->mParams
['tooltip'] ) ) {
1478 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1482 * flatten an array of options to a single array, for instance,
1483 * a set of "<options>" inside "<optgroups>".
1484 * @param $options array Associative Array with values either Strings
1486 * @return Array flattened input
1488 public static function flattenOptions( $options ) {
1489 $flatOpts = array();
1491 foreach ( $options as $value ) {
1492 if ( is_array( $value ) ) {
1493 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1495 $flatOpts[] = $value;
1503 * Formats one or more errors as accepted by field validation-callback.
1504 * @param $errors String|Message|Array of strings or Message instances
1505 * @return String html
1508 protected static function formatErrors( $errors ) {
1509 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1510 $errors = array_shift( $errors );
1513 if ( is_array( $errors ) ) {
1515 foreach ( $errors as $error ) {
1516 if ( $error instanceof Message
) {
1517 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1519 $lines[] = Html
::rawElement( 'li', array(), $error );
1522 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1524 if ( $errors instanceof Message
) {
1525 $errors = $errors->parse();
1527 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1532 class HTMLTextField
extends HTMLFormField
{
1533 function getSize() {
1534 return isset( $this->mParams
['size'] )
1535 ?
$this->mParams
['size']
1539 function getInputHTML( $value ) {
1542 'name' => $this->mName
,
1543 'size' => $this->getSize(),
1545 ) +
$this->getTooltipAndAccessKey();
1547 if ( $this->mClass
!== '' ) {
1548 $attribs['class'] = $this->mClass
;
1551 if ( !empty( $this->mParams
['disabled'] ) ) {
1552 $attribs['disabled'] = 'disabled';
1555 # TODO: Enforce pattern, step, required, readonly on the server side as
1557 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1558 'placeholder', 'list', 'maxlength' );
1559 foreach ( $allowedParams as $param ) {
1560 if ( isset( $this->mParams
[$param] ) ) {
1561 $attribs[$param] = $this->mParams
[$param];
1565 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1566 if ( isset( $this->mParams
[$param] ) ) {
1567 $attribs[$param] = '';
1571 # Implement tiny differences between some field variants
1572 # here, rather than creating a new class for each one which
1573 # is essentially just a clone of this one.
1574 if ( isset( $this->mParams
['type'] ) ) {
1575 switch ( $this->mParams
['type'] ) {
1577 $attribs['type'] = 'email';
1580 $attribs['type'] = 'number';
1583 $attribs['type'] = 'number';
1584 $attribs['step'] = 'any';
1589 $attribs['type'] = $this->mParams
['type'];
1594 return Html
::element( 'input', $attribs );
1597 class HTMLTextAreaField
extends HTMLFormField
{
1598 function getCols() {
1599 return isset( $this->mParams
['cols'] )
1600 ?
$this->mParams
['cols']
1604 function getRows() {
1605 return isset( $this->mParams
['rows'] )
1606 ?
$this->mParams
['rows']
1610 function getInputHTML( $value ) {
1613 'name' => $this->mName
,
1614 'cols' => $this->getCols(),
1615 'rows' => $this->getRows(),
1616 ) +
$this->getTooltipAndAccessKey();
1618 if ( $this->mClass
!== '' ) {
1619 $attribs['class'] = $this->mClass
;
1622 if ( !empty( $this->mParams
['disabled'] ) ) {
1623 $attribs['disabled'] = 'disabled';
1626 if ( !empty( $this->mParams
['readonly'] ) ) {
1627 $attribs['readonly'] = 'readonly';
1630 if ( isset( $this->mParams
['placeholder'] ) ) {
1631 $attribs['placeholder'] = $this->mParams
['placeholder'];
1634 foreach ( array( 'required', 'autofocus' ) as $param ) {
1635 if ( isset( $this->mParams
[$param] ) ) {
1636 $attribs[$param] = '';
1640 return Html
::element( 'textarea', $attribs, $value );
1645 * A field that will contain a numeric value
1647 class HTMLFloatField
extends HTMLTextField
{
1648 function getSize() {
1649 return isset( $this->mParams
['size'] )
1650 ?
$this->mParams
['size']
1654 function validate( $value, $alldata ) {
1655 $p = parent
::validate( $value, $alldata );
1657 if ( $p !== true ) {
1661 $value = trim( $value );
1663 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1664 # with the addition that a leading '+' sign is ok.
1665 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1666 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1669 # The "int" part of these message names is rather confusing.
1670 # They make equal sense for all numbers.
1671 if ( isset( $this->mParams
['min'] ) ) {
1672 $min = $this->mParams
['min'];
1674 if ( $min > $value ) {
1675 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1679 if ( isset( $this->mParams
['max'] ) ) {
1680 $max = $this->mParams
['max'];
1682 if ( $max < $value ) {
1683 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1692 * A field that must contain a number
1694 class HTMLIntField
extends HTMLFloatField
{
1695 function validate( $value, $alldata ) {
1696 $p = parent
::validate( $value, $alldata );
1698 if ( $p !== true ) {
1702 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1703 # with the addition that a leading '+' sign is ok. Note that leading zeros
1704 # are fine, and will be left in the input, which is useful for things like
1705 # phone numbers when you know that they are integers (the HTML5 type=tel
1706 # input does not require its value to be numeric). If you want a tidier
1707 # value to, eg, save in the DB, clean it up with intval().
1708 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1710 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1720 class HTMLCheckField
extends HTMLFormField
{
1721 function getInputHTML( $value ) {
1722 if ( !empty( $this->mParams
['invert'] ) ) {
1726 $attr = $this->getTooltipAndAccessKey();
1727 $attr['id'] = $this->mID
;
1729 if ( !empty( $this->mParams
['disabled'] ) ) {
1730 $attr['disabled'] = 'disabled';
1733 if ( $this->mClass
!== '' ) {
1734 $attr['class'] = $this->mClass
;
1737 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1738 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1742 * For a checkbox, the label goes on the right hand side, and is
1743 * added in getInputHTML(), rather than HTMLFormField::getRow()
1746 function getLabel() {
1751 * @param $request WebRequest
1754 function loadDataFromRequest( $request ) {
1756 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1760 // GetCheck won't work like we want for checks.
1761 // Fetch the value in either one of the two following case:
1762 // - we have a valid token (form got posted or GET forged by the user)
1763 // - checkbox name has a value (false or true), ie is not null
1764 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1765 // XOR has the following truth table, which is what we want
1766 // INVERT VALUE | OUTPUT
1767 // true true | false
1768 // false true | true
1769 // false false | false
1770 // true false | true
1771 return $request->getBool( $this->mName
) xor $invert;
1773 return $this->getDefault();
1779 * A select dropdown field. Basically a wrapper for Xmlselect class
1781 class HTMLSelectField
extends HTMLFormField
{
1782 function validate( $value, $alldata ) {
1783 $p = parent
::validate( $value, $alldata );
1785 if ( $p !== true ) {
1789 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1791 if ( in_array( $value, $validOptions ) )
1794 return $this->msg( 'htmlform-select-badoption' )->parse();
1797 function getInputHTML( $value ) {
1798 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1800 # If one of the options' 'name' is int(0), it is automatically selected.
1801 # because PHP sucks and thinks int(0) == 'some string'.
1802 # Working around this by forcing all of them to strings.
1803 foreach ( $this->mParams
['options'] as &$opt ) {
1804 if ( is_int( $opt ) ) {
1805 $opt = strval( $opt );
1808 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1810 if ( !empty( $this->mParams
['disabled'] ) ) {
1811 $select->setAttribute( 'disabled', 'disabled' );
1814 if ( $this->mClass
!== '' ) {
1815 $select->setAttribute( 'class', $this->mClass
);
1818 $select->addOptions( $this->mParams
['options'] );
1820 return $select->getHTML();
1825 * Select dropdown field, with an additional "other" textbox.
1827 class HTMLSelectOrOtherField
extends HTMLTextField
{
1828 static $jsAdded = false;
1830 function __construct( $params ) {
1831 if ( !in_array( 'other', $params['options'], true ) ) {
1832 $msg = isset( $params['other'] ) ?
1834 wfMessage( 'htmlform-selectorother-other' )->text();
1835 $params['options'][$msg] = 'other';
1838 parent
::__construct( $params );
1841 static function forceToStringRecursive( $array ) {
1842 if ( is_array( $array ) ) {
1843 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1845 return strval( $array );
1849 function getInputHTML( $value ) {
1850 $valInSelect = false;
1852 if ( $value !== false ) {
1853 $valInSelect = in_array(
1855 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1859 $selected = $valInSelect ?
$value : 'other';
1861 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1863 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1864 $select->addOptions( $opts );
1866 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1868 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1870 if ( !empty( $this->mParams
['disabled'] ) ) {
1871 $select->setAttribute( 'disabled', 'disabled' );
1872 $tbAttribs['disabled'] = 'disabled';
1875 $select = $select->getHTML();
1877 if ( isset( $this->mParams
['maxlength'] ) ) {
1878 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1881 if ( $this->mClass
!== '' ) {
1882 $tbAttribs['class'] = $this->mClass
;
1885 $textbox = Html
::input(
1886 $this->mName
. '-other',
1887 $valInSelect ?
'' : $value,
1892 return "$select<br />\n$textbox";
1896 * @param $request WebRequest
1899 function loadDataFromRequest( $request ) {
1900 if ( $request->getCheck( $this->mName
) ) {
1901 $val = $request->getText( $this->mName
);
1903 if ( $val == 'other' ) {
1904 $val = $request->getText( $this->mName
. '-other' );
1909 return $this->getDefault();
1915 * Multi-select field
1917 class HTMLMultiSelectField
extends HTMLFormField
{
1919 function validate( $value, $alldata ) {
1920 $p = parent
::validate( $value, $alldata );
1922 if ( $p !== true ) {
1926 if ( !is_array( $value ) ) {
1930 # If all options are valid, array_intersect of the valid options
1931 # and the provided options will return the provided options.
1932 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1934 $validValues = array_intersect( $value, $validOptions );
1935 if ( count( $validValues ) == count( $value ) ) {
1938 return $this->msg( 'htmlform-select-badoption' )->parse();
1942 function getInputHTML( $value ) {
1943 $html = $this->formatOptions( $this->mParams
['options'], $value );
1948 function formatOptions( $options, $value ) {
1953 if ( !empty( $this->mParams
['disabled'] ) ) {
1954 $attribs['disabled'] = 'disabled';
1957 foreach ( $options as $label => $info ) {
1958 if ( is_array( $info ) ) {
1959 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1960 $html .= $this->formatOptions( $info, $value );
1962 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1964 $checkbox = Xml
::check(
1965 $this->mName
. '[]',
1966 in_array( $info, $value, true ),
1967 $attribs +
$thisAttribs );
1968 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1970 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1978 * @param $request WebRequest
1981 function loadDataFromRequest( $request ) {
1982 if ( $this->mParent
->getMethod() == 'post' ) {
1983 if ( $request->wasPosted() ) {
1984 # Checkboxes are just not added to the request arrays if they're not checked,
1985 # so it's perfectly possible for there not to be an entry at all
1986 return $request->getArray( $this->mName
, array() );
1988 # That's ok, the user has not yet submitted the form, so show the defaults
1989 return $this->getDefault();
1992 # This is the impossible case: if we look at $_GET and see no data for our
1993 # field, is it because the user has not yet submitted the form, or that they
1994 # have submitted it with all the options unchecked? We will have to assume the
1995 # latter, which basically means that you can't specify 'positive' defaults
1998 return $request->getArray( $this->mName
, array() );
2002 function getDefault() {
2003 if ( isset( $this->mDefault
) ) {
2004 return $this->mDefault
;
2010 protected function needsLabel() {
2016 * Double field with a dropdown list constructed from a system message in the format
2019 * * New Optgroup header
2020 * Plus a text field underneath for an additional reason. The 'value' of the field is
2021 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2023 * @todo FIXME: If made 'required', only the text field should be compulsory.
2025 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2027 function __construct( $params ) {
2028 if ( array_key_exists( 'other', $params ) ) {
2029 } elseif ( array_key_exists( 'other-message', $params ) ) {
2030 $params['other'] = wfMessage( $params['other-message'] )->plain();
2032 $params['other'] = null;
2035 if ( array_key_exists( 'options', $params ) ) {
2036 # Options array already specified
2037 } elseif ( array_key_exists( 'options-message', $params ) ) {
2038 # Generate options array from a system message
2039 $params['options'] = self
::parseMessage(
2040 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2045 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2047 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2049 parent
::__construct( $params );
2053 * Build a drop-down box from a textual list.
2054 * @param $string String message text
2055 * @param $otherName String name of "other reason" option
2057 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2059 public static function parseMessage( $string, $otherName = null ) {
2060 if ( $otherName === null ) {
2061 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2065 $options = array( $otherName => 'other' );
2067 foreach ( explode( "\n", $string ) as $option ) {
2068 $value = trim( $option );
2069 if ( $value == '' ) {
2071 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2072 # A new group is starting...
2073 $value = trim( substr( $value, 1 ) );
2075 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2077 $opt = trim( substr( $value, 2 ) );
2078 if ( $optgroup === false ) {
2079 $options[$opt] = $opt;
2081 $options[$optgroup][$opt] = $opt;
2084 # groupless reason list
2086 $options[$option] = $option;
2093 function getInputHTML( $value ) {
2094 $select = parent
::getInputHTML( $value[1] );
2096 $textAttribs = array(
2097 'id' => $this->mID
. '-other',
2098 'size' => $this->getSize(),
2101 if ( $this->mClass
!== '' ) {
2102 $textAttribs['class'] = $this->mClass
;
2105 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2106 if ( isset( $this->mParams
[$param] ) ) {
2107 $textAttribs[$param] = '';
2111 $textbox = Html
::input(
2112 $this->mName
. '-other',
2118 return "$select<br />\n$textbox";
2122 * @param $request WebRequest
2123 * @return Array("<overall message>","<select value>","<text field value>")
2125 function loadDataFromRequest( $request ) {
2126 if ( $request->getCheck( $this->mName
) ) {
2128 $list = $request->getText( $this->mName
);
2129 $text = $request->getText( $this->mName
. '-other' );
2131 if ( $list == 'other' ) {
2133 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2134 # User has spoofed the select form to give an option which wasn't
2135 # in the original offer. Sulk...
2137 } elseif ( $text == '' ) {
2140 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2144 $final = $this->getDefault();
2148 foreach ( $this->mFlatOptions
as $option ) {
2149 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2150 if ( strpos( $text, $match ) === 0 ) {
2152 $text = substr( $text, strlen( $match ) );
2157 return array( $final, $list, $text );
2160 function getSize() {
2161 return isset( $this->mParams
['size'] )
2162 ?
$this->mParams
['size']
2166 function validate( $value, $alldata ) {
2167 # HTMLSelectField forces $value to be one of the options in the select
2168 # field, which is not useful here. But we do want the validation further up
2170 $p = parent
::validate( $value[1], $alldata );
2172 if ( $p !== true ) {
2176 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value[1] === '' ) {
2177 return $this->msg( 'htmlform-required' )->parse();
2185 * Radio checkbox fields.
2187 class HTMLRadioField
extends HTMLFormField
{
2190 function validate( $value, $alldata ) {
2191 $p = parent
::validate( $value, $alldata );
2193 if ( $p !== true ) {
2197 if ( !is_string( $value ) && !is_int( $value ) ) {
2201 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2203 if ( in_array( $value, $validOptions ) ) {
2206 return $this->msg( 'htmlform-select-badoption' )->parse();
2211 * This returns a block of all the radio options, in one cell.
2212 * @see includes/HTMLFormField#getInputHTML()
2213 * @param $value String
2216 function getInputHTML( $value ) {
2217 $html = $this->formatOptions( $this->mParams
['options'], $value );
2222 function formatOptions( $options, $value ) {
2226 if ( !empty( $this->mParams
['disabled'] ) ) {
2227 $attribs['disabled'] = 'disabled';
2230 # TODO: should this produce an unordered list perhaps?
2231 foreach ( $options as $label => $info ) {
2232 if ( is_array( $info ) ) {
2233 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2234 $html .= $this->formatOptions( $info, $value );
2236 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2237 $radio = Xml
::radio(
2241 $attribs +
array( 'id' => $id )
2243 $radio .= ' ' .
2244 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2246 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2253 protected function needsLabel() {
2259 * An information field (text blob), not a proper input.
2261 class HTMLInfoField
extends HTMLFormField
{
2262 public function __construct( $info ) {
2263 $info['nodata'] = true;
2265 parent
::__construct( $info );
2268 public function getInputHTML( $value ) {
2269 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2272 public function getTableRow( $value ) {
2273 if ( !empty( $this->mParams
['rawrow'] ) ) {
2277 return parent
::getTableRow( $value );
2283 public function getDiv( $value ) {
2284 if ( !empty( $this->mParams
['rawrow'] ) ) {
2288 return parent
::getDiv( $value );
2294 public function getRaw( $value ) {
2295 if ( !empty( $this->mParams
['rawrow'] ) ) {
2299 return parent
::getRaw( $value );
2302 protected function needsLabel() {
2307 class HTMLHiddenField
extends HTMLFormField
{
2308 public function __construct( $params ) {
2309 parent
::__construct( $params );
2311 # Per HTML5 spec, hidden fields cannot be 'required'
2312 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2313 unset( $this->mParams
['required'] );
2316 public function getTableRow( $value ) {
2319 $params['id'] = $this->mID
;
2322 $this->mParent
->addHiddenField(
2334 public function getDiv( $value ) {
2335 return $this->getTableRow( $value );
2341 public function getRaw( $value ) {
2342 return $this->getTableRow( $value );
2345 public function getInputHTML( $value ) { return ''; }
2349 * Add a submit button inline in the form (as opposed to
2350 * HTMLForm::addButton(), which will add it at the end).
2352 class HTMLSubmitField
extends HTMLFormField
{
2354 public function __construct( $info ) {
2355 $info['nodata'] = true;
2356 parent
::__construct( $info );
2359 public function getInputHTML( $value ) {
2360 return Xml
::submitButton(
2363 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2364 'name' => $this->mName
,
2370 protected function needsLabel() {
2375 * Button cannot be invalid
2376 * @param $value String
2377 * @param $alldata Array
2380 public function validate( $value, $alldata ) {
2385 class HTMLEditTools
extends HTMLFormField
{
2386 public function getInputHTML( $value ) {
2390 public function getTableRow( $value ) {
2391 $msg = $this->formatMsg();
2393 return '<tr><td></td><td class="mw-input">'
2394 . '<div class="mw-editTools">'
2395 . $msg->parseAsBlock()
2396 . "</div></td></tr>\n";
2402 public function getDiv( $value ) {
2403 $msg = $this->formatMsg();
2404 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2410 public function getRaw( $value ) {
2411 return $this->getDiv( $value );
2414 protected function formatMsg() {
2415 if ( empty( $this->mParams
['message'] ) ) {
2416 $msg = $this->msg( 'edittools' );
2418 $msg = $this->msg( $this->mParams
['message'] );
2419 if ( $msg->isDisabled() ) {
2420 $msg = $this->msg( 'edittools' );
2423 $msg->inContentLanguage();