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 * The constructor input is an associative array of $fieldname => $info,
38 * where $info is an Associative Array with any of the following:
40 * 'class' -- the subclass of HTMLFormField that will be used
41 * to create the object. *NOT* the CSS class!
42 * 'type' -- roughly translates into the <select> type attribute.
43 * if 'class' is not specified, this is used as a map
44 * through HTMLForm::$typeMappings to get the class name.
45 * 'default' -- default value when the form is displayed
46 * 'id' -- HTML id attribute
47 * 'cssclass' -- CSS class
48 * 'options' -- varies according to the specific object.
49 * 'label-message' -- message key for a message to use as the label.
50 * can be an array of msg key and then parameters to
52 * 'label' -- alternatively, a raw text message. Overridden by
54 * 'help' -- message text for a message to use as a help text.
55 * 'help-message' -- message key for a message to use as a help text.
56 * can be an array of msg key and then parameters to
58 * Overwrites 'help-messages' and 'help'.
59 * 'help-messages' -- array of message key. As above, each item can
60 * be an array of msg key and then parameters.
62 * 'required' -- passed through to the object, indicating that it
63 * is a required field.
64 * 'size' -- the length of text fields
65 * 'filter-callback -- a function name to give you the chance to
66 * massage the inputted value before it's processed.
67 * @see HTMLForm::filter()
68 * 'validation-callback' -- a function name to give you the chance
69 * to impose extra validation on the field input.
70 * @see HTMLForm::validate()
71 * 'name' -- By default, the 'name' attribute of the input field
72 * is "wp{$fieldname}". If you want a different name
73 * (eg one without the "wp" prefix), specify it here and
74 * it will be used without modification.
76 * Since 1.20, you can chain mutators to ease the form generation:
79 * $form = new HTMLForm( $someFields );
80 * $form->setMethod( 'get' )
81 * ->setWrapperLegendMsg( 'message-key' )
86 * Note that you will have prepareForm and displayForm at the end. Other
87 * methods call done after that would simply not be part of the form :(
89 * TODO: Document 'section' / 'subsection' stuff
91 class HTMLForm
extends ContextSource
{
93 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
94 static $typeMappings = array(
95 'text' => 'HTMLTextField',
96 'textarea' => 'HTMLTextAreaField',
97 'select' => 'HTMLSelectField',
98 'radio' => 'HTMLRadioField',
99 'multiselect' => 'HTMLMultiSelectField',
100 'check' => 'HTMLCheckField',
101 'toggle' => 'HTMLCheckField',
102 'int' => 'HTMLIntField',
103 'float' => 'HTMLFloatField',
104 'info' => 'HTMLInfoField',
105 'selectorother' => 'HTMLSelectOrOtherField',
106 'selectandother' => 'HTMLSelectAndOtherField',
107 'submit' => 'HTMLSubmitField',
108 'hidden' => 'HTMLHiddenField',
109 'edittools' => 'HTMLEditTools',
111 // HTMLTextField will output the correct type="" attribute automagically.
112 // There are about four zillion other HTML5 input types, like url, but
113 // we don't use those at the moment, so no point in adding all of them.
114 'email' => 'HTMLTextField',
115 'password' => 'HTMLTextField',
118 protected $mMessagePrefix;
120 /** @var HTMLFormField[] */
121 protected $mFlatFields;
123 protected $mFieldTree;
124 protected $mShowReset = false;
127 protected $mSubmitCallback;
128 protected $mValidationErrorMessage;
130 protected $mPre = '';
131 protected $mHeader = '';
132 protected $mFooter = '';
133 protected $mSectionHeaders = array();
134 protected $mSectionFooters = array();
135 protected $mPost = '';
138 protected $mSubmitID;
139 protected $mSubmitName;
140 protected $mSubmitText;
141 protected $mSubmitTooltip;
144 protected $mMethod = 'post';
147 * Form action URL. false means we will use the URL to set Title
151 protected $mAction = false;
153 protected $mUseMultipart = false;
154 protected $mHiddenFields = array();
155 protected $mButtons = array();
157 protected $mWrapperLegend = false;
160 * If true, sections that contain both fields and subsections will
161 * render their subsections before their fields.
163 * Subclasses may set this to false to render subsections after fields
166 protected $mSubSectionBeforeFields = true;
169 * Format in which to display form. For viable options,
170 * @see $availableDisplayFormats
173 protected $displayFormat = 'table';
176 * Available formats in which to display the form
179 protected $availableDisplayFormats = array(
186 * Build a new HTMLForm from an array of field attributes
187 * @param $descriptor Array of Field constructs, as described above
188 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
189 * Obviates the need to call $form->setTitle()
190 * @param $messagePrefix String a prefix to go in front of default messages
192 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
193 if ( $context instanceof IContextSource
) {
194 $this->setContext( $context );
195 $this->mTitle
= false; // We don't need them to set a title
196 $this->mMessagePrefix
= $messagePrefix;
199 if ( is_string( $context ) && $messagePrefix === '' ) {
200 // it's actually $messagePrefix
201 $this->mMessagePrefix
= $context;
205 // Expand out into a tree.
206 $loadedDescriptor = array();
207 $this->mFlatFields
= array();
209 foreach ( $descriptor as $fieldname => $info ) {
210 $section = isset( $info['section'] )
214 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
215 $this->mUseMultipart
= true;
218 $field = self
::loadInputFromParameters( $fieldname, $info );
219 $field->mParent
= $this;
221 $setSection =& $loadedDescriptor;
223 $sectionParts = explode( '/', $section );
225 while ( count( $sectionParts ) ) {
226 $newName = array_shift( $sectionParts );
228 if ( !isset( $setSection[$newName] ) ) {
229 $setSection[$newName] = array();
232 $setSection =& $setSection[$newName];
236 $setSection[$fieldname] = $field;
237 $this->mFlatFields
[$fieldname] = $field;
240 $this->mFieldTree
= $loadedDescriptor;
244 * Set format in which to display the form
245 * @param $format String the name of the format to use, must be one of
246 * $this->availableDisplayFormats
248 * @return HTMLForm $this for chaining calls (since 1.20)
250 public function setDisplayFormat( $format ) {
251 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
252 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats
, true ) );
254 $this->displayFormat
= $format;
259 * Getter for displayFormat
263 public function getDisplayFormat() {
264 return $this->displayFormat
;
268 * Add the HTMLForm-specific JavaScript, if it hasn't been
270 * @deprecated since 1.18 load modules with ResourceLoader instead
272 static function addJS() { wfDeprecated( __METHOD__
, '1.18' ); }
275 * Initialise a new Object for the field
276 * @param $fieldname string
277 * @param $descriptor string input Descriptor, as described above
278 * @return HTMLFormField subclass
280 static function loadInputFromParameters( $fieldname, $descriptor ) {
281 if ( isset( $descriptor['class'] ) ) {
282 $class = $descriptor['class'];
283 } elseif ( isset( $descriptor['type'] ) ) {
284 $class = self
::$typeMappings[$descriptor['type']];
285 $descriptor['class'] = $class;
291 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
294 $descriptor['fieldname'] = $fieldname;
297 # This will throw a fatal error whenever someone try to use
298 # 'class' to feed a CSS class instead of 'cssclass'. Would be
299 # great to avoid the fatal error and show a nice error.
300 $obj = new $class( $descriptor );
306 * Prepare form for submission.
308 * @attention When doing method chaining, that should be the very last
309 * method call before displayForm().
311 * @return HTMLForm $this for chaining calls (since 1.20)
313 function prepareForm() {
314 # Check if we have the info we need
315 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
316 throw new MWException( "You must call setTitle() on an HTMLForm" );
319 # Load data from the request.
325 * Try submitting, with edit token check first
326 * @return Status|boolean
328 function tryAuthorizedSubmit() {
332 if ( $this->getMethod() != 'post' ) {
333 $submit = true; // no session check needed
334 } elseif ( $this->getRequest()->wasPosted() ) {
335 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
336 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
337 // Session tokens for logged-out users have no security value.
338 // However, if the user gave one, check it in order to give a nice
339 // "session expired" error instead of "permission denied" or such.
340 $submit = $this->getUser()->matchEditToken( $editToken );
347 $result = $this->trySubmit();
354 * The here's-one-I-made-earlier option: do the submission if
355 * posted, or display the form with or without funky validation
357 * @return Bool or Status whether submission was successful.
360 $this->prepareForm();
362 $result = $this->tryAuthorizedSubmit();
363 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
367 $this->displayForm( $result );
372 * Validate all the fields, and call the submision callback
373 * function if everything is kosher.
374 * @return Mixed Bool true == Successful submission, Bool false
375 * == No submission attempted, anything else == Error to
378 function trySubmit() {
379 # Check for validation
380 foreach ( $this->mFlatFields
as $fieldname => $field ) {
381 if ( !empty( $field->mParams
['nodata'] ) ) {
384 if ( $field->validate(
385 $this->mFieldData
[$fieldname],
389 return isset( $this->mValidationErrorMessage
)
390 ?
$this->mValidationErrorMessage
391 : array( 'htmlform-invalid-input' );
395 $callback = $this->mSubmitCallback
;
396 if ( !is_callable( $callback ) ) {
397 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
400 $data = $this->filterDataForSubmit( $this->mFieldData
);
402 $res = call_user_func( $callback, $data, $this );
408 * Set a callback to a function to do something with the form
409 * once it's been successfully validated.
410 * @param $cb String function name. The function will be passed
411 * the output from HTMLForm::filterDataForSubmit, and must
412 * return Bool true on success, Bool false if no submission
413 * was attempted, or String HTML output to display on error.
414 * @return HTMLForm $this for chaining calls (since 1.20)
416 function setSubmitCallback( $cb ) {
417 $this->mSubmitCallback
= $cb;
422 * Set a message to display on a validation error.
423 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
424 * (so each entry can be either a String or Array)
425 * @return HTMLForm $this for chaining calls (since 1.20)
427 function setValidationErrorMessage( $msg ) {
428 $this->mValidationErrorMessage
= $msg;
433 * Set the introductory message, overwriting any existing message.
434 * @param $msg String complete text of message to display
435 * @return HTMLForm $this for chaining calls (since 1.20)
437 function setIntro( $msg ) {
438 $this->setPreText( $msg );
443 * Set the introductory message, overwriting any existing message.
445 * @param $msg String complete text of message to display
446 * @return HTMLForm $this for chaining calls (since 1.20)
448 function setPreText( $msg ) {
454 * Add introductory text.
455 * @param $msg String complete text of message to display
456 * @return HTMLForm $this for chaining calls (since 1.20)
458 function addPreText( $msg ) {
464 * Add header text, inside the form.
465 * @param $msg String complete text of message to display
466 * @param $section string The section to add the header to
467 * @return HTMLForm $this for chaining calls (since 1.20)
469 function addHeaderText( $msg, $section = null ) {
470 if ( is_null( $section ) ) {
471 $this->mHeader
.= $msg;
473 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
474 $this->mSectionHeaders
[$section] = '';
476 $this->mSectionHeaders
[$section] .= $msg;
482 * Set header text, inside the form.
484 * @param $msg String complete text of message to display
485 * @param $section The section to add the header to
486 * @return HTMLForm $this for chaining calls (since 1.20)
488 function setHeaderText( $msg, $section = null ) {
489 if ( is_null( $section ) ) {
490 $this->mHeader
= $msg;
492 $this->mSectionHeaders
[$section] = $msg;
498 * Add footer text, inside the form.
499 * @param $msg String complete text of message to display
500 * @param $section string The section to add the footer text to
501 * @return HTMLForm $this for chaining calls (since 1.20)
503 function addFooterText( $msg, $section = null ) {
504 if ( is_null( $section ) ) {
505 $this->mFooter
.= $msg;
507 if ( !isset( $this->mSectionFooters
[$section] ) ) {
508 $this->mSectionFooters
[$section] = '';
510 $this->mSectionFooters
[$section] .= $msg;
516 * Set footer text, inside the form.
518 * @param $msg String complete text of message to display
519 * @param $section string The section to add the footer text to
520 * @return HTMLForm $this for chaining calls (since 1.20)
522 function setFooterText( $msg, $section = null ) {
523 if ( is_null( $section ) ) {
524 $this->mFooter
= $msg;
526 $this->mSectionFooters
[$section] = $msg;
532 * Add text to the end of the display.
533 * @param $msg String complete text of message to display
534 * @return HTMLForm $this for chaining calls (since 1.20)
536 function addPostText( $msg ) {
537 $this->mPost
.= $msg;
542 * Set text at the end of the display.
543 * @param $msg String complete text of message to display
544 * @return HTMLForm $this for chaining calls (since 1.20)
546 function setPostText( $msg ) {
552 * Add a hidden field to the output
553 * @param $name String field name. This will be used exactly as entered
554 * @param $value String field value
555 * @param $attribs Array
556 * @return HTMLForm $this for chaining calls (since 1.20)
558 public function addHiddenField( $name, $value, $attribs = array() ) {
559 $attribs +
= array( 'name' => $name );
560 $this->mHiddenFields
[] = array( $value, $attribs );
565 * Add a button to the form
566 * @param $name String field name.
567 * @param $value String field value
568 * @param $id String DOM id for the button (default: null)
569 * @param $attribs Array
570 * @return HTMLForm $this for chaining calls (since 1.20)
572 public function addButton( $name, $value, $id = null, $attribs = null ) {
573 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
578 * Display the form (sending to $wgOut), with an appropriate error
579 * message or stack of messages, and any validation errors, etc.
581 * @attention You should call prepareForm() before calling this function.
582 * Moreover, when doing method chaining this should be the very last method
583 * call just after prepareForm().
585 * @param $submitResult Mixed output from HTMLForm::trySubmit()
586 * @return Nothing, should be last call
588 function displayForm( $submitResult ) {
589 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
593 * Returns the raw HTML generated by the form
594 * @param $submitResult Mixed output from HTMLForm::trySubmit()
597 function getHTML( $submitResult ) {
598 # For good measure (it is the default)
599 $this->getOutput()->preventClickjacking();
600 $this->getOutput()->addModules( 'mediawiki.htmlform' );
603 . $this->getErrors( $submitResult )
606 . $this->getHiddenFields()
607 . $this->getButtons()
611 $html = $this->wrapForm( $html );
613 return '' . $this->mPre
. $html . $this->mPost
;
617 * Wrap the form innards in an actual "<form>" element
618 * @param $html String HTML contents to wrap.
619 * @return String wrapped HTML.
621 function wrapForm( $html ) {
623 # Include a <fieldset> wrapper for style, if requested.
624 if ( $this->mWrapperLegend
!== false ) {
625 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
627 # Use multipart/form-data
628 $encType = $this->mUseMultipart
629 ?
'multipart/form-data'
630 : 'application/x-www-form-urlencoded';
633 'action' => $this->mAction
=== false ?
$this->getTitle()->getFullURL() : $this->mAction
,
634 'method' => $this->mMethod
,
635 'class' => 'visualClear',
636 'enctype' => $encType,
638 if ( !empty( $this->mId
) ) {
639 $attribs['id'] = $this->mId
;
642 return Html
::rawElement( 'form', $attribs, $html );
646 * Get the hidden fields that should go inside the form.
647 * @return String HTML.
649 function getHiddenFields() {
650 global $wgArticlePath;
653 if ( $this->getMethod() == 'post' ) {
654 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
655 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
658 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
659 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
662 foreach ( $this->mHiddenFields
as $data ) {
663 list( $value, $attribs ) = $data;
664 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
671 * Get the submit and (potentially) reset buttons.
672 * @return String HTML.
674 function getButtons() {
678 if ( isset( $this->mSubmitID
) ) {
679 $attribs['id'] = $this->mSubmitID
;
682 if ( isset( $this->mSubmitName
) ) {
683 $attribs['name'] = $this->mSubmitName
;
686 if ( isset( $this->mSubmitTooltip
) ) {
687 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
690 $attribs['class'] = 'mw-htmlform-submit';
692 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
694 if ( $this->mShowReset
) {
695 $html .= Html
::element(
699 'value' => wfMsg( 'htmlform-reset' )
704 foreach ( $this->mButtons
as $button ) {
707 'name' => $button['name'],
708 'value' => $button['value']
711 if ( $button['attribs'] ) {
712 $attrs +
= $button['attribs'];
715 if ( isset( $button['id'] ) ) {
716 $attrs['id'] = $button['id'];
719 $html .= Html
::element( 'input', $attrs );
726 * Get the whole body of the form.
730 return $this->displaySection( $this->mFieldTree
);
734 * Format and display an error message stack.
735 * @param $errors String|Array|Status
738 function getErrors( $errors ) {
739 if ( $errors instanceof Status
) {
740 if ( $errors->isOK() ) {
743 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
745 } elseif ( is_array( $errors ) ) {
746 $errorstr = $this->formatErrors( $errors );
752 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
757 * Format a stack of error messages into a single HTML string
758 * @param $errors Array of message keys/values
759 * @return String HTML, a "<ul>" list of errors
761 public static function formatErrors( $errors ) {
764 foreach ( $errors as $error ) {
765 if ( is_array( $error ) ) {
766 $msg = array_shift( $error );
772 $errorstr .= Html
::rawElement(
775 wfMsgExt( $msg, array( 'parseinline' ), $error )
779 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
785 * Set the text for the submit button
786 * @param $t String plaintext.
787 * @return HTMLForm $this for chaining calls (since 1.20)
789 function setSubmitText( $t ) {
790 $this->mSubmitText
= $t;
795 * Set the text for the submit button to a message
797 * @param $msg String message key
798 * @return HTMLForm $this for chaining calls (since 1.20)
800 public function setSubmitTextMsg( $msg ) {
801 $this->setSubmitText( $this->msg( $msg )->text() );
806 * Get the text for the submit button, either customised or a default.
809 function getSubmitText() {
810 return $this->mSubmitText
812 : wfMsg( 'htmlform-submit' );
816 * @param $name String Submit button name
817 * @return HTMLForm $this for chaining calls (since 1.20)
819 public function setSubmitName( $name ) {
820 $this->mSubmitName
= $name;
825 * @param $name String Tooltip for the submit button
826 * @return HTMLForm $this for chaining calls (since 1.20)
828 public function setSubmitTooltip( $name ) {
829 $this->mSubmitTooltip
= $name;
834 * Set the id for the submit button.
836 * @todo FIXME: Integrity of $t is *not* validated
837 * @return HTMLForm $this for chaining calls (since 1.20)
839 function setSubmitID( $t ) {
840 $this->mSubmitID
= $t;
845 * @param $id String DOM id for the form
846 * @return HTMLForm $this for chaining calls (since 1.20)
848 public function setId( $id ) {
853 * Prompt the whole form to be wrapped in a "<fieldset>", with
854 * this text as its "<legend>" element.
855 * @param $legend String HTML to go inside the "<legend>" element.
857 * @return HTMLForm $this for chaining calls (since 1.20)
859 public function setWrapperLegend( $legend ) {
860 $this->mWrapperLegend
= $legend;
865 * Prompt the whole form to be wrapped in a "<fieldset>", with
866 * this message as its "<legend>" element.
868 * @param $msg String message key
869 * @return HTMLForm $this for chaining calls (since 1.20)
871 public function setWrapperLegendMsg( $msg ) {
872 $this->setWrapperLegend( $this->msg( $msg )->escaped() );
877 * Set the prefix for various default messages
878 * @todo currently only used for the "<fieldset>" legend on forms
879 * with multiple sections; should be used elsewhre?
881 * @return HTMLForm $this for chaining calls (since 1.20)
883 function setMessagePrefix( $p ) {
884 $this->mMessagePrefix
= $p;
889 * Set the title for form submission
890 * @param $t Title of page the form is on/should be posted to
891 * @return HTMLForm $this for chaining calls (since 1.20)
893 function setTitle( $t ) {
902 function getTitle() {
903 return $this->mTitle
=== false
904 ?
$this->getContext()->getTitle()
909 * Set the method used to submit the form
910 * @param $method String
911 * @return HTMLForm $this for chaining calls (since 1.20)
913 public function setMethod( $method = 'post' ) {
914 $this->mMethod
= $method;
918 public function getMethod() {
919 return $this->mMethod
;
924 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
925 * @param $sectionName string ID attribute of the "<table>" tag for this section, ignored if empty
926 * @param $fieldsetIDPrefix string ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
929 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
930 $displayFormat = $this->getDisplayFormat();
933 $subsectionHtml = '';
936 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ?
'getTableRow' : 'get' . ucfirst( $displayFormat );
938 foreach ( $fields as $key => $value ) {
939 if ( $value instanceof HTMLFormField
) {
940 $v = empty( $value->mParams
['nodata'] )
941 ?
$this->mFieldData
[$key]
942 : $value->getDefault();
943 $html .= $value->$getFieldHtmlMethod( $v );
945 $labelValue = trim( $value->getLabel() );
946 if ( $labelValue != ' ' && $labelValue !== '' ) {
949 } elseif ( is_array( $value ) ) {
950 $section = $this->displaySection( $value, $key );
951 $legend = $this->getLegend( $key );
952 if ( isset( $this->mSectionHeaders
[$key] ) ) {
953 $section = $this->mSectionHeaders
[$key] . $section;
955 if ( isset( $this->mSectionFooters
[$key] ) ) {
956 $section .= $this->mSectionFooters
[$key];
958 $attributes = array();
959 if ( $fieldsetIDPrefix ) {
960 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
962 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
966 if ( $displayFormat !== 'raw' ) {
969 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
970 $classes[] = 'mw-htmlform-nolabel';
974 'class' => implode( ' ', $classes ),
977 if ( $sectionName ) {
978 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
981 if ( $displayFormat === 'table' ) {
982 $html = Html
::rawElement( 'table', $attribs,
983 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
984 } elseif ( $displayFormat === 'div' ) {
985 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
989 if ( $this->mSubSectionBeforeFields
) {
990 return $subsectionHtml . "\n" . $html;
992 return $html . "\n" . $subsectionHtml;
997 * Construct the form fields from the Descriptor array
999 function loadData() {
1000 $fieldData = array();
1002 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1003 if ( !empty( $field->mParams
['nodata'] ) ) {
1005 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1006 $fieldData[$fieldname] = $field->getDefault();
1008 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1013 foreach ( $fieldData as $name => &$value ) {
1014 $field = $this->mFlatFields
[$name];
1015 $value = $field->filter( $value, $this->mFlatFields
);
1018 $this->mFieldData
= $fieldData;
1022 * Stop a reset button being shown for this form
1023 * @param $suppressReset Bool set to false to re-enable the
1025 * @return HTMLForm $this for chaining calls (since 1.20)
1027 function suppressReset( $suppressReset = true ) {
1028 $this->mShowReset
= !$suppressReset;
1033 * Overload this if you want to apply special filtration routines
1034 * to the form as a whole, after it's submitted but before it's
1039 function filterDataForSubmit( $data ) {
1044 * Get a string to go in the "<legend>" of a section fieldset.
1045 * Override this if you want something more complicated.
1046 * @param $key String
1049 public function getLegend( $key ) {
1050 return wfMsg( "{$this->mMessagePrefix}-$key" );
1054 * Set the value for the action attribute of the form.
1055 * When set to false (which is the default state), the set title is used.
1059 * @param string|bool $action
1060 * @return HTMLForm $this for chaining calls (since 1.20)
1062 public function setAction( $action ) {
1063 $this->mAction
= $action;
1070 * The parent class to generate form fields. Any field type should
1071 * be a subclass of this.
1073 abstract class HTMLFormField
{
1075 protected $mValidationCallback;
1076 protected $mFilterCallback;
1079 protected $mLabel; # String label. Set on construction
1081 protected $mClass = '';
1082 protected $mDefault;
1090 * This function must be implemented to return the HTML to generate
1091 * the input object itself. It should not implement the surrounding
1092 * table cells/rows, or labels/help messages.
1093 * @param $value String the value to set the input to; eg a default
1094 * text for a text input.
1095 * @return String valid HTML.
1097 abstract function getInputHTML( $value );
1100 * Override this function to add specific validation checks on the
1101 * field input. Don't forget to call parent::validate() to ensure
1102 * that the user-defined callback mValidationCallback is still run
1103 * @param $value String the value the field was submitted with
1104 * @param $alldata Array the data collected from the form
1105 * @return Mixed Bool true on success, or String error to display.
1107 function validate( $value, $alldata ) {
1108 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
1109 return wfMsgExt( 'htmlform-required', 'parseinline' );
1112 if ( isset( $this->mValidationCallback
) ) {
1113 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
1119 function filter( $value, $alldata ) {
1120 if ( isset( $this->mFilterCallback
) ) {
1121 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
1128 * Should this field have a label, or is there no input element with the
1129 * appropriate id for the label to point to?
1131 * @return bool True to output a label, false to suppress
1133 protected function needsLabel() {
1138 * Get the value that this input has been set to from a posted form,
1139 * or the input's default value if it has not been set.
1140 * @param $request WebRequest
1141 * @return String the value
1143 function loadDataFromRequest( $request ) {
1144 if ( $request->getCheck( $this->mName
) ) {
1145 return $request->getText( $this->mName
);
1147 return $this->getDefault();
1152 * Initialise the object
1153 * @param $params array Associative Array. See HTMLForm doc for syntax.
1155 function __construct( $params ) {
1156 $this->mParams
= $params;
1158 # Generate the label from a message, if possible
1159 if ( isset( $params['label-message'] ) ) {
1160 $msgInfo = $params['label-message'];
1162 if ( is_array( $msgInfo ) ) {
1163 $msg = array_shift( $msgInfo );
1169 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
1170 } elseif ( isset( $params['label'] ) ) {
1171 $this->mLabel
= $params['label'];
1174 $this->mName
= "wp{$params['fieldname']}";
1175 if ( isset( $params['name'] ) ) {
1176 $this->mName
= $params['name'];
1179 $validName = Sanitizer
::escapeId( $this->mName
);
1180 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1181 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1184 $this->mID
= "mw-input-{$this->mName}";
1186 if ( isset( $params['default'] ) ) {
1187 $this->mDefault
= $params['default'];
1190 if ( isset( $params['id'] ) ) {
1191 $id = $params['id'];
1192 $validId = Sanitizer
::escapeId( $id );
1194 if ( $id != $validId ) {
1195 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1201 if ( isset( $params['cssclass'] ) ) {
1202 $this->mClass
= $params['cssclass'];
1205 if ( isset( $params['validation-callback'] ) ) {
1206 $this->mValidationCallback
= $params['validation-callback'];
1209 if ( isset( $params['filter-callback'] ) ) {
1210 $this->mFilterCallback
= $params['filter-callback'];
1213 if ( isset( $params['flatlist'] ) ) {
1214 $this->mClass
.= ' mw-htmlform-flatlist';
1219 * Get the complete table row for the input, including help text,
1220 * labels, and whatever.
1221 * @param $value String the value to set the input to.
1222 * @return String complete HTML table row.
1224 function getTableRow( $value ) {
1225 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1226 $inputHtml = $this->getInputHTML( $value );
1227 $fieldType = get_class( $this );
1228 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1229 $cellAttributes = array();
1231 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1232 $cellAttributes['colspan'] = 2;
1233 $verticalLabel = true;
1235 $verticalLabel = false;
1238 $label = $this->getLabelHtml( $cellAttributes );
1240 $field = Html
::rawElement(
1242 array( 'class' => 'mw-input' ) +
$cellAttributes,
1243 $inputHtml . "\n$errors"
1246 if ( $verticalLabel ) {
1247 $html = Html
::rawElement( 'tr',
1248 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1249 $html .= Html
::rawElement( 'tr',
1250 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1253 $html = Html
::rawElement( 'tr',
1254 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1258 return $html . $helptext;
1262 * Get the complete div for the input, including help text,
1263 * labels, and whatever.
1265 * @param $value String the value to set the input to.
1266 * @return String complete HTML table row.
1268 public function getDiv( $value ) {
1269 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1270 $inputHtml = $this->getInputHTML( $value );
1271 $fieldType = get_class( $this );
1272 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1273 $cellAttributes = array();
1274 $label = $this->getLabelHtml( $cellAttributes );
1276 $field = Html
::rawElement(
1278 array( 'class' => 'mw-input' ) +
$cellAttributes,
1279 $inputHtml . "\n$errors"
1281 $html = Html
::rawElement( 'div',
1282 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1289 * Get the complete raw fields for the input, including help text,
1290 * labels, and whatever.
1292 * @param $value String the value to set the input to.
1293 * @return String complete HTML table row.
1295 public function getRaw( $value ) {
1296 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1297 $inputHtml = $this->getInputHTML( $value );
1298 $fieldType = get_class( $this );
1299 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1300 $cellAttributes = array();
1301 $label = $this->getLabelHtml( $cellAttributes );
1303 $html = "\n$errors";
1305 $html .= $inputHtml;
1311 * Generate help text HTML in table format
1313 * @param $helptext String|null
1316 public function getHelpTextHtmlTable( $helptext ) {
1317 if ( is_null( $helptext ) ) {
1321 $row = Html
::rawElement(
1323 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1326 $row = Html
::rawElement( 'tr', array(), $row );
1331 * Generate help text HTML in div format
1333 * @param $helptext String|null
1336 public function getHelpTextHtmlDiv( $helptext ) {
1337 if ( is_null( $helptext ) ) {
1341 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1346 * Generate help text HTML formatted for raw output
1348 * @param $helptext String|null
1351 public function getHelpTextHtmlRaw( $helptext ) {
1352 return $this->getHelpTextHtmlDiv( $helptext );
1356 * Determine the help text to display
1360 public function getHelpText() {
1363 if ( isset( $this->mParams
['help-message'] ) ) {
1364 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1367 if ( isset( $this->mParams
['help-messages'] ) ) {
1368 foreach ( $this->mParams
['help-messages'] as $name ) {
1369 $helpMessage = (array)$name;
1370 $msg = wfMessage( array_shift( $helpMessage ), $helpMessage );
1372 if ( $msg->exists() ) {
1373 if ( is_null( $helptext ) ) {
1376 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1378 $helptext .= $msg->parse(); // Append message
1382 elseif ( isset( $this->mParams
['help'] ) ) {
1383 $helptext = $this->mParams
['help'];
1389 * Determine form errors to display and their classes
1391 * @param $value String the value of the input
1394 public function getErrorsAndErrorClass( $value ) {
1395 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1397 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1401 $errors = self
::formatErrors( $errors );
1402 $errorClass = 'mw-htmlform-invalid-input';
1404 return array( $errors, $errorClass );
1407 function getLabel() {
1408 return $this->mLabel
;
1411 function getLabelHtml( $cellAttributes = array() ) {
1412 # Don't output a for= attribute for labels with no associated input.
1413 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1416 if ( $this->needsLabel() ) {
1417 $for['for'] = $this->mID
;
1420 $displayFormat = $this->mParent
->getDisplayFormat();
1421 $labelElement = Html
::rawElement( 'label', $for, $this->getLabel() );
1423 if ( $displayFormat == 'table' ) {
1424 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1425 Html
::rawElement( 'label', $for, $this->getLabel() )
1427 } elseif ( $displayFormat == 'div' ) {
1428 return Html
::rawElement( 'div', array( 'class' => 'mw-label' ) +
$cellAttributes,
1429 Html
::rawElement( 'label', $for, $this->getLabel() )
1432 return $labelElement;
1436 function getDefault() {
1437 if ( isset( $this->mDefault
) ) {
1438 return $this->mDefault
;
1445 * Returns the attributes required for the tooltip and accesskey.
1447 * @return array Attributes
1449 public function getTooltipAndAccessKey() {
1450 if ( empty( $this->mParams
['tooltip'] ) ) {
1453 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1457 * flatten an array of options to a single array, for instance,
1458 * a set of "<options>" inside "<optgroups>".
1459 * @param $options array Associative Array with values either Strings
1461 * @return Array flattened input
1463 public static function flattenOptions( $options ) {
1464 $flatOpts = array();
1466 foreach ( $options as $value ) {
1467 if ( is_array( $value ) ) {
1468 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1470 $flatOpts[] = $value;
1478 * Formats one or more errors as accepted by field validation-callback.
1479 * @param $errors String|Message|Array of strings or Message instances
1480 * @return String html
1483 protected static function formatErrors( $errors ) {
1484 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1485 $errors = array_shift( $errors );
1488 if ( is_array( $errors ) ) {
1490 foreach ( $errors as $error ) {
1491 if ( $error instanceof Message
) {
1492 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1494 $lines[] = Html
::rawElement( 'li', array(), $error );
1497 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1499 if ( $errors instanceof Message
) {
1500 $errors = $errors->parse();
1502 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1507 class HTMLTextField
extends HTMLFormField
{
1508 function getSize() {
1509 return isset( $this->mParams
['size'] )
1510 ?
$this->mParams
['size']
1514 function getInputHTML( $value ) {
1517 'name' => $this->mName
,
1518 'size' => $this->getSize(),
1520 ) +
$this->getTooltipAndAccessKey();
1522 if ( $this->mClass
!== '' ) {
1523 $attribs['class'] = $this->mClass
;
1526 if ( isset( $this->mParams
['maxlength'] ) ) {
1527 $attribs['maxlength'] = $this->mParams
['maxlength'];
1530 if ( !empty( $this->mParams
['disabled'] ) ) {
1531 $attribs['disabled'] = 'disabled';
1534 # TODO: Enforce pattern, step, required, readonly on the server side as
1536 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1537 'placeholder' ) as $param ) {
1538 if ( isset( $this->mParams
[$param] ) ) {
1539 $attribs[$param] = $this->mParams
[$param];
1543 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1544 if ( isset( $this->mParams
[$param] ) ) {
1545 $attribs[$param] = '';
1549 # Implement tiny differences between some field variants
1550 # here, rather than creating a new class for each one which
1551 # is essentially just a clone of this one.
1552 if ( isset( $this->mParams
['type'] ) ) {
1553 switch ( $this->mParams
['type'] ) {
1555 $attribs['type'] = 'email';
1558 $attribs['type'] = 'number';
1561 $attribs['type'] = 'number';
1562 $attribs['step'] = 'any';
1567 $attribs['type'] = $this->mParams
['type'];
1572 return Html
::element( 'input', $attribs );
1575 class HTMLTextAreaField
extends HTMLFormField
{
1576 function getCols() {
1577 return isset( $this->mParams
['cols'] )
1578 ?
$this->mParams
['cols']
1582 function getRows() {
1583 return isset( $this->mParams
['rows'] )
1584 ?
$this->mParams
['rows']
1588 function getInputHTML( $value ) {
1591 'name' => $this->mName
,
1592 'cols' => $this->getCols(),
1593 'rows' => $this->getRows(),
1594 ) +
$this->getTooltipAndAccessKey();
1596 if ( $this->mClass
!== '' ) {
1597 $attribs['class'] = $this->mClass
;
1600 if ( !empty( $this->mParams
['disabled'] ) ) {
1601 $attribs['disabled'] = 'disabled';
1604 if ( !empty( $this->mParams
['readonly'] ) ) {
1605 $attribs['readonly'] = 'readonly';
1608 if ( isset( $this->mParams
['placeholder'] ) ) {
1609 $attribs['placeholder'] = $this->mParams
['placeholder'];
1612 foreach ( array( 'required', 'autofocus' ) as $param ) {
1613 if ( isset( $this->mParams
[$param] ) ) {
1614 $attribs[$param] = '';
1618 return Html
::element( 'textarea', $attribs, $value );
1623 * A field that will contain a numeric value
1625 class HTMLFloatField
extends HTMLTextField
{
1626 function getSize() {
1627 return isset( $this->mParams
['size'] )
1628 ?
$this->mParams
['size']
1632 function validate( $value, $alldata ) {
1633 $p = parent
::validate( $value, $alldata );
1635 if ( $p !== true ) {
1639 $value = trim( $value );
1641 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1642 # with the addition that a leading '+' sign is ok.
1643 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1644 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1647 # The "int" part of these message names is rather confusing.
1648 # They make equal sense for all numbers.
1649 if ( isset( $this->mParams
['min'] ) ) {
1650 $min = $this->mParams
['min'];
1652 if ( $min > $value ) {
1653 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1657 if ( isset( $this->mParams
['max'] ) ) {
1658 $max = $this->mParams
['max'];
1660 if ( $max < $value ) {
1661 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1670 * A field that must contain a number
1672 class HTMLIntField
extends HTMLFloatField
{
1673 function validate( $value, $alldata ) {
1674 $p = parent
::validate( $value, $alldata );
1676 if ( $p !== true ) {
1680 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1681 # with the addition that a leading '+' sign is ok. Note that leading zeros
1682 # are fine, and will be left in the input, which is useful for things like
1683 # phone numbers when you know that they are integers (the HTML5 type=tel
1684 # input does not require its value to be numeric). If you want a tidier
1685 # value to, eg, save in the DB, clean it up with intval().
1686 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1688 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1698 class HTMLCheckField
extends HTMLFormField
{
1699 function getInputHTML( $value ) {
1700 if ( !empty( $this->mParams
['invert'] ) ) {
1704 $attr = $this->getTooltipAndAccessKey();
1705 $attr['id'] = $this->mID
;
1707 if ( !empty( $this->mParams
['disabled'] ) ) {
1708 $attr['disabled'] = 'disabled';
1711 if ( $this->mClass
!== '' ) {
1712 $attr['class'] = $this->mClass
;
1715 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1716 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1720 * For a checkbox, the label goes on the right hand side, and is
1721 * added in getInputHTML(), rather than HTMLFormField::getRow()
1724 function getLabel() {
1729 * @param $request WebRequest
1732 function loadDataFromRequest( $request ) {
1734 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1738 // GetCheck won't work like we want for checks.
1739 // Fetch the value in either one of the two following case:
1740 // - we have a valid token (form got posted or GET forged by the user)
1741 // - checkbox name has a value (false or true), ie is not null
1742 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1743 // XOR has the following truth table, which is what we want
1744 // INVERT VALUE | OUTPUT
1745 // true true | false
1746 // false true | true
1747 // false false | false
1748 // true false | true
1749 return $request->getBool( $this->mName
) xor $invert;
1751 return $this->getDefault();
1757 * A select dropdown field. Basically a wrapper for Xmlselect class
1759 class HTMLSelectField
extends HTMLFormField
{
1760 function validate( $value, $alldata ) {
1761 $p = parent
::validate( $value, $alldata );
1763 if ( $p !== true ) {
1767 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1769 if ( in_array( $value, $validOptions ) )
1772 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1775 function getInputHTML( $value ) {
1776 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1778 # If one of the options' 'name' is int(0), it is automatically selected.
1779 # because PHP sucks and thinks int(0) == 'some string'.
1780 # Working around this by forcing all of them to strings.
1781 foreach ( $this->mParams
['options'] as &$opt ) {
1782 if ( is_int( $opt ) ) {
1783 $opt = strval( $opt );
1786 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1788 if ( !empty( $this->mParams
['disabled'] ) ) {
1789 $select->setAttribute( 'disabled', 'disabled' );
1792 if ( $this->mClass
!== '' ) {
1793 $select->setAttribute( 'class', $this->mClass
);
1796 $select->addOptions( $this->mParams
['options'] );
1798 return $select->getHTML();
1803 * Select dropdown field, with an additional "other" textbox.
1805 class HTMLSelectOrOtherField
extends HTMLTextField
{
1806 static $jsAdded = false;
1808 function __construct( $params ) {
1809 if ( !in_array( 'other', $params['options'], true ) ) {
1810 $msg = isset( $params['other'] ) ?
$params['other'] : wfMsg( 'htmlform-selectorother-other' );
1811 $params['options'][$msg] = 'other';
1814 parent
::__construct( $params );
1817 static function forceToStringRecursive( $array ) {
1818 if ( is_array( $array ) ) {
1819 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1821 return strval( $array );
1825 function getInputHTML( $value ) {
1826 $valInSelect = false;
1828 if ( $value !== false ) {
1829 $valInSelect = in_array(
1831 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1835 $selected = $valInSelect ?
$value : 'other';
1837 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1839 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1840 $select->addOptions( $opts );
1842 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1844 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1846 if ( !empty( $this->mParams
['disabled'] ) ) {
1847 $select->setAttribute( 'disabled', 'disabled' );
1848 $tbAttribs['disabled'] = 'disabled';
1851 $select = $select->getHTML();
1853 if ( isset( $this->mParams
['maxlength'] ) ) {
1854 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1857 if ( $this->mClass
!== '' ) {
1858 $tbAttribs['class'] = $this->mClass
;
1861 $textbox = Html
::input(
1862 $this->mName
. '-other',
1863 $valInSelect ?
'' : $value,
1868 return "$select<br />\n$textbox";
1872 * @param $request WebRequest
1875 function loadDataFromRequest( $request ) {
1876 if ( $request->getCheck( $this->mName
) ) {
1877 $val = $request->getText( $this->mName
);
1879 if ( $val == 'other' ) {
1880 $val = $request->getText( $this->mName
. '-other' );
1885 return $this->getDefault();
1891 * Multi-select field
1893 class HTMLMultiSelectField
extends HTMLFormField
{
1895 function validate( $value, $alldata ) {
1896 $p = parent
::validate( $value, $alldata );
1898 if ( $p !== true ) {
1902 if ( !is_array( $value ) ) {
1906 # If all options are valid, array_intersect of the valid options
1907 # and the provided options will return the provided options.
1908 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1910 $validValues = array_intersect( $value, $validOptions );
1911 if ( count( $validValues ) == count( $value ) ) {
1914 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1918 function getInputHTML( $value ) {
1919 $html = $this->formatOptions( $this->mParams
['options'], $value );
1924 function formatOptions( $options, $value ) {
1929 if ( !empty( $this->mParams
['disabled'] ) ) {
1930 $attribs['disabled'] = 'disabled';
1933 foreach ( $options as $label => $info ) {
1934 if ( is_array( $info ) ) {
1935 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1936 $html .= $this->formatOptions( $info, $value );
1938 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1940 $checkbox = Xml
::check(
1941 $this->mName
. '[]',
1942 in_array( $info, $value, true ),
1943 $attribs +
$thisAttribs );
1944 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1946 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1954 * @param $request WebRequest
1957 function loadDataFromRequest( $request ) {
1958 if ( $this->mParent
->getMethod() == 'post' ) {
1959 if ( $request->wasPosted() ) {
1960 # Checkboxes are just not added to the request arrays if they're not checked,
1961 # so it's perfectly possible for there not to be an entry at all
1962 return $request->getArray( $this->mName
, array() );
1964 # That's ok, the user has not yet submitted the form, so show the defaults
1965 return $this->getDefault();
1968 # This is the impossible case: if we look at $_GET and see no data for our
1969 # field, is it because the user has not yet submitted the form, or that they
1970 # have submitted it with all the options unchecked? We will have to assume the
1971 # latter, which basically means that you can't specify 'positive' defaults
1974 return $request->getArray( $this->mName
, array() );
1978 function getDefault() {
1979 if ( isset( $this->mDefault
) ) {
1980 return $this->mDefault
;
1986 protected function needsLabel() {
1992 * Double field with a dropdown list constructed from a system message in the format
1995 * * New Optgroup header
1996 * Plus a text field underneath for an additional reason. The 'value' of the field is
1997 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
1999 * @todo FIXME: If made 'required', only the text field should be compulsory.
2001 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2003 function __construct( $params ) {
2004 if ( array_key_exists( 'other', $params ) ) {
2005 } elseif ( array_key_exists( 'other-message', $params ) ) {
2006 $params['other'] = wfMessage( $params['other-message'] )->plain();
2008 $params['other'] = null;
2011 if ( array_key_exists( 'options', $params ) ) {
2012 # Options array already specified
2013 } elseif ( array_key_exists( 'options-message', $params ) ) {
2014 # Generate options array from a system message
2015 $params['options'] = self
::parseMessage(
2016 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2021 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2023 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2025 parent
::__construct( $params );
2029 * Build a drop-down box from a textual list.
2030 * @param $string String message text
2031 * @param $otherName String name of "other reason" option
2033 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2035 public static function parseMessage( $string, $otherName = null ) {
2036 if ( $otherName === null ) {
2037 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2041 $options = array( $otherName => 'other' );
2043 foreach ( explode( "\n", $string ) as $option ) {
2044 $value = trim( $option );
2045 if ( $value == '' ) {
2047 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2048 # A new group is starting...
2049 $value = trim( substr( $value, 1 ) );
2051 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2053 $opt = trim( substr( $value, 2 ) );
2054 if ( $optgroup === false ) {
2055 $options[$opt] = $opt;
2057 $options[$optgroup][$opt] = $opt;
2060 # groupless reason list
2062 $options[$option] = $option;
2069 function getInputHTML( $value ) {
2070 $select = parent
::getInputHTML( $value[1] );
2072 $textAttribs = array(
2073 'id' => $this->mID
. '-other',
2074 'size' => $this->getSize(),
2077 if ( $this->mClass
!== '' ) {
2078 $textAttribs['class'] = $this->mClass
;
2081 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2082 if ( isset( $this->mParams
[$param] ) ) {
2083 $textAttribs[$param] = '';
2087 $textbox = Html
::input(
2088 $this->mName
. '-other',
2094 return "$select<br />\n$textbox";
2098 * @param $request WebRequest
2099 * @return Array("<overall message>","<select value>","<text field value>")
2101 function loadDataFromRequest( $request ) {
2102 if ( $request->getCheck( $this->mName
) ) {
2104 $list = $request->getText( $this->mName
);
2105 $text = $request->getText( $this->mName
. '-other' );
2107 if ( $list == 'other' ) {
2109 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2110 # User has spoofed the select form to give an option which wasn't
2111 # in the original offer. Sulk...
2113 } elseif ( $text == '' ) {
2116 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
2120 $final = $this->getDefault();
2124 foreach ( $this->mFlatOptions
as $option ) {
2125 $match = $option . wfMsgForContent( 'colon-separator' );
2126 if ( strpos( $text, $match ) === 0 ) {
2128 $text = substr( $text, strlen( $match ) );
2133 return array( $final, $list, $text );
2136 function getSize() {
2137 return isset( $this->mParams
['size'] )
2138 ?
$this->mParams
['size']
2142 function validate( $value, $alldata ) {
2143 # HTMLSelectField forces $value to be one of the options in the select
2144 # field, which is not useful here. But we do want the validation further up
2146 $p = parent
::validate( $value[1], $alldata );
2148 if ( $p !== true ) {
2152 if ( isset( $this->mParams
['required'] ) && $value[1] === '' ) {
2153 return wfMsgExt( 'htmlform-required', 'parseinline' );
2161 * Radio checkbox fields.
2163 class HTMLRadioField
extends HTMLFormField
{
2166 function validate( $value, $alldata ) {
2167 $p = parent
::validate( $value, $alldata );
2169 if ( $p !== true ) {
2173 if ( !is_string( $value ) && !is_int( $value ) ) {
2177 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2179 if ( in_array( $value, $validOptions ) ) {
2182 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
2187 * This returns a block of all the radio options, in one cell.
2188 * @see includes/HTMLFormField#getInputHTML()
2189 * @param $value String
2192 function getInputHTML( $value ) {
2193 $html = $this->formatOptions( $this->mParams
['options'], $value );
2198 function formatOptions( $options, $value ) {
2202 if ( !empty( $this->mParams
['disabled'] ) ) {
2203 $attribs['disabled'] = 'disabled';
2206 # TODO: should this produce an unordered list perhaps?
2207 foreach ( $options as $label => $info ) {
2208 if ( is_array( $info ) ) {
2209 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2210 $html .= $this->formatOptions( $info, $value );
2212 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2213 $radio = Xml
::radio(
2217 $attribs +
array( 'id' => $id )
2219 $radio .= ' ' .
2220 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2222 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2229 protected function needsLabel() {
2235 * An information field (text blob), not a proper input.
2237 class HTMLInfoField
extends HTMLFormField
{
2238 public function __construct( $info ) {
2239 $info['nodata'] = true;
2241 parent
::__construct( $info );
2244 public function getInputHTML( $value ) {
2245 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2248 public function getTableRow( $value ) {
2249 if ( !empty( $this->mParams
['rawrow'] ) ) {
2253 return parent
::getTableRow( $value );
2259 public function getDiv( $value ) {
2260 if ( !empty( $this->mParams
['rawrow'] ) ) {
2264 return parent
::getDiv( $value );
2270 public function getRaw( $value ) {
2271 if ( !empty( $this->mParams
['rawrow'] ) ) {
2275 return parent
::getRaw( $value );
2278 protected function needsLabel() {
2283 class HTMLHiddenField
extends HTMLFormField
{
2284 public function __construct( $params ) {
2285 parent
::__construct( $params );
2287 # Per HTML5 spec, hidden fields cannot be 'required'
2288 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2289 unset( $this->mParams
['required'] );
2292 public function getTableRow( $value ) {
2295 $params['id'] = $this->mID
;
2298 $this->mParent
->addHiddenField(
2310 public function getDiv( $value ) {
2311 return $this->getTableRow( $value );
2317 public function getRaw( $value ) {
2318 return $this->getTableRow( $value );
2321 public function getInputHTML( $value ) { return ''; }
2325 * Add a submit button inline in the form (as opposed to
2326 * HTMLForm::addButton(), which will add it at the end).
2328 class HTMLSubmitField
extends HTMLFormField
{
2330 public function __construct( $info ) {
2331 $info['nodata'] = true;
2332 parent
::__construct( $info );
2335 public function getInputHTML( $value ) {
2336 return Xml
::submitButton(
2339 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2340 'name' => $this->mName
,
2346 protected function needsLabel() {
2351 * Button cannot be invalid
2352 * @param $value String
2353 * @param $alldata Array
2356 public function validate( $value, $alldata ) {
2361 class HTMLEditTools
extends HTMLFormField
{
2362 public function getInputHTML( $value ) {
2366 public function getTableRow( $value ) {
2367 $msg = $this->formatMsg();
2369 return '<tr><td></td><td class="mw-input">'
2370 . '<div class="mw-editTools">'
2371 . $msg->parseAsBlock()
2372 . "</div></td></tr>\n";
2378 public function getDiv( $value ) {
2379 $msg = $this->formatMsg();
2380 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2386 public function getRaw( $value ) {
2387 return $this->getDiv( $value );
2390 protected function formatMsg() {
2391 if ( empty( $this->mParams
['message'] ) ) {
2392 $msg = wfMessage( 'edittools' );
2394 $msg = wfMessage( $this->mParams
['message'] );
2395 if ( $msg->isDisabled() ) {
2396 $msg = wfMessage( 'edittools' );
2399 $msg->inContentLanguage();