3 * Object handling generic submission, CSRF protection, layout and
4 * other logic for UI forms. in a reusable manner.
6 * In order to generate the form, the HTMLForm object takes an array
7 * structure detailing the form fields available. Each element of the
8 * array is a basic property-list, including the type of field, the
9 * label it is to be given in the form, callbacks for validation and
10 * 'filtering', and other pertinent information.
12 * Field types are implemented as subclasses of the generic HTMLFormField
13 * object, and typically implement at least getInputHTML, which generates
14 * the HTML for the input field to be placed in the table.
16 * The constructor input is an associative array of $fieldname => $info,
17 * where $info is an Associative Array with any of the following:
19 * 'class' -- the subclass of HTMLFormField that will be used
20 * to create the object. *NOT* the CSS class!
21 * 'type' -- roughly translates into the <select> type attribute.
22 * if 'class' is not specified, this is used as a map
23 * through HTMLForm::$typeMappings to get the class name.
24 * 'default' -- default value when the form is displayed
25 * 'id' -- HTML id attribute
26 * 'cssclass' -- CSS class
27 * 'options' -- varies according to the specific object.
28 * 'label-message' -- message key for a message to use as the label.
29 * can be an array of msg key and then parameters to
31 * 'label' -- alternatively, a raw text message. Overridden by
33 * 'help' -- message text for a message to use as a help text.
34 * 'help-message' -- message key for a message to use as a help text.
35 * can be an array of msg key and then parameters to
37 * Overwrites 'help-messages' and 'help'.
38 * 'help-messages' -- array of message key. As above, each item can
39 * be an array of msg key and then parameters.
41 * 'required' -- passed through to the object, indicating that it
42 * is a required field.
43 * 'size' -- the length of text fields
44 * 'filter-callback -- a function name to give you the chance to
45 * massage the inputted value before it's processed.
46 * @see HTMLForm::filter()
47 * 'validation-callback' -- a function name to give you the chance
48 * to impose extra validation on the field input.
49 * @see HTMLForm::validate()
50 * 'name' -- By default, the 'name' attribute of the input field
51 * is "wp{$fieldname}". If you want a different name
52 * (eg one without the "wp" prefix), specify it here and
53 * it will be used without modification.
55 * TODO: Document 'section' / 'subsection' stuff
57 class HTMLForm
extends ContextSource
{
59 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
60 static $typeMappings = array(
61 'text' => 'HTMLTextField',
62 'textarea' => 'HTMLTextAreaField',
63 'select' => 'HTMLSelectField',
64 'radio' => 'HTMLRadioField',
65 'multiselect' => 'HTMLMultiSelectField',
66 'check' => 'HTMLCheckField',
67 'toggle' => 'HTMLCheckField',
68 'int' => 'HTMLIntField',
69 'float' => 'HTMLFloatField',
70 'info' => 'HTMLInfoField',
71 'selectorother' => 'HTMLSelectOrOtherField',
72 'selectandother' => 'HTMLSelectAndOtherField',
73 'submit' => 'HTMLSubmitField',
74 'hidden' => 'HTMLHiddenField',
75 'edittools' => 'HTMLEditTools',
77 // HTMLTextField will output the correct type="" attribute automagically.
78 // There are about four zillion other HTML5 input types, like url, but
79 // we don't use those at the moment, so no point in adding all of them.
80 'email' => 'HTMLTextField',
81 'password' => 'HTMLTextField',
84 protected $mMessagePrefix;
86 /** @var HTMLFormField[] */
87 protected $mFlatFields;
89 protected $mFieldTree;
90 protected $mShowReset = false;
93 protected $mSubmitCallback;
94 protected $mValidationErrorMessage;
97 protected $mHeader = '';
98 protected $mFooter = '';
99 protected $mSectionHeaders = array();
100 protected $mSectionFooters = array();
101 protected $mPost = '';
104 protected $mSubmitID;
105 protected $mSubmitName;
106 protected $mSubmitText;
107 protected $mSubmitTooltip;
110 protected $mMethod = 'post';
113 * Form action URL. false means we will use the URL to set Title
117 protected $mAction = false;
119 protected $mUseMultipart = false;
120 protected $mHiddenFields = array();
121 protected $mButtons = array();
123 protected $mWrapperLegend = false;
126 * If true, sections that contain both fields and subsections will
127 * render their subsections before their fields.
129 * Subclasses may set this to false to render subsections after fields
132 protected $mSubSectionBeforeFields = true;
135 * Format in which to display form. For viable options,
136 * @see $availableDisplayFormats
139 protected $displayFormat = 'table';
142 * Available formats in which to display the form
145 protected $availableDisplayFormats = array(
152 * Build a new HTMLForm from an array of field attributes
153 * @param $descriptor Array of Field constructs, as described above
154 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
155 * Obviates the need to call $form->setTitle()
156 * @param $messagePrefix String a prefix to go in front of default messages
158 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
159 if ( $context instanceof IContextSource
) {
160 $this->setContext( $context );
161 $this->mTitle
= false; // We don't need them to set a title
162 $this->mMessagePrefix
= $messagePrefix;
165 if ( is_string( $context ) && $messagePrefix === '' ) {
166 // it's actually $messagePrefix
167 $this->mMessagePrefix
= $context;
171 // Expand out into a tree.
172 $loadedDescriptor = array();
173 $this->mFlatFields
= array();
175 foreach ( $descriptor as $fieldname => $info ) {
176 $section = isset( $info['section'] )
180 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
181 $this->mUseMultipart
= true;
184 $field = self
::loadInputFromParameters( $fieldname, $info );
185 $field->mParent
= $this;
187 $setSection =& $loadedDescriptor;
189 $sectionParts = explode( '/', $section );
191 while ( count( $sectionParts ) ) {
192 $newName = array_shift( $sectionParts );
194 if ( !isset( $setSection[$newName] ) ) {
195 $setSection[$newName] = array();
198 $setSection =& $setSection[$newName];
202 $setSection[$fieldname] = $field;
203 $this->mFlatFields
[$fieldname] = $field;
206 $this->mFieldTree
= $loadedDescriptor;
210 * Set format in which to display the form
211 * @param $format String the name of the format to use, must be one of
212 * $this->availableDisplayFormats
215 public function setDisplayFormat( $format ) {
216 if ( !in_array( $format, $this->availableDisplayFormats
) ) {
217 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats
, true ) );
219 $this->displayFormat
= $format;
223 * Getter for displayFormat
227 public function getDisplayFormat() {
228 return $this->displayFormat
;
232 * Add the HTMLForm-specific JavaScript, if it hasn't been
234 * @deprecated since 1.18 load modules with ResourceLoader instead
236 static function addJS() { wfDeprecated( __METHOD__
, '1.18' ); }
239 * Initialise a new Object for the field
240 * @param $fieldname string
241 * @param $descriptor string input Descriptor, as described above
242 * @return HTMLFormField subclass
244 static function loadInputFromParameters( $fieldname, $descriptor ) {
245 if ( isset( $descriptor['class'] ) ) {
246 $class = $descriptor['class'];
247 } elseif ( isset( $descriptor['type'] ) ) {
248 $class = self
::$typeMappings[$descriptor['type']];
249 $descriptor['class'] = $class;
255 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
258 $descriptor['fieldname'] = $fieldname;
261 # This will throw a fatal error whenever someone try to use
262 # 'class' to feed a CSS class instead of 'cssclass'. Would be
263 # great to avoid the fatal error and show a nice error.
264 $obj = new $class( $descriptor );
270 * Prepare form for submission
272 function prepareForm() {
273 # Check if we have the info we need
274 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
275 throw new MWException( "You must call setTitle() on an HTMLForm" );
278 # Load data from the request.
283 * Try submitting, with edit token check first
284 * @return Status|boolean
286 function tryAuthorizedSubmit() {
290 if ( $this->getMethod() != 'post' ) {
291 $submit = true; // no session check needed
292 } elseif ( $this->getRequest()->wasPosted() ) {
293 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
294 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
295 // Session tokens for logged-out users have no security value.
296 // However, if the user gave one, check it in order to give a nice
297 // "session expired" error instead of "permission denied" or such.
298 $submit = $this->getUser()->matchEditToken( $editToken );
305 $result = $this->trySubmit();
312 * The here's-one-I-made-earlier option: do the submission if
313 * posted, or display the form with or without funky validation
315 * @return Bool or Status whether submission was successful.
318 $this->prepareForm();
320 $result = $this->tryAuthorizedSubmit();
321 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
325 $this->displayForm( $result );
330 * Validate all the fields, and call the submision callback
331 * function if everything is kosher.
332 * @return Mixed Bool true == Successful submission, Bool false
333 * == No submission attempted, anything else == Error to
336 function trySubmit() {
337 # Check for validation
338 foreach ( $this->mFlatFields
as $fieldname => $field ) {
339 if ( !empty( $field->mParams
['nodata'] ) ) {
342 if ( $field->validate(
343 $this->mFieldData
[$fieldname],
347 return isset( $this->mValidationErrorMessage
)
348 ?
$this->mValidationErrorMessage
349 : array( 'htmlform-invalid-input' );
353 $callback = $this->mSubmitCallback
;
355 $data = $this->filterDataForSubmit( $this->mFieldData
);
357 $res = call_user_func( $callback, $data, $this );
363 * Set a callback to a function to do something with the form
364 * once it's been successfully validated.
365 * @param $cb String function name. The function will be passed
366 * the output from HTMLForm::filterDataForSubmit, and must
367 * return Bool true on success, Bool false if no submission
368 * was attempted, or String HTML output to display on error.
370 function setSubmitCallback( $cb ) {
371 $this->mSubmitCallback
= $cb;
375 * Set a message to display on a validation error.
376 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
377 * (so each entry can be either a String or Array)
379 function setValidationErrorMessage( $msg ) {
380 $this->mValidationErrorMessage
= $msg;
384 * Set the introductory message, overwriting any existing message.
385 * @param $msg String complete text of message to display
387 function setIntro( $msg ) {
388 $this->setPreText( $msg );
392 * Set the introductory message, overwriting any existing message.
394 * @param $msg String complete text of message to display
396 function setPreText( $msg ) { $this->mPre
= $msg; }
399 * Add introductory text.
400 * @param $msg String complete text of message to display
402 function addPreText( $msg ) { $this->mPre
.= $msg; }
405 * Add header text, inside the form.
406 * @param $msg String complete text of message to display
407 * @param $section string The section to add the header to
409 function addHeaderText( $msg, $section = null ) {
410 if ( is_null( $section ) ) {
411 $this->mHeader
.= $msg;
413 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
414 $this->mSectionHeaders
[$section] = '';
416 $this->mSectionHeaders
[$section] .= $msg;
421 * Set header text, inside the form.
423 * @param $msg String complete text of message to display
424 * @param $section The section to add the header to
426 function setHeaderText( $msg, $section = null ) {
427 if ( is_null( $section ) ) {
428 $this->mHeader
= $msg;
430 $this->mSectionHeaders
[$section] = $msg;
435 * Add footer text, inside the form.
436 * @param $msg String complete text of message to display
437 * @param $section string The section to add the footer text to
439 function addFooterText( $msg, $section = null ) {
440 if ( is_null( $section ) ) {
441 $this->mFooter
.= $msg;
443 if ( !isset( $this->mSectionFooters
[$section] ) ) {
444 $this->mSectionFooters
[$section] = '';
446 $this->mSectionFooters
[$section] .= $msg;
451 * Set footer text, inside the form.
453 * @param $msg String complete text of message to display
454 * @param $section string The section to add the footer text to
456 function setFooterText( $msg, $section = null ) {
457 if ( is_null( $section ) ) {
458 $this->mFooter
= $msg;
460 $this->mSectionFooters
[$section] = $msg;
465 * Add text to the end of the display.
466 * @param $msg String complete text of message to display
468 function addPostText( $msg ) { $this->mPost
.= $msg; }
471 * Set text at the end of the display.
472 * @param $msg String complete text of message to display
474 function setPostText( $msg ) { $this->mPost
= $msg; }
477 * Add a hidden field to the output
478 * @param $name String field name. This will be used exactly as entered
479 * @param $value String field value
480 * @param $attribs Array
482 public function addHiddenField( $name, $value, $attribs = array() ) {
483 $attribs +
= array( 'name' => $name );
484 $this->mHiddenFields
[] = array( $value, $attribs );
487 public function addButton( $name, $value, $id = null, $attribs = null ) {
488 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
492 * Display the form (sending to $wgOut), with an appropriate error
493 * message or stack of messages, and any validation errors, etc.
494 * @param $submitResult Mixed output from HTMLForm::trySubmit()
496 function displayForm( $submitResult ) {
497 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
501 * Returns the raw HTML generated by the form
502 * @param $submitResult Mixed output from HTMLForm::trySubmit()
505 function getHTML( $submitResult ) {
506 # For good measure (it is the default)
507 $this->getOutput()->preventClickjacking();
508 $this->getOutput()->addModules( 'mediawiki.htmlform' );
511 . $this->getErrors( $submitResult )
514 . $this->getHiddenFields()
515 . $this->getButtons()
519 $html = $this->wrapForm( $html );
521 return '' . $this->mPre
. $html . $this->mPost
;
525 * Wrap the form innards in an actual <form> element
526 * @param $html String HTML contents to wrap.
527 * @return String wrapped HTML.
529 function wrapForm( $html ) {
531 # Include a <fieldset> wrapper for style, if requested.
532 if ( $this->mWrapperLegend
!== false ) {
533 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
535 # Use multipart/form-data
536 $encType = $this->mUseMultipart
537 ?
'multipart/form-data'
538 : 'application/x-www-form-urlencoded';
541 'action' => $this->mAction
=== false ?
$this->getTitle()->getFullURL() : $this->mAction
,
542 'method' => $this->mMethod
,
543 'class' => 'visualClear',
544 'enctype' => $encType,
546 if ( !empty( $this->mId
) ) {
547 $attribs['id'] = $this->mId
;
550 return Html
::rawElement( 'form', $attribs, $html );
554 * Get the hidden fields that should go inside the form.
555 * @return String HTML.
557 function getHiddenFields() {
558 global $wgArticlePath;
561 if ( $this->getMethod() == 'post' ) {
562 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
563 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
566 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
567 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
570 foreach ( $this->mHiddenFields
as $data ) {
571 list( $value, $attribs ) = $data;
572 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
579 * Get the submit and (potentially) reset buttons.
580 * @return String HTML.
582 function getButtons() {
586 if ( isset( $this->mSubmitID
) ) {
587 $attribs['id'] = $this->mSubmitID
;
590 if ( isset( $this->mSubmitName
) ) {
591 $attribs['name'] = $this->mSubmitName
;
594 if ( isset( $this->mSubmitTooltip
) ) {
595 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
598 $attribs['class'] = 'mw-htmlform-submit';
600 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
602 if ( $this->mShowReset
) {
603 $html .= Html
::element(
607 'value' => wfMsg( 'htmlform-reset' )
612 foreach ( $this->mButtons
as $button ) {
615 'name' => $button['name'],
616 'value' => $button['value']
619 if ( $button['attribs'] ) {
620 $attrs +
= $button['attribs'];
623 if ( isset( $button['id'] ) ) {
624 $attrs['id'] = $button['id'];
627 $html .= Html
::element( 'input', $attrs );
634 * Get the whole body of the form.
638 return $this->displaySection( $this->mFieldTree
);
642 * Format and display an error message stack.
643 * @param $errors String|Array|Status
646 function getErrors( $errors ) {
647 if ( $errors instanceof Status
) {
648 if ( $errors->isOK() ) {
651 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
653 } elseif ( is_array( $errors ) ) {
654 $errorstr = $this->formatErrors( $errors );
660 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
665 * Format a stack of error messages into a single HTML string
666 * @param $errors Array of message keys/values
667 * @return String HTML, a <ul> list of errors
669 public static function formatErrors( $errors ) {
672 foreach ( $errors as $error ) {
673 if ( is_array( $error ) ) {
674 $msg = array_shift( $error );
680 $errorstr .= Html
::rawElement(
683 wfMsgExt( $msg, array( 'parseinline' ), $error )
687 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
693 * Set the text for the submit button
694 * @param $t String plaintext.
696 function setSubmitText( $t ) {
697 $this->mSubmitText
= $t;
701 * Set the text for the submit button to a message
703 * @param $msg String message key
705 public function setSubmitTextMsg( $msg ) {
706 return $this->setSubmitText( $this->msg( $msg )->text() );
710 * Get the text for the submit button, either customised or a default.
713 function getSubmitText() {
714 return $this->mSubmitText
716 : wfMsg( 'htmlform-submit' );
719 public function setSubmitName( $name ) {
720 $this->mSubmitName
= $name;
723 public function setSubmitTooltip( $name ) {
724 $this->mSubmitTooltip
= $name;
728 * Set the id for the submit button.
730 * @todo FIXME: Integrity of $t is *not* validated
732 function setSubmitID( $t ) {
733 $this->mSubmitID
= $t;
736 public function setId( $id ) {
740 * Prompt the whole form to be wrapped in a <fieldset>, with
741 * this text as its <legend> element.
742 * @param $legend String HTML to go inside the <legend> element.
745 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
748 * Prompt the whole form to be wrapped in a <fieldset>, with
749 * this message as its <legend> element.
751 * @param $msg String message key
753 public function setWrapperLegendMsg( $msg ) {
754 return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
758 * Set the prefix for various default messages
759 * TODO: currently only used for the <fieldset> legend on forms
760 * with multiple sections; should be used elsewhre?
763 function setMessagePrefix( $p ) {
764 $this->mMessagePrefix
= $p;
768 * Set the title for form submission
769 * @param $t Title of page the form is on/should be posted to
771 function setTitle( $t ) {
779 function getTitle() {
780 return $this->mTitle
=== false
781 ?
$this->getContext()->getTitle()
786 * Set the method used to submit the form
787 * @param $method String
789 public function setMethod( $method = 'post' ) {
790 $this->mMethod
= $method;
793 public function getMethod() {
794 return $this->mMethod
;
799 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
800 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
801 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
804 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
805 $displayFormat = $this->getDisplayFormat();
808 $subsectionHtml = '';
811 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ?
'getTableRow' : 'get' . ucfirst( $displayFormat );
813 foreach ( $fields as $key => $value ) {
814 if ( $value instanceof HTMLFormField
) {
815 $v = empty( $value->mParams
['nodata'] )
816 ?
$this->mFieldData
[$key]
817 : $value->getDefault();
818 $html .= $value->$getFieldHtmlMethod( $v );
820 $labelValue = trim( $value->getLabel() );
821 if ( $labelValue != ' ' && $labelValue !== '' ) {
824 } elseif ( is_array( $value ) ) {
825 $section = $this->displaySection( $value, $key );
826 $legend = $this->getLegend( $key );
827 if ( isset( $this->mSectionHeaders
[$key] ) ) {
828 $section = $this->mSectionHeaders
[$key] . $section;
830 if ( isset( $this->mSectionFooters
[$key] ) ) {
831 $section .= $this->mSectionFooters
[$key];
833 $attributes = array();
834 if ( $fieldsetIDPrefix ) {
835 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
837 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
841 if ( $displayFormat !== 'raw' ) {
844 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
845 $classes[] = 'mw-htmlform-nolabel';
849 'class' => implode( ' ', $classes ),
852 if ( $sectionName ) {
853 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
856 if ( $displayFormat === 'table' ) {
857 $html = Html
::rawElement( 'table', $attribs,
858 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
859 } elseif ( $displayFormat === 'div' ) {
860 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
864 if ( $this->mSubSectionBeforeFields
) {
865 return $subsectionHtml . "\n" . $html;
867 return $html . "\n" . $subsectionHtml;
872 * Construct the form fields from the Descriptor array
874 function loadData() {
875 $fieldData = array();
877 foreach ( $this->mFlatFields
as $fieldname => $field ) {
878 if ( !empty( $field->mParams
['nodata'] ) ) {
880 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
881 $fieldData[$fieldname] = $field->getDefault();
883 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
888 foreach ( $fieldData as $name => &$value ) {
889 $field = $this->mFlatFields
[$name];
890 $value = $field->filter( $value, $this->mFlatFields
);
893 $this->mFieldData
= $fieldData;
897 * Stop a reset button being shown for this form
898 * @param $suppressReset Bool set to false to re-enable the
901 function suppressReset( $suppressReset = true ) {
902 $this->mShowReset
= !$suppressReset;
906 * Overload this if you want to apply special filtration routines
907 * to the form as a whole, after it's submitted but before it's
912 function filterDataForSubmit( $data ) {
917 * Get a string to go in the <legend> of a section fieldset. Override this if you
918 * want something more complicated
922 public function getLegend( $key ) {
923 return wfMsg( "{$this->mMessagePrefix}-$key" );
927 * Set the value for the action attribute of the form.
928 * When set to false (which is the default state), the set title is used.
932 * @param string|bool $action
934 public function setAction( $action ) {
935 $this->mAction
= $action;
941 * The parent class to generate form fields. Any field type should
942 * be a subclass of this.
944 abstract class HTMLFormField
{
946 protected $mValidationCallback;
947 protected $mFilterCallback;
950 protected $mLabel; # String label. Set on construction
952 protected $mClass = '';
961 * This function must be implemented to return the HTML to generate
962 * the input object itself. It should not implement the surrounding
963 * table cells/rows, or labels/help messages.
964 * @param $value String the value to set the input to; eg a default
965 * text for a text input.
966 * @return String valid HTML.
968 abstract function getInputHTML( $value );
971 * Override this function to add specific validation checks on the
972 * field input. Don't forget to call parent::validate() to ensure
973 * that the user-defined callback mValidationCallback is still run
974 * @param $value String the value the field was submitted with
975 * @param $alldata Array the data collected from the form
976 * @return Mixed Bool true on success, or String error to display.
978 function validate( $value, $alldata ) {
979 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
980 return wfMsgExt( 'htmlform-required', 'parseinline' );
983 if ( isset( $this->mValidationCallback
) ) {
984 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
990 function filter( $value, $alldata ) {
991 if ( isset( $this->mFilterCallback
) ) {
992 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
999 * Should this field have a label, or is there no input element with the
1000 * appropriate id for the label to point to?
1002 * @return bool True to output a label, false to suppress
1004 protected function needsLabel() {
1009 * Get the value that this input has been set to from a posted form,
1010 * or the input's default value if it has not been set.
1011 * @param $request WebRequest
1012 * @return String the value
1014 function loadDataFromRequest( $request ) {
1015 if ( $request->getCheck( $this->mName
) ) {
1016 return $request->getText( $this->mName
);
1018 return $this->getDefault();
1023 * Initialise the object
1024 * @param $params array Associative Array. See HTMLForm doc for syntax.
1026 function __construct( $params ) {
1027 $this->mParams
= $params;
1029 # Generate the label from a message, if possible
1030 if ( isset( $params['label-message'] ) ) {
1031 $msgInfo = $params['label-message'];
1033 if ( is_array( $msgInfo ) ) {
1034 $msg = array_shift( $msgInfo );
1040 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
1041 } elseif ( isset( $params['label'] ) ) {
1042 $this->mLabel
= $params['label'];
1045 $this->mName
= "wp{$params['fieldname']}";
1046 if ( isset( $params['name'] ) ) {
1047 $this->mName
= $params['name'];
1050 $validName = Sanitizer
::escapeId( $this->mName
);
1051 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1052 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1055 $this->mID
= "mw-input-{$this->mName}";
1057 if ( isset( $params['default'] ) ) {
1058 $this->mDefault
= $params['default'];
1061 if ( isset( $params['id'] ) ) {
1062 $id = $params['id'];
1063 $validId = Sanitizer
::escapeId( $id );
1065 if ( $id != $validId ) {
1066 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1072 if ( isset( $params['cssclass'] ) ) {
1073 $this->mClass
= $params['cssclass'];
1076 if ( isset( $params['validation-callback'] ) ) {
1077 $this->mValidationCallback
= $params['validation-callback'];
1080 if ( isset( $params['filter-callback'] ) ) {
1081 $this->mFilterCallback
= $params['filter-callback'];
1084 if ( isset( $params['flatlist'] ) ) {
1085 $this->mClass
.= ' mw-htmlform-flatlist';
1090 * Get the complete table row for the input, including help text,
1091 * labels, and whatever.
1092 * @param $value String the value to set the input to.
1093 * @return String complete HTML table row.
1095 function getTableRow( $value ) {
1096 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1097 $inputHtml = $this->getInputHTML( $value );
1098 $fieldType = get_class( $this );
1099 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1100 $cellAttributes = array();
1102 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1103 $cellAttributes['colspan'] = 2;
1104 $verticalLabel = true;
1106 $verticalLabel = false;
1109 $label = $this->getLabelHtml( $cellAttributes );
1111 $field = Html
::rawElement(
1113 array( 'class' => 'mw-input' ) +
$cellAttributes,
1114 $inputHtml . "\n$errors"
1117 if ( $verticalLabel ) {
1118 $html = Html
::rawElement( 'tr',
1119 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1120 $html .= Html
::rawElement( 'tr',
1121 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1124 $html = Html
::rawElement( 'tr',
1125 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1129 return $html . $helptext;
1133 * Get the complete div for the input, including help text,
1134 * labels, and whatever.
1136 * @param $value String the value to set the input to.
1137 * @return String complete HTML table row.
1139 public function getDiv( $value ) {
1140 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1141 $inputHtml = $this->getInputHTML( $value );
1142 $fieldType = get_class( $this );
1143 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1144 $cellAttributes = array();
1145 $label = $this->getLabelHtml( $cellAttributes );
1147 $field = Html
::rawElement(
1149 array( 'class' => 'mw-input' ) +
$cellAttributes,
1150 $inputHtml . "\n$errors"
1152 $html = Html
::rawElement( 'div',
1153 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1160 * Get the complete raw fields for the input, including help text,
1161 * labels, and whatever.
1163 * @param $value String the value to set the input to.
1164 * @return String complete HTML table row.
1166 public function getRaw( $value ) {
1167 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1168 $inputHtml = $this->getInputHTML( $value );
1169 $fieldType = get_class( $this );
1170 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1171 $cellAttributes = array();
1172 $label = $this->getLabelHtml( $cellAttributes );
1174 $html = "\n$errors";
1176 $html .= $inputHtml;
1182 * Generate help text HTML in table format
1184 * @param $helptext String|null
1187 public function getHelpTextHtmlTable( $helptext ) {
1188 if ( is_null( $helptext ) ) {
1192 $row = Html
::rawElement(
1194 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1197 $row = Html
::rawElement( 'tr', array(), $row );
1202 * Generate help text HTML in div format
1204 * @param $helptext String|null
1207 public function getHelpTextHtmlDiv( $helptext ) {
1208 if ( is_null( $helptext ) ) {
1212 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1217 * Generate help text HTML formatted for raw output
1219 * @param $helptext String|null
1222 public function getHelpTextHtmlRaw( $helptext ) {
1223 return $this->getHelpTextHtmlDiv( $helptext );
1227 * Determine the help text to display
1231 public function getHelpText() {
1234 if ( isset( $this->mParams
['help-message'] ) ) {
1235 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1238 if ( isset( $this->mParams
['help-messages'] ) ) {
1239 foreach ( $this->mParams
['help-messages'] as $name ) {
1240 $helpMessage = (array)$name;
1241 $msg = wfMessage( array_shift( $helpMessage ), $helpMessage );
1243 if ( $msg->exists() ) {
1244 if ( is_null( $helptext ) ) {
1247 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1249 $helptext .= $msg->parse(); // Append message
1253 elseif ( isset( $this->mParams
['help'] ) ) {
1254 $helptext = $this->mParams
['help'];
1260 * Determine form errors to display and their classes
1262 * @param $value String the value of the input
1265 public function getErrorsAndErrorClass( $value ) {
1266 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1268 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1272 $errors = self
::formatErrors( $errors );
1273 $errorClass = 'mw-htmlform-invalid-input';
1275 return array( $errors, $errorClass );
1278 function getLabel() {
1279 return $this->mLabel
;
1282 function getLabelHtml( $cellAttributes = array() ) {
1283 # Don't output a for= attribute for labels with no associated input.
1284 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1287 if ( $this->needsLabel() ) {
1288 $for['for'] = $this->mID
;
1291 $displayFormat = $this->mParent
->getDisplayFormat();
1292 $labelElement = Html
::rawElement( 'label', $for, $this->getLabel() );
1294 if ( $displayFormat == 'table' ) {
1295 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1296 Html
::rawElement( 'label', $for, $this->getLabel() )
1298 } elseif ( $displayFormat == 'div' ) {
1299 return Html
::rawElement( 'div', array( 'class' => 'mw-label' ) +
$cellAttributes,
1300 Html
::rawElement( 'label', $for, $this->getLabel() )
1303 return $labelElement;
1307 function getDefault() {
1308 if ( isset( $this->mDefault
) ) {
1309 return $this->mDefault
;
1316 * Returns the attributes required for the tooltip and accesskey.
1318 * @return array Attributes
1320 public function getTooltipAndAccessKey() {
1321 if ( empty( $this->mParams
['tooltip'] ) ) {
1324 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1328 * flatten an array of options to a single array, for instance,
1329 * a set of <options> inside <optgroups>.
1330 * @param $options array Associative Array with values either Strings
1332 * @return Array flattened input
1334 public static function flattenOptions( $options ) {
1335 $flatOpts = array();
1337 foreach ( $options as $value ) {
1338 if ( is_array( $value ) ) {
1339 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1341 $flatOpts[] = $value;
1349 * Formats one or more errors as accepted by field validation-callback.
1350 * @param $errors String|Message|Array of strings or Message instances
1351 * @return String html
1354 protected static function formatErrors( $errors ) {
1355 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1356 $errors = array_shift( $errors );
1359 if ( is_array( $errors ) ) {
1361 foreach ( $errors as $error ) {
1362 if ( $error instanceof Message
) {
1363 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1365 $lines[] = Html
::rawElement( 'li', array(), $error );
1368 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1370 if ( $errors instanceof Message
) {
1371 $errors = $errors->parse();
1373 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1378 class HTMLTextField
extends HTMLFormField
{
1379 function getSize() {
1380 return isset( $this->mParams
['size'] )
1381 ?
$this->mParams
['size']
1385 function getInputHTML( $value ) {
1388 'name' => $this->mName
,
1389 'size' => $this->getSize(),
1391 ) +
$this->getTooltipAndAccessKey();
1393 if ( $this->mClass
!== '' ) {
1394 $attribs['class'] = $this->mClass
;
1397 if ( isset( $this->mParams
['maxlength'] ) ) {
1398 $attribs['maxlength'] = $this->mParams
['maxlength'];
1401 if ( !empty( $this->mParams
['disabled'] ) ) {
1402 $attribs['disabled'] = 'disabled';
1405 # TODO: Enforce pattern, step, required, readonly on the server side as
1407 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1408 'placeholder' ) as $param ) {
1409 if ( isset( $this->mParams
[$param] ) ) {
1410 $attribs[$param] = $this->mParams
[$param];
1414 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1415 if ( isset( $this->mParams
[$param] ) ) {
1416 $attribs[$param] = '';
1420 # Implement tiny differences between some field variants
1421 # here, rather than creating a new class for each one which
1422 # is essentially just a clone of this one.
1423 if ( isset( $this->mParams
['type'] ) ) {
1424 switch ( $this->mParams
['type'] ) {
1426 $attribs['type'] = 'email';
1429 $attribs['type'] = 'number';
1432 $attribs['type'] = 'number';
1433 $attribs['step'] = 'any';
1438 $attribs['type'] = $this->mParams
['type'];
1443 return Html
::element( 'input', $attribs );
1446 class HTMLTextAreaField
extends HTMLFormField
{
1447 function getCols() {
1448 return isset( $this->mParams
['cols'] )
1449 ?
$this->mParams
['cols']
1453 function getRows() {
1454 return isset( $this->mParams
['rows'] )
1455 ?
$this->mParams
['rows']
1459 function getInputHTML( $value ) {
1462 'name' => $this->mName
,
1463 'cols' => $this->getCols(),
1464 'rows' => $this->getRows(),
1465 ) +
$this->getTooltipAndAccessKey();
1467 if ( $this->mClass
!== '' ) {
1468 $attribs['class'] = $this->mClass
;
1471 if ( !empty( $this->mParams
['disabled'] ) ) {
1472 $attribs['disabled'] = 'disabled';
1475 if ( !empty( $this->mParams
['readonly'] ) ) {
1476 $attribs['readonly'] = 'readonly';
1479 if ( isset( $this->mParams
['placeholder'] ) ) {
1480 $attribs['placeholder'] = $this->mParams
['placeholder'];
1483 foreach ( array( 'required', 'autofocus' ) as $param ) {
1484 if ( isset( $this->mParams
[$param] ) ) {
1485 $attribs[$param] = '';
1489 return Html
::element( 'textarea', $attribs, $value );
1494 * A field that will contain a numeric value
1496 class HTMLFloatField
extends HTMLTextField
{
1497 function getSize() {
1498 return isset( $this->mParams
['size'] )
1499 ?
$this->mParams
['size']
1503 function validate( $value, $alldata ) {
1504 $p = parent
::validate( $value, $alldata );
1506 if ( $p !== true ) {
1510 $value = trim( $value );
1512 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1513 # with the addition that a leading '+' sign is ok.
1514 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1515 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1518 # The "int" part of these message names is rather confusing.
1519 # They make equal sense for all numbers.
1520 if ( isset( $this->mParams
['min'] ) ) {
1521 $min = $this->mParams
['min'];
1523 if ( $min > $value ) {
1524 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1528 if ( isset( $this->mParams
['max'] ) ) {
1529 $max = $this->mParams
['max'];
1531 if ( $max < $value ) {
1532 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1541 * A field that must contain a number
1543 class HTMLIntField
extends HTMLFloatField
{
1544 function validate( $value, $alldata ) {
1545 $p = parent
::validate( $value, $alldata );
1547 if ( $p !== true ) {
1551 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1552 # with the addition that a leading '+' sign is ok. Note that leading zeros
1553 # are fine, and will be left in the input, which is useful for things like
1554 # phone numbers when you know that they are integers (the HTML5 type=tel
1555 # input does not require its value to be numeric). If you want a tidier
1556 # value to, eg, save in the DB, clean it up with intval().
1557 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1559 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1569 class HTMLCheckField
extends HTMLFormField
{
1570 function getInputHTML( $value ) {
1571 if ( !empty( $this->mParams
['invert'] ) ) {
1575 $attr = $this->getTooltipAndAccessKey();
1576 $attr['id'] = $this->mID
;
1578 if ( !empty( $this->mParams
['disabled'] ) ) {
1579 $attr['disabled'] = 'disabled';
1582 if ( $this->mClass
!== '' ) {
1583 $attr['class'] = $this->mClass
;
1586 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1587 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1591 * For a checkbox, the label goes on the right hand side, and is
1592 * added in getInputHTML(), rather than HTMLFormField::getRow()
1595 function getLabel() {
1600 * @param $request WebRequest
1603 function loadDataFromRequest( $request ) {
1605 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1609 // GetCheck won't work like we want for checks.
1610 // Fetch the value in either one of the two following case:
1611 // - we have a valid token (form got posted or GET forged by the user)
1612 // - checkbox name has a value (false or true), ie is not null
1613 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1614 // XOR has the following truth table, which is what we want
1615 // INVERT VALUE | OUTPUT
1616 // true true | false
1617 // false true | true
1618 // false false | false
1619 // true false | true
1620 return $request->getBool( $this->mName
) xor $invert;
1622 return $this->getDefault();
1628 * A select dropdown field. Basically a wrapper for Xmlselect class
1630 class HTMLSelectField
extends HTMLFormField
{
1631 function validate( $value, $alldata ) {
1632 $p = parent
::validate( $value, $alldata );
1634 if ( $p !== true ) {
1638 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1640 if ( in_array( $value, $validOptions ) )
1643 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1646 function getInputHTML( $value ) {
1647 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1649 # If one of the options' 'name' is int(0), it is automatically selected.
1650 # because PHP sucks and thinks int(0) == 'some string'.
1651 # Working around this by forcing all of them to strings.
1652 foreach ( $this->mParams
['options'] as &$opt ) {
1653 if ( is_int( $opt ) ) {
1654 $opt = strval( $opt );
1657 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1659 if ( !empty( $this->mParams
['disabled'] ) ) {
1660 $select->setAttribute( 'disabled', 'disabled' );
1663 if ( $this->mClass
!== '' ) {
1664 $select->setAttribute( 'class', $this->mClass
);
1667 $select->addOptions( $this->mParams
['options'] );
1669 return $select->getHTML();
1674 * Select dropdown field, with an additional "other" textbox.
1676 class HTMLSelectOrOtherField
extends HTMLTextField
{
1677 static $jsAdded = false;
1679 function __construct( $params ) {
1680 if ( !in_array( 'other', $params['options'], true ) ) {
1681 $msg = isset( $params['other'] ) ?
$params['other'] : wfMsg( 'htmlform-selectorother-other' );
1682 $params['options'][$msg] = 'other';
1685 parent
::__construct( $params );
1688 static function forceToStringRecursive( $array ) {
1689 if ( is_array( $array ) ) {
1690 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1692 return strval( $array );
1696 function getInputHTML( $value ) {
1697 $valInSelect = false;
1699 if ( $value !== false ) {
1700 $valInSelect = in_array(
1702 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1706 $selected = $valInSelect ?
$value : 'other';
1708 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1710 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1711 $select->addOptions( $opts );
1713 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1715 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1717 if ( !empty( $this->mParams
['disabled'] ) ) {
1718 $select->setAttribute( 'disabled', 'disabled' );
1719 $tbAttribs['disabled'] = 'disabled';
1722 $select = $select->getHTML();
1724 if ( isset( $this->mParams
['maxlength'] ) ) {
1725 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1728 if ( $this->mClass
!== '' ) {
1729 $tbAttribs['class'] = $this->mClass
;
1732 $textbox = Html
::input(
1733 $this->mName
. '-other',
1734 $valInSelect ?
'' : $value,
1739 return "$select<br />\n$textbox";
1743 * @param $request WebRequest
1746 function loadDataFromRequest( $request ) {
1747 if ( $request->getCheck( $this->mName
) ) {
1748 $val = $request->getText( $this->mName
);
1750 if ( $val == 'other' ) {
1751 $val = $request->getText( $this->mName
. '-other' );
1756 return $this->getDefault();
1762 * Multi-select field
1764 class HTMLMultiSelectField
extends HTMLFormField
{
1766 function validate( $value, $alldata ) {
1767 $p = parent
::validate( $value, $alldata );
1769 if ( $p !== true ) {
1773 if ( !is_array( $value ) ) {
1777 # If all options are valid, array_intersect of the valid options
1778 # and the provided options will return the provided options.
1779 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1781 $validValues = array_intersect( $value, $validOptions );
1782 if ( count( $validValues ) == count( $value ) ) {
1785 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1789 function getInputHTML( $value ) {
1790 $html = $this->formatOptions( $this->mParams
['options'], $value );
1795 function formatOptions( $options, $value ) {
1800 if ( !empty( $this->mParams
['disabled'] ) ) {
1801 $attribs['disabled'] = 'disabled';
1804 foreach ( $options as $label => $info ) {
1805 if ( is_array( $info ) ) {
1806 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1807 $html .= $this->formatOptions( $info, $value );
1809 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1811 $checkbox = Xml
::check(
1812 $this->mName
. '[]',
1813 in_array( $info, $value, true ),
1814 $attribs +
$thisAttribs );
1815 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1817 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1825 * @param $request WebRequest
1828 function loadDataFromRequest( $request ) {
1829 if ( $this->mParent
->getMethod() == 'post' ) {
1830 if ( $request->wasPosted() ) {
1831 # Checkboxes are just not added to the request arrays if they're not checked,
1832 # so it's perfectly possible for there not to be an entry at all
1833 return $request->getArray( $this->mName
, array() );
1835 # That's ok, the user has not yet submitted the form, so show the defaults
1836 return $this->getDefault();
1839 # This is the impossible case: if we look at $_GET and see no data for our
1840 # field, is it because the user has not yet submitted the form, or that they
1841 # have submitted it with all the options unchecked? We will have to assume the
1842 # latter, which basically means that you can't specify 'positive' defaults
1845 return $request->getArray( $this->mName
, array() );
1849 function getDefault() {
1850 if ( isset( $this->mDefault
) ) {
1851 return $this->mDefault
;
1857 protected function needsLabel() {
1863 * Double field with a dropdown list constructed from a system message in the format
1866 * * New Optgroup header
1867 * Plus a text field underneath for an additional reason. The 'value' of the field is
1868 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1870 * @todo FIXME: If made 'required', only the text field should be compulsory.
1872 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1874 function __construct( $params ) {
1875 if ( array_key_exists( 'other', $params ) ) {
1876 } elseif ( array_key_exists( 'other-message', $params ) ) {
1877 $params['other'] = wfMessage( $params['other-message'] )->plain();
1879 $params['other'] = null;
1882 if ( array_key_exists( 'options', $params ) ) {
1883 # Options array already specified
1884 } elseif ( array_key_exists( 'options-message', $params ) ) {
1885 # Generate options array from a system message
1886 $params['options'] = self
::parseMessage(
1887 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1892 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1894 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1896 parent
::__construct( $params );
1900 * Build a drop-down box from a textual list.
1901 * @param $string String message text
1902 * @param $otherName String name of "other reason" option
1904 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1906 public static function parseMessage( $string, $otherName = null ) {
1907 if ( $otherName === null ) {
1908 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1912 $options = array( $otherName => 'other' );
1914 foreach ( explode( "\n", $string ) as $option ) {
1915 $value = trim( $option );
1916 if ( $value == '' ) {
1918 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1919 # A new group is starting...
1920 $value = trim( substr( $value, 1 ) );
1922 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1924 $opt = trim( substr( $value, 2 ) );
1925 if ( $optgroup === false ) {
1926 $options[$opt] = $opt;
1928 $options[$optgroup][$opt] = $opt;
1931 # groupless reason list
1933 $options[$option] = $option;
1940 function getInputHTML( $value ) {
1941 $select = parent
::getInputHTML( $value[1] );
1943 $textAttribs = array(
1944 'id' => $this->mID
. '-other',
1945 'size' => $this->getSize(),
1948 if ( $this->mClass
!== '' ) {
1949 $textAttribs['class'] = $this->mClass
;
1952 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1953 if ( isset( $this->mParams
[$param] ) ) {
1954 $textAttribs[$param] = '';
1958 $textbox = Html
::input(
1959 $this->mName
. '-other',
1965 return "$select<br />\n$textbox";
1969 * @param $request WebRequest
1970 * @return Array( <overall message>, <select value>, <text field value> )
1972 function loadDataFromRequest( $request ) {
1973 if ( $request->getCheck( $this->mName
) ) {
1975 $list = $request->getText( $this->mName
);
1976 $text = $request->getText( $this->mName
. '-other' );
1978 if ( $list == 'other' ) {
1980 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
1981 # User has spoofed the select form to give an option which wasn't
1982 # in the original offer. Sulk...
1984 } elseif ( $text == '' ) {
1987 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1991 $final = $this->getDefault();
1995 foreach ( $this->mFlatOptions
as $option ) {
1996 $match = $option . wfMsgForContent( 'colon-separator' );
1997 if ( strpos( $text, $match ) === 0 ) {
1999 $text = substr( $text, strlen( $match ) );
2004 return array( $final, $list, $text );
2007 function getSize() {
2008 return isset( $this->mParams
['size'] )
2009 ?
$this->mParams
['size']
2013 function validate( $value, $alldata ) {
2014 # HTMLSelectField forces $value to be one of the options in the select
2015 # field, which is not useful here. But we do want the validation further up
2017 $p = parent
::validate( $value[1], $alldata );
2019 if ( $p !== true ) {
2023 if ( isset( $this->mParams
['required'] ) && $value[1] === '' ) {
2024 return wfMsgExt( 'htmlform-required', 'parseinline' );
2032 * Radio checkbox fields.
2034 class HTMLRadioField
extends HTMLFormField
{
2037 function validate( $value, $alldata ) {
2038 $p = parent
::validate( $value, $alldata );
2040 if ( $p !== true ) {
2044 if ( !is_string( $value ) && !is_int( $value ) ) {
2048 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2050 if ( in_array( $value, $validOptions ) ) {
2053 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
2058 * This returns a block of all the radio options, in one cell.
2059 * @see includes/HTMLFormField#getInputHTML()
2060 * @param $value String
2063 function getInputHTML( $value ) {
2064 $html = $this->formatOptions( $this->mParams
['options'], $value );
2069 function formatOptions( $options, $value ) {
2073 if ( !empty( $this->mParams
['disabled'] ) ) {
2074 $attribs['disabled'] = 'disabled';
2077 # TODO: should this produce an unordered list perhaps?
2078 foreach ( $options as $label => $info ) {
2079 if ( is_array( $info ) ) {
2080 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2081 $html .= $this->formatOptions( $info, $value );
2083 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2084 $radio = Xml
::radio(
2088 $attribs +
array( 'id' => $id )
2090 $radio .= ' ' .
2091 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2093 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2100 protected function needsLabel() {
2106 * An information field (text blob), not a proper input.
2108 class HTMLInfoField
extends HTMLFormField
{
2109 public function __construct( $info ) {
2110 $info['nodata'] = true;
2112 parent
::__construct( $info );
2115 public function getInputHTML( $value ) {
2116 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2119 public function getTableRow( $value ) {
2120 if ( !empty( $this->mParams
['rawrow'] ) ) {
2124 return parent
::getTableRow( $value );
2130 public function getDiv( $value ) {
2131 if ( !empty( $this->mParams
['rawrow'] ) ) {
2135 return parent
::getDiv( $value );
2141 public function getRaw( $value ) {
2142 if ( !empty( $this->mParams
['rawrow'] ) ) {
2146 return parent
::getRaw( $value );
2149 protected function needsLabel() {
2154 class HTMLHiddenField
extends HTMLFormField
{
2155 public function __construct( $params ) {
2156 parent
::__construct( $params );
2158 # Per HTML5 spec, hidden fields cannot be 'required'
2159 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2160 unset( $this->mParams
['required'] );
2163 public function getTableRow( $value ) {
2166 $params['id'] = $this->mID
;
2169 $this->mParent
->addHiddenField(
2181 public function getDiv( $value ) {
2182 return $this->getTableRow( $value );
2188 public function getRaw( $value ) {
2189 return $this->getTableRow( $value );
2192 public function getInputHTML( $value ) { return ''; }
2196 * Add a submit button inline in the form (as opposed to
2197 * HTMLForm::addButton(), which will add it at the end).
2199 class HTMLSubmitField
extends HTMLFormField
{
2201 public function __construct( $info ) {
2202 $info['nodata'] = true;
2203 parent
::__construct( $info );
2206 public function getInputHTML( $value ) {
2207 return Xml
::submitButton(
2210 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2211 'name' => $this->mName
,
2217 protected function needsLabel() {
2222 * Button cannot be invalid
2223 * @param $value String
2224 * @param $alldata Array
2227 public function validate( $value, $alldata ) {
2232 class HTMLEditTools
extends HTMLFormField
{
2233 public function getInputHTML( $value ) {
2237 public function getTableRow( $value ) {
2238 $msg = $this->formatMsg();
2240 return '<tr><td></td><td class="mw-input">'
2241 . '<div class="mw-editTools">'
2242 . $msg->parseAsBlock()
2243 . "</div></td></tr>\n";
2249 public function getDiv( $value ) {
2250 $msg = $this->formatMsg();
2251 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2257 public function getRaw( $value ) {
2258 return $this->getDiv( $value );
2261 protected function formatMsg() {
2262 if ( empty( $this->mParams
['message'] ) ) {
2263 $msg = wfMessage( 'edittools' );
2265 $msg = wfMessage( $this->mParams
['message'] );
2266 if ( $msg->isDisabled() ) {
2267 $msg = wfMessage( 'edittools' );
2270 $msg->inContentLanguage();