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' -- message key for a message to use as a help text.
34 * can be an array of msg key and then parameters to
36 * 'required' -- passed through to the object, indicating that it
37 * is a required field.
38 * 'size' -- the length of text fields
39 * 'filter-callback -- a function name to give you the chance to
40 * massage the inputted value before it's processed.
41 * @see HTMLForm::filter()
42 * 'validation-callback' -- a function name to give you the chance
43 * to impose extra validation on the field input.
44 * @see HTMLForm::validate()
46 * TODO: Document 'section' / 'subsection' stuff
49 static $jsAdded = false;
51 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
52 static $typeMappings = array(
53 'text' => 'HTMLTextField',
54 'textarea' => 'HTMLTextAreaField',
55 'select' => 'HTMLSelectField',
56 'radio' => 'HTMLRadioField',
57 'multiselect' => 'HTMLMultiSelectField',
58 'check' => 'HTMLCheckField',
59 'toggle' => 'HTMLCheckField',
60 'int' => 'HTMLIntField',
61 'float' => 'HTMLFloatField',
62 'info' => 'HTMLInfoField',
63 'selectorother' => 'HTMLSelectOrOtherField',
64 'submit' => 'HTMLSubmitField',
65 'hidden' => 'HTMLHiddenField',
66 'edittools' => 'HTMLEditTools',
68 # HTMLTextField will output the correct type="" attribute automagically.
69 # There are about four zillion other HTML5 input types, like url, but
70 # we don't use those at the moment, so no point in adding all of them.
71 'email' => 'HTMLTextField',
72 'password' => 'HTMLTextField',
75 protected $mMessagePrefix;
76 protected $mFlatFields;
77 protected $mFieldTree;
78 protected $mShowReset = false;
81 protected $mSubmitCallback;
82 protected $mValidationErrorMessage;
85 protected $mHeader = '';
86 protected $mFooter = '';
87 protected $mPost = '';
91 protected $mSubmitName;
92 protected $mSubmitText;
93 protected $mSubmitTooltip;
96 protected $mUseMultipart = false;
97 protected $mHiddenFields = array();
98 protected $mButtons = array();
100 protected $mWrapperLegend = false;
103 * Build a new HTMLForm from an array of field attributes
104 * @param $descriptor Array of Field constructs, as described above
105 * @param $messagePrefix String a prefix to go in front of default messages
107 public function __construct( $descriptor, $messagePrefix = '' ) {
108 $this->mMessagePrefix
= $messagePrefix;
110 // Expand out into a tree.
111 $loadedDescriptor = array();
112 $this->mFlatFields
= array();
114 foreach ( $descriptor as $fieldname => $info ) {
115 $section = isset( $info['section'] )
119 $info['name'] = isset( $info['name'] )
123 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
124 $this->mUseMultipart
= true;
127 $field = self
::loadInputFromParameters( $info );
128 $field->mParent
= $this;
130 $setSection =& $loadedDescriptor;
132 $sectionParts = explode( '/', $section );
134 while ( count( $sectionParts ) ) {
135 $newName = array_shift( $sectionParts );
137 if ( !isset( $setSection[$newName] ) ) {
138 $setSection[$newName] = array();
141 $setSection =& $setSection[$newName];
145 $setSection[$fieldname] = $field;
146 $this->mFlatFields
[$fieldname] = $field;
149 $this->mFieldTree
= $loadedDescriptor;
153 * Add the HTMLForm-specific JavaScript, if it hasn't been
156 static function addJS() {
157 if ( self
::$jsAdded ) return;
161 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
165 * Initialise a new Object for the field
166 * @param $descriptor input Descriptor, as described above
167 * @return HTMLFormField subclass
169 static function loadInputFromParameters( $descriptor ) {
170 if ( isset( $descriptor['class'] ) ) {
171 $class = $descriptor['class'];
172 } elseif ( isset( $descriptor['type'] ) ) {
173 $class = self
::$typeMappings[$descriptor['type']];
174 $descriptor['class'] = $class;
178 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
181 $obj = new $class( $descriptor );
187 * The here's-one-I-made-earlier option: do the submission if
188 * posted, or display the form with or without funky valiation
190 * @return Bool whether submission was successful.
193 // Check if we have the info we need
194 if ( ! $this->mTitle
) {
195 throw new MWException( "You must call setTitle() on an HTMLForm" );
200 # Load data from the request.
204 global $wgUser, $wgRequest;
205 $editToken = $wgRequest->getVal( 'wpEditToken' );
208 if ( $wgUser->matchEditToken( $editToken ) ) {
209 $result = $this->trySubmit();
212 if ( $result === true ||
213 ( $result instanceof Status
&& $result->isGood() ) )
219 $this->displayForm( $result );
224 * Validate all the fields, and call the submision callback
225 * function if everything is kosher.
226 * @return Mixed Bool true == Successful submission, Bool false
227 * == No submission attempted, anything else == Error to
230 function trySubmit() {
231 # Check for validation
232 foreach ( $this->mFlatFields
as $fieldname => $field ) {
233 if ( !empty( $field->mParams
['nodata'] ) ) {
236 if ( $field->validate(
237 $this->mFieldData
[$fieldname],
241 return isset( $this->mValidationErrorMessage
)
242 ?
$this->mValidationErrorMessage
243 : array( 'htmlform-invalid-input' );
247 $callback = $this->mSubmitCallback
;
249 $data = $this->filterDataForSubmit( $this->mFieldData
);
251 $res = call_user_func( $callback, $data );
257 * Set a callback to a function to do something with the form
258 * once it's been successfully validated.
259 * @param $cb String function name. The function will be passed
260 * the output from HTMLForm::filterDataForSubmit, and must
261 * return Bool true on success, Bool false if no submission
262 * was attempted, or String HTML output to display on error.
264 function setSubmitCallback( $cb ) {
265 $this->mSubmitCallback
= $cb;
269 * Set a message to display on a validation error.
270 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
271 * (so each entry can be either a String or Array)
273 function setValidationErrorMessage( $msg ) {
274 $this->mValidationErrorMessage
= $msg;
278 * Set the introductory message, overwriting any existing message.
279 * @param $msg String complete text of message to display
281 function setIntro( $msg ) { $this->mPre
= $msg; }
284 * Add introductory text.
285 * @param $msg String complete text of message to display
287 function addPreText( $msg ) { $this->mPre
.= $msg; }
290 * Add header text, inside the form.
291 * @param $msg String complete text of message to display
293 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
296 * Add footer text, inside the form.
297 * @param $msg String complete text of message to display
299 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
302 * Add text to the end of the display.
303 * @param $msg String complete text of message to display
305 function addPostText( $msg ) { $this->mPost
.= $msg; }
308 * Add a hidden field to the output
309 * @param $name String field name
310 * @param $value String field value
311 * @param $attribs Array
313 public function addHiddenField( $name, $value, $attribs = array() ) {
314 $attribs +
= array( 'name' => $name );
315 $this->mHiddenFields
[] = array( $value, $attribs );
318 public function addButton( $name, $value, $id = null, $attribs = null ) {
319 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
323 * Display the form (sending to wgOut), with an appropriate error
324 * message or stack of messages, and any validation errors, etc.
325 * @param $submitResult Mixed output from HTMLForm::trySubmit()
327 function displayForm( $submitResult ) {
331 . $this->getErrors( $submitResult )
334 . $this->getHiddenFields()
335 . $this->getButtons()
339 $html = $this->wrapForm( $html );
349 * Wrap the form innards in an actual <form> element
350 * @param $html String HTML contents to wrap.
351 * @return String wrapped HTML.
353 function wrapForm( $html ) {
355 # Include a <fieldset> wrapper for style, if requested.
356 if ( $this->mWrapperLegend
!== false ) {
357 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
359 # Use multipart/form-data
360 $encType = $this->mUseMultipart
361 ?
'multipart/form-data'
362 : 'application/x-www-form-urlencoded';
365 'action' => $this->getTitle()->getFullURL(),
367 'class' => 'visualClear',
368 'enctype' => $encType,
370 if ( !empty( $this->mId
) ) {
371 $attribs['id'] = $this->mId
;
374 return Html
::rawElement( 'form', $attribs, $html );
378 * Get the hidden fields that should go inside the form.
379 * @return String HTML.
381 function getHiddenFields() {
385 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
386 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
388 foreach ( $this->mHiddenFields
as $data ) {
389 list( $value, $attribs ) = $data;
390 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
397 * Get the submit and (potentially) reset buttons.
398 * @return String HTML.
400 function getButtons() {
404 if ( isset( $this->mSubmitID
) ) {
405 $attribs['id'] = $this->mSubmitID
;
408 if ( isset( $this->mSubmitName
) ) {
409 $attribs['name'] = $this->mSubmitName
;
412 if ( isset( $this->mSubmitTooltip
) ) {
414 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
417 $attribs['class'] = 'mw-htmlform-submit';
419 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
421 if ( $this->mShowReset
) {
422 $html .= Html
::element(
426 'value' => wfMsg( 'htmlform-reset' )
431 foreach ( $this->mButtons
as $button ) {
434 'name' => $button['name'],
435 'value' => $button['value']
438 if ( $button['attribs'] ) {
439 $attrs +
= $button['attribs'];
442 if ( isset( $button['id'] ) ) {
443 $attrs['id'] = $button['id'];
446 $html .= Html
::element( 'input', $attrs );
453 * Get the whole body of the form.
456 return $this->displaySection( $this->mFieldTree
);
460 * Format and display an error message stack.
461 * @param $errors Mixed String or Array of message keys
464 function getErrors( $errors ) {
465 if ( $errors instanceof Status
) {
467 $errorstr = $wgOut->parse( $errors->getWikiText() );
468 } elseif ( is_array( $errors ) ) {
469 $errorstr = $this->formatErrors( $errors );
475 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
480 * Format a stack of error messages into a single HTML string
481 * @param $errors Array of message keys/values
482 * @return String HTML, a <ul> list of errors
484 static function formatErrors( $errors ) {
487 foreach ( $errors as $error ) {
488 if ( is_array( $error ) ) {
489 $msg = array_shift( $error );
495 $errorstr .= Html
::rawElement(
498 wfMsgExt( $msg, array( 'parseinline' ), $error )
502 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
508 * Set the text for the submit button
509 * @param $t String plaintext.
511 function setSubmitText( $t ) {
512 $this->mSubmitText
= $t;
516 * Get the text for the submit button, either customised or a default.
517 * @return unknown_type
519 function getSubmitText() {
520 return $this->mSubmitText
522 : wfMsg( 'htmlform-submit' );
525 public function setSubmitName( $name ) {
526 $this->mSubmitName
= $name;
529 public function setSubmitTooltip( $name ) {
530 $this->mSubmitTooltip
= $name;
535 * Set the id for the submit button.
536 * @param $t String. FIXME: Integrity is *not* validated
538 function setSubmitID( $t ) {
539 $this->mSubmitID
= $t;
542 public function setId( $id ) {
546 * Prompt the whole form to be wrapped in a <fieldset>, with
547 * this text as its <legend> element.
548 * @param $legend String HTML to go inside the <legend> element.
551 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
554 * Set the prefix for various default messages
555 * TODO: currently only used for the <fieldset> legend on forms
556 * with multiple sections; should be used elsewhre?
559 function setMessagePrefix( $p ) {
560 $this->mMessagePrefix
= $p;
564 * Set the title for form submission
565 * @param $t Title of page the form is on/should be posted to
567 function setTitle( $t ) {
575 function getTitle() {
576 return $this->mTitle
;
583 function displaySection( $fields, $sectionName = '' ) {
585 $subsectionHtml = '';
586 $hasLeftColumn = false;
588 foreach ( $fields as $key => $value ) {
589 if ( is_object( $value ) ) {
590 $v = empty( $value->mParams
['nodata'] )
591 ?
$this->mFieldData
[$key]
592 : $value->getDefault();
593 $tableHtml .= $value->getTableRow( $v );
595 if ( $value->getLabel() != ' ' )
596 $hasLeftColumn = true;
597 } elseif ( is_array( $value ) ) {
598 $section = $this->displaySection( $value, $key );
599 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
600 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
606 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
607 $classes[] = 'mw-htmlform-nolabel';
611 'class' => implode( ' ', $classes ),
614 if ( $sectionName ) {
615 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
618 $tableHtml = Html
::rawElement( 'table', $attribs,
619 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
621 return $subsectionHtml . "\n" . $tableHtml;
625 * Construct the form fields from the Descriptor array
627 function loadData() {
630 $fieldData = array();
632 foreach ( $this->mFlatFields
as $fieldname => $field ) {
633 if ( !empty( $field->mParams
['nodata'] ) ) {
635 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
636 $fieldData[$fieldname] = $field->getDefault();
638 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
643 foreach ( $fieldData as $name => &$value ) {
644 $field = $this->mFlatFields
[$name];
645 $value = $field->filter( $value, $this->mFlatFields
);
648 $this->mFieldData
= $fieldData;
652 * Stop a reset button being shown for this form
653 * @param $suppressReset Bool set to false to re-enable the
656 function suppressReset( $suppressReset = true ) {
657 $this->mShowReset
= !$suppressReset;
661 * Overload this if you want to apply special filtration routines
662 * to the form as a whole, after it's submitted but before it's
665 * @return unknown_type
667 function filterDataForSubmit( $data ) {
673 * The parent class to generate form fields. Any field type should
674 * be a subclass of this.
676 abstract class HTMLFormField
{
678 protected $mValidationCallback;
679 protected $mFilterCallback;
682 protected $mLabel; # String label. Set on construction
684 protected $mClass = '';
689 * This function must be implemented to return the HTML to generate
690 * the input object itself. It should not implement the surrounding
691 * table cells/rows, or labels/help messages.
692 * @param $value String the value to set the input to; eg a default
693 * text for a text input.
694 * @return String valid HTML.
696 abstract function getInputHTML( $value );
699 * Override this function to add specific validation checks on the
700 * field input. Don't forget to call parent::validate() to ensure
701 * that the user-defined callback mValidationCallback is still run
702 * @param $value String the value the field was submitted with
703 * @param $alldata Array the data collected from the form
704 * @return Mixed Bool true on success, or String error to display.
706 function validate( $value, $alldata ) {
707 if ( isset( $this->mValidationCallback
) ) {
708 return call_user_func( $this->mValidationCallback
, $value, $alldata );
714 function filter( $value, $alldata ) {
715 if ( isset( $this->mFilterCallback
) ) {
716 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
723 * Should this field have a label, or is there no input element with the
724 * appropriate id for the label to point to?
726 * @return bool True to output a label, false to suppress
728 protected function needsLabel() {
733 * Get the value that this input has been set to from a posted form,
734 * or the input's default value if it has not been set.
735 * @param $request WebRequest
736 * @return String the value
738 function loadDataFromRequest( $request ) {
739 if ( $request->getCheck( $this->mName
) ) {
740 return $request->getText( $this->mName
);
742 return $this->getDefault();
747 * Initialise the object
748 * @param $params Associative Array. See HTMLForm doc for syntax.
750 function __construct( $params ) {
751 $this->mParams
= $params;
753 # Generate the label from a message, if possible
754 if ( isset( $params['label-message'] ) ) {
755 $msgInfo = $params['label-message'];
757 if ( is_array( $msgInfo ) ) {
758 $msg = array_shift( $msgInfo );
764 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
765 } elseif ( isset( $params['label'] ) ) {
766 $this->mLabel
= $params['label'];
769 if ( isset( $params['name'] ) ) {
770 $name = $params['name'];
771 $validName = Sanitizer
::escapeId( $name );
773 if ( $name != $validName ) {
774 throw new MWException( "Invalid name '$name' passed to " . __METHOD__
);
777 $this->mName
= 'wp' . $name;
778 $this->mID
= 'mw-input-' . $name;
781 if ( isset( $params['default'] ) ) {
782 $this->mDefault
= $params['default'];
785 if ( isset( $params['id'] ) ) {
787 $validId = Sanitizer
::escapeId( $id );
789 if ( $id != $validId ) {
790 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
796 if ( isset( $params['cssclass'] ) ) {
797 $this->mClass
= $params['cssclass'];
800 if ( isset( $params['validation-callback'] ) ) {
801 $this->mValidationCallback
= $params['validation-callback'];
804 if ( isset( $params['filter-callback'] ) ) {
805 $this->mFilterCallback
= $params['filter-callback'];
810 * Get the complete table row for the input, including help text,
811 * labels, and whatever.
812 * @param $value String the value to set the input to.
813 * @return String complete HTML table row.
815 function getTableRow( $value ) {
816 # Check for invalid data.
819 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
821 $cellAttributes = array();
822 $verticalLabel = false;
824 if ( !empty($this->mParams
['vertical-label']) ) {
825 $cellAttributes['colspan'] = 2;
826 $verticalLabel = true;
829 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
832 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
835 $label = $this->getLabelHtml( $cellAttributes );
836 $field = Html
::rawElement(
838 array( 'class' => 'mw-input' ) +
$cellAttributes,
839 $this->getInputHTML( $value ) . "\n$errors"
842 $fieldType = get_class( $this );
844 if ($verticalLabel) {
845 $html = Html
::rawElement( 'tr',
846 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
847 $html .= Html
::rawElement( 'tr',
848 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
851 $html = Html
::rawElement( 'tr',
852 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
858 if ( isset( $this->mParams
['help-message'] ) ) {
859 $msg = $this->mParams
['help-message'];
860 $helptext = wfMsgExt( $msg, 'parseinline' );
861 if ( wfEmptyMsg( $msg, $helptext ) ) {
865 } elseif ( isset( $this->mParams
['help'] ) ) {
866 $helptext = $this->mParams
['help'];
869 if ( !is_null( $helptext ) ) {
870 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
872 $row = Html
::rawElement( 'tr', array(), $row );
879 function getLabel() {
880 return $this->mLabel
;
882 function getLabelHtml( $cellAttributes = array() ) {
883 # Don't output a for= attribute for labels with no associated input.
884 # Kind of hacky here, possibly we don't want these to be <label>s at all.
887 if ( $this->needsLabel() ) {
888 $for['for'] = $this->mID
;
891 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
892 Html
::rawElement( 'label', $for, $this->getLabel() )
896 function getDefault() {
897 if ( isset( $this->mDefault
) ) {
898 return $this->mDefault
;
905 * Returns the attributes required for the tooltip and accesskey.
907 * @return array Attributes
909 public function getTooltipAndAccessKey() {
910 if ( empty( $this->mParams
['tooltip'] ) ) {
916 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
920 * flatten an array of options to a single array, for instance,
921 * a set of <options> inside <optgroups>.
922 * @param $options Associative Array with values either Strings
924 * @return Array flattened input
926 public static function flattenOptions( $options ) {
929 foreach ( $options as $value ) {
930 if ( is_array( $value ) ) {
931 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
933 $flatOpts[] = $value;
941 class HTMLTextField
extends HTMLFormField
{
943 return isset( $this->mParams
['size'] )
944 ?
$this->mParams
['size']
948 function getInputHTML( $value ) {
951 'name' => $this->mName
,
952 'size' => $this->getSize(),
954 ) +
$this->getTooltipAndAccessKey();
956 if ( isset( $this->mParams
['maxlength'] ) ) {
957 $attribs['maxlength'] = $this->mParams
['maxlength'];
960 if ( !empty( $this->mParams
['disabled'] ) ) {
961 $attribs['disabled'] = 'disabled';
964 # TODO: Enforce pattern, step, required, readonly on the server side as
966 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
967 'placeholder' ) as $param ) {
968 if ( isset( $this->mParams
[$param] ) ) {
969 $attribs[$param] = $this->mParams
[$param];
973 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
974 if ( isset( $this->mParams
[$param] ) ) {
975 $attribs[$param] = '';
979 # Implement tiny differences between some field variants
980 # here, rather than creating a new class for each one which
981 # is essentially just a clone of this one.
982 if ( isset( $this->mParams
['type'] ) ) {
983 switch ( $this->mParams
['type'] ) {
985 $attribs['type'] = 'email';
988 $attribs['type'] = 'number';
991 $attribs['type'] = 'number';
992 $attribs['step'] = 'any';
997 $attribs['type'] = $this->mParams
['type'];
1002 return Html
::element( 'input', $attribs );
1005 public function validate( $value, $alldata ) {
1006 $p = parent
::validate( $value, $alldata );
1008 if ( $p !== true ) {
1012 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
1013 return wfMsgExt( 'htmlform-required', 'parseinline' );
1019 class HTMLTextAreaField
extends HTMLFormField
{
1020 function getCols() {
1021 return isset( $this->mParams
['cols'] )
1022 ?
$this->mParams
['cols']
1026 function getRows() {
1027 return isset( $this->mParams
['rows'] )
1028 ?
$this->mParams
['rows']
1032 function getInputHTML( $value ) {
1035 'name' => $this->mName
,
1036 'cols' => $this->getCols(),
1037 'rows' => $this->getRows(),
1038 ) +
$this->getTooltipAndAccessKey();
1041 if ( !empty( $this->mParams
['disabled'] ) ) {
1042 $attribs['disabled'] = 'disabled';
1045 if ( !empty( $this->mParams
['readonly'] ) ) {
1046 $attribs['readonly'] = 'readonly';
1049 foreach ( array( 'required', 'autofocus' ) as $param ) {
1050 if ( isset( $this->mParams
[$param] ) ) {
1051 $attribs[$param] = '';
1055 return Html
::element( 'textarea', $attribs, $value );
1058 public function validate( $value, $alldata ) {
1059 $p = parent
::validate( $value, $alldata );
1061 if ( $p !== true ) {
1065 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
1066 return wfMsgExt( 'htmlform-required', 'parseinline' );
1074 * A field that will contain a numeric value
1076 class HTMLFloatField
extends HTMLTextField
{
1077 function getSize() {
1078 return isset( $this->mParams
['size'] )
1079 ?
$this->mParams
['size']
1083 function validate( $value, $alldata ) {
1084 $p = parent
::validate( $value, $alldata );
1086 if ( $p !== true ) {
1090 if ( floatval( $value ) != $value ) {
1091 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1094 # The "int" part of these message names is rather confusing.
1095 # They make equal sense for all numbers.
1096 if ( isset( $this->mParams
['min'] ) ) {
1097 $min = $this->mParams
['min'];
1099 if ( $min > $value ) {
1100 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1104 if ( isset( $this->mParams
['max'] ) ) {
1105 $max = $this->mParams
['max'];
1107 if ( $max < $value ) {
1108 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1117 * A field that must contain a number
1119 class HTMLIntField
extends HTMLFloatField
{
1120 function validate( $value, $alldata ) {
1121 $p = parent
::validate( $value, $alldata );
1123 if ( $p !== true ) {
1128 && ( !is_numeric( $value ) ||
round( $value ) != $value )
1130 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1140 class HTMLCheckField
extends HTMLFormField
{
1141 function getInputHTML( $value ) {
1142 if ( !empty( $this->mParams
['invert'] ) ) {
1146 $attr = $this->getTooltipAndAccessKey();
1147 $attr['id'] = $this->mID
;
1149 if ( !empty( $this->mParams
['disabled'] ) ) {
1150 $attr['disabled'] = 'disabled';
1153 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1154 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1158 * For a checkbox, the label goes on the right hand side, and is
1159 * added in getInputHTML(), rather than HTMLFormField::getRow()
1161 function getLabel() {
1165 function loadDataFromRequest( $request ) {
1167 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1171 // GetCheck won't work like we want for checks.
1172 if ( $request->getCheck( 'wpEditToken' ) ) {
1173 // XOR has the following truth table, which is what we want
1174 // INVERT VALUE | OUTPUT
1175 // true true | false
1176 // false true | true
1177 // false false | false
1178 // true false | true
1179 return $request->getBool( $this->mName
) xor $invert;
1181 return $this->getDefault();
1187 * A select dropdown field. Basically a wrapper for Xmlselect class
1189 class HTMLSelectField
extends HTMLFormField
{
1190 function validate( $value, $alldata ) {
1191 $p = parent
::validate( $value, $alldata );
1193 if ( $p !== true ) {
1197 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1199 if ( in_array( $value, $validOptions ) )
1202 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1205 function getInputHTML( $value ) {
1206 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1208 # If one of the options' 'name' is int(0), it is automatically selected.
1209 # because PHP sucks and things int(0) == 'some string'.
1210 # Working around this by forcing all of them to strings.
1211 $options = array_map( 'strval', $this->mParams
['options'] );
1213 if ( !empty( $this->mParams
['disabled'] ) ) {
1214 $select->setAttribute( 'disabled', 'disabled' );
1217 $select->addOptions( $options );
1219 return $select->getHTML();
1224 * Select dropdown field, with an additional "other" textbox.
1226 class HTMLSelectOrOtherField
extends HTMLTextField
{
1227 static $jsAdded = false;
1229 function __construct( $params ) {
1230 if ( !in_array( 'other', $params['options'], true ) ) {
1231 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1234 parent
::__construct( $params );
1237 static function forceToStringRecursive( $array ) {
1238 if ( is_array( $array ) ) {
1239 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1241 return strval( $array );
1245 function getInputHTML( $value ) {
1246 $valInSelect = false;
1248 if ( $value !== false ) {
1249 $valInSelect = in_array(
1251 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1255 $selected = $valInSelect ?
$value : 'other';
1257 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1259 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1260 $select->addOptions( $opts );
1262 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1264 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1266 if ( !empty( $this->mParams
['disabled'] ) ) {
1267 $select->setAttribute( 'disabled', 'disabled' );
1268 $tbAttribs['disabled'] = 'disabled';
1271 $select = $select->getHTML();
1273 if ( isset( $this->mParams
['maxlength'] ) ) {
1274 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1277 $textbox = Html
::input(
1278 $this->mName
. '-other',
1279 $valInSelect ?
'' : $value,
1284 return "$select<br />\n$textbox";
1287 function loadDataFromRequest( $request ) {
1288 if ( $request->getCheck( $this->mName
) ) {
1289 $val = $request->getText( $this->mName
);
1291 if ( $val == 'other' ) {
1292 $val = $request->getText( $this->mName
. '-other' );
1297 return $this->getDefault();
1303 * Multi-select field
1305 class HTMLMultiSelectField
extends HTMLFormField
{
1306 function validate( $value, $alldata ) {
1307 $p = parent
::validate( $value, $alldata );
1309 if ( $p !== true ) {
1313 if ( !is_array( $value ) ) {
1317 # If all options are valid, array_intersect of the valid options
1318 # and the provided options will return the provided options.
1319 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1321 $validValues = array_intersect( $value, $validOptions );
1322 if ( count( $validValues ) == count( $value ) ) {
1325 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1329 function getInputHTML( $value ) {
1330 $html = $this->formatOptions( $this->mParams
['options'], $value );
1335 function formatOptions( $options, $value ) {
1340 if ( !empty( $this->mParams
['disabled'] ) ) {
1341 $attribs['disabled'] = 'disabled';
1344 foreach ( $options as $label => $info ) {
1345 if ( is_array( $info ) ) {
1346 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1347 $html .= $this->formatOptions( $info, $value );
1349 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1351 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value, true ),
1352 $attribs +
$thisAttribs );
1353 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1355 $html .= $checkbox . '<br />';
1362 function loadDataFromRequest( $request ) {
1363 # won't work with getCheck
1364 if ( $request->getCheck( 'wpEditToken' ) ) {
1365 $arr = $request->getArray( $this->mName
);
1373 return $this->getDefault();
1377 function getDefault() {
1378 if ( isset( $this->mDefault
) ) {
1379 return $this->mDefault
;
1385 protected function needsLabel() {
1391 * Radio checkbox fields.
1393 class HTMLRadioField
extends HTMLFormField
{
1394 function validate( $value, $alldata ) {
1395 $p = parent
::validate( $value, $alldata );
1397 if ( $p !== true ) {
1401 if ( !is_string( $value ) && !is_int( $value ) ) {
1405 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1407 if ( in_array( $value, $validOptions ) ) {
1410 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1415 * This returns a block of all the radio options, in one cell.
1416 * @see includes/HTMLFormField#getInputHTML()
1418 function getInputHTML( $value ) {
1419 $html = $this->formatOptions( $this->mParams
['options'], $value );
1424 function formatOptions( $options, $value ) {
1428 if ( !empty( $this->mParams
['disabled'] ) ) {
1429 $attribs['disabled'] = 'disabled';
1432 # TODO: should this produce an unordered list perhaps?
1433 foreach ( $options as $label => $info ) {
1434 if ( is_array( $info ) ) {
1435 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1436 $html .= $this->formatOptions( $info, $value );
1438 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1439 $html .= Xml
::radio(
1443 $attribs +
array( 'id' => $id )
1446 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1448 $html .= "<br />\n";
1455 protected function needsLabel() {
1461 * An information field (text blob), not a proper input.
1463 class HTMLInfoField
extends HTMLFormField
{
1464 function __construct( $info ) {
1465 $info['nodata'] = true;
1467 parent
::__construct( $info );
1470 function getInputHTML( $value ) {
1471 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1474 function getTableRow( $value ) {
1475 if ( !empty( $this->mParams
['rawrow'] ) ) {
1479 return parent
::getTableRow( $value );
1482 protected function needsLabel() {
1487 class HTMLHiddenField
extends HTMLFormField
{
1488 public function __construct( $params ) {
1489 parent
::__construct( $params );
1490 # forcing the 'wp' prefix on hidden field names
1492 $this->mName
= substr( $this->mName
, 2 );
1495 public function getTableRow( $value ) {
1498 $params['id'] = $this->mID
;
1501 $this->mParent
->addHiddenField(
1510 public function getInputHTML( $value ) { return ''; }
1514 * Add a submit button inline in the form (as opposed to
1515 * HTMLForm::addButton(), which will add it at the end).
1517 class HTMLSubmitField
extends HTMLFormField
{
1519 function __construct( $info ) {
1520 $info['nodata'] = true;
1521 parent
::__construct( $info );
1524 function getInputHTML( $value ) {
1525 return Xml
::submitButton(
1528 'class' => 'mw-htmlform-submit',
1529 'name' => $this->mName
,
1535 protected function needsLabel() {
1540 class HTMLEditTools
extends HTMLFormField
{
1541 public function getInputHTML( $value ) {
1545 public function getTableRow( $value ) {
1546 return "<tr><td></td><td class=\"mw-input\">"
1547 . '<div class="mw-editTools">'
1548 . wfMsgExt( empty( $this->mParams
['message'] )
1549 ?
'edittools' : $this->mParams
['message'],
1550 array( 'parse', 'content' ) )
1551 . "</div></td></tr>\n";