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;
95 protected $mMethod = 'post';
97 protected $mUseMultipart = false;
98 protected $mHiddenFields = array();
99 protected $mButtons = array();
101 protected $mWrapperLegend = false;
104 * Build a new HTMLForm from an array of field attributes
105 * @param $descriptor Array of Field constructs, as described above
106 * @param $messagePrefix String a prefix to go in front of default messages
108 public function __construct( $descriptor, $messagePrefix = '' ) {
109 $this->mMessagePrefix
= $messagePrefix;
111 // Expand out into a tree.
112 $loadedDescriptor = array();
113 $this->mFlatFields
= array();
115 foreach ( $descriptor as $fieldname => $info ) {
116 $section = isset( $info['section'] )
120 $info['name'] = isset( $info['name'] )
124 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
125 $this->mUseMultipart
= true;
128 $field = self
::loadInputFromParameters( $info );
129 $field->mParent
= $this;
131 $setSection =& $loadedDescriptor;
133 $sectionParts = explode( '/', $section );
135 while ( count( $sectionParts ) ) {
136 $newName = array_shift( $sectionParts );
138 if ( !isset( $setSection[$newName] ) ) {
139 $setSection[$newName] = array();
142 $setSection =& $setSection[$newName];
146 $setSection[$fieldname] = $field;
147 $this->mFlatFields
[$fieldname] = $field;
150 $this->mFieldTree
= $loadedDescriptor;
154 * Add the HTMLForm-specific JavaScript, if it hasn't been
157 static function addJS() {
158 if ( self
::$jsAdded ) return;
162 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
166 * Initialise a new Object for the field
167 * @param $descriptor input Descriptor, as described above
168 * @return HTMLFormField subclass
170 static function loadInputFromParameters( $descriptor ) {
171 if ( isset( $descriptor['class'] ) ) {
172 $class = $descriptor['class'];
173 } elseif ( isset( $descriptor['type'] ) ) {
174 $class = self
::$typeMappings[$descriptor['type']];
175 $descriptor['class'] = $class;
179 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
182 $obj = new $class( $descriptor );
188 * Prepare form for submission
190 function prepareForm() {
191 # Check if we have the info we need
192 if ( ! $this->mTitle
) {
193 throw new MWException( "You must call setTitle() on an HTMLForm" );
196 // FIXME shouldn't this be closer to displayForm() ?
199 # Load data from the request.
204 * Try submitting, with edit token check first
205 * @return Status|boolean
207 function tryAuthorizedSubmit() {
208 global $wgUser, $wgRequest;
209 $editToken = $wgRequest->getVal( 'wpEditToken' );
212 if ( $wgUser->matchEditToken( $editToken ) ) {
213 $result = $this->trySubmit();
219 * The here's-one-I-made-earlier option: do the submission if
220 * posted, or display the form with or without funky valiation
222 * @return Bool or Status whether submission was successful.
225 $this->prepareForm();
227 $result = $this->tryAuthorizedSubmit();
228 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
232 $this->displayForm( $result );
237 * Validate all the fields, and call the submision callback
238 * function if everything is kosher.
239 * @return Mixed Bool true == Successful submission, Bool false
240 * == No submission attempted, anything else == Error to
243 function trySubmit() {
244 # Check for validation
245 foreach ( $this->mFlatFields
as $fieldname => $field ) {
246 if ( !empty( $field->mParams
['nodata'] ) ) {
249 if ( $field->validate(
250 $this->mFieldData
[$fieldname],
254 return isset( $this->mValidationErrorMessage
)
255 ?
$this->mValidationErrorMessage
256 : array( 'htmlform-invalid-input' );
260 $callback = $this->mSubmitCallback
;
262 $data = $this->filterDataForSubmit( $this->mFieldData
);
264 $res = call_user_func( $callback, $data );
270 * Set a callback to a function to do something with the form
271 * once it's been successfully validated.
272 * @param $cb String function name. The function will be passed
273 * the output from HTMLForm::filterDataForSubmit, and must
274 * return Bool true on success, Bool false if no submission
275 * was attempted, or String HTML output to display on error.
277 function setSubmitCallback( $cb ) {
278 $this->mSubmitCallback
= $cb;
282 * Set a message to display on a validation error.
283 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
284 * (so each entry can be either a String or Array)
286 function setValidationErrorMessage( $msg ) {
287 $this->mValidationErrorMessage
= $msg;
291 * Set the introductory message, overwriting any existing message.
292 * @param $msg String complete text of message to display
294 function setIntro( $msg ) { $this->mPre
= $msg; }
297 * Add introductory text.
298 * @param $msg String complete text of message to display
300 function addPreText( $msg ) { $this->mPre
.= $msg; }
303 * Add header text, inside the form.
304 * @param $msg String complete text of message to display
306 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
309 * Add footer text, inside the form.
310 * @param $msg String complete text of message to display
312 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
315 * Add text to the end of the display.
316 * @param $msg String complete text of message to display
318 function addPostText( $msg ) { $this->mPost
.= $msg; }
321 * Add a hidden field to the output
322 * @param $name String field name
323 * @param $value String field value
324 * @param $attribs Array
326 public function addHiddenField( $name, $value, $attribs = array() ) {
327 $attribs +
= array( 'name' => $name );
328 $this->mHiddenFields
[] = array( $value, $attribs );
331 public function addButton( $name, $value, $id = null, $attribs = null ) {
332 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
336 * Display the form (sending to wgOut), with an appropriate error
337 * message or stack of messages, and any validation errors, etc.
338 * @param $submitResult Mixed output from HTMLForm::trySubmit()
340 function displayForm( $submitResult ) {
344 . $this->getErrors( $submitResult )
347 . $this->getHiddenFields()
348 . $this->getButtons()
352 $html = $this->wrapForm( $html );
362 * Wrap the form innards in an actual <form> element
363 * @param $html String HTML contents to wrap.
364 * @return String wrapped HTML.
366 function wrapForm( $html ) {
368 # Include a <fieldset> wrapper for style, if requested.
369 if ( $this->mWrapperLegend
!== false ) {
370 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
372 # Use multipart/form-data
373 $encType = $this->mUseMultipart
374 ?
'multipart/form-data'
375 : 'application/x-www-form-urlencoded';
378 'action' => $this->getTitle()->getFullURL(),
379 'method' => $this->mMethod
,
380 'class' => 'visualClear',
381 'enctype' => $encType,
383 if ( !empty( $this->mId
) ) {
384 $attribs['id'] = $this->mId
;
387 return Html
::rawElement( 'form', $attribs, $html );
391 * Get the hidden fields that should go inside the form.
392 * @return String HTML.
394 function getHiddenFields() {
398 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
399 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
401 foreach ( $this->mHiddenFields
as $data ) {
402 list( $value, $attribs ) = $data;
403 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
410 * Get the submit and (potentially) reset buttons.
411 * @return String HTML.
413 function getButtons() {
417 if ( isset( $this->mSubmitID
) ) {
418 $attribs['id'] = $this->mSubmitID
;
421 if ( isset( $this->mSubmitName
) ) {
422 $attribs['name'] = $this->mSubmitName
;
425 if ( isset( $this->mSubmitTooltip
) ) {
427 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
430 $attribs['class'] = 'mw-htmlform-submit';
432 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
434 if ( $this->mShowReset
) {
435 $html .= Html
::element(
439 'value' => wfMsg( 'htmlform-reset' )
444 foreach ( $this->mButtons
as $button ) {
447 'name' => $button['name'],
448 'value' => $button['value']
451 if ( $button['attribs'] ) {
452 $attrs +
= $button['attribs'];
455 if ( isset( $button['id'] ) ) {
456 $attrs['id'] = $button['id'];
459 $html .= Html
::element( 'input', $attrs );
466 * Get the whole body of the form.
469 return $this->displaySection( $this->mFieldTree
);
473 * Format and display an error message stack.
474 * @param $errors Mixed String or Array of message keys
477 function getErrors( $errors ) {
478 if ( $errors instanceof Status
) {
480 $errorstr = $wgOut->parse( $errors->getWikiText() );
481 } elseif ( is_array( $errors ) ) {
482 $errorstr = $this->formatErrors( $errors );
488 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
493 * Format a stack of error messages into a single HTML string
494 * @param $errors Array of message keys/values
495 * @return String HTML, a <ul> list of errors
497 static function formatErrors( $errors ) {
500 foreach ( $errors as $error ) {
501 if ( is_array( $error ) ) {
502 $msg = array_shift( $error );
508 $errorstr .= Html
::rawElement(
511 wfMsgExt( $msg, array( 'parseinline' ), $error )
515 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
521 * Set the text for the submit button
522 * @param $t String plaintext.
524 function setSubmitText( $t ) {
525 $this->mSubmitText
= $t;
529 * Get the text for the submit button, either customised or a default.
530 * @return unknown_type
532 function getSubmitText() {
533 return $this->mSubmitText
535 : wfMsg( 'htmlform-submit' );
538 public function setSubmitName( $name ) {
539 $this->mSubmitName
= $name;
542 public function setSubmitTooltip( $name ) {
543 $this->mSubmitTooltip
= $name;
547 * Set the id for the submit button.
548 * @param $t String. FIXME: Integrity is *not* validated
550 function setSubmitID( $t ) {
551 $this->mSubmitID
= $t;
554 public function setId( $id ) {
558 * Prompt the whole form to be wrapped in a <fieldset>, with
559 * this text as its <legend> element.
560 * @param $legend String HTML to go inside the <legend> element.
563 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
566 * Set the prefix for various default messages
567 * TODO: currently only used for the <fieldset> legend on forms
568 * with multiple sections; should be used elsewhre?
571 function setMessagePrefix( $p ) {
572 $this->mMessagePrefix
= $p;
576 * Set the title for form submission
577 * @param $t Title of page the form is on/should be posted to
579 function setTitle( $t ) {
587 function getTitle() {
588 return $this->mTitle
;
592 * Set the method used to submit the form
593 * @param $method String
595 public function setMethod( $method='post' ){
596 $this->mMethod
= $method;
603 function displaySection( $fields, $sectionName = '' ) {
605 $subsectionHtml = '';
606 $hasLeftColumn = false;
608 foreach ( $fields as $key => $value ) {
609 if ( is_object( $value ) ) {
610 $v = empty( $value->mParams
['nodata'] )
611 ?
$this->mFieldData
[$key]
612 : $value->getDefault();
613 $tableHtml .= $value->getTableRow( $v );
615 if ( $value->getLabel() != ' ' )
616 $hasLeftColumn = true;
617 } elseif ( is_array( $value ) ) {
618 $section = $this->displaySection( $value, $key );
619 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
620 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
626 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
627 $classes[] = 'mw-htmlform-nolabel';
631 'class' => implode( ' ', $classes ),
634 if ( $sectionName ) {
635 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
638 $tableHtml = Html
::rawElement( 'table', $attribs,
639 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
641 return $subsectionHtml . "\n" . $tableHtml;
645 * Construct the form fields from the Descriptor array
647 function loadData() {
650 $fieldData = array();
652 foreach ( $this->mFlatFields
as $fieldname => $field ) {
653 if ( !empty( $field->mParams
['nodata'] ) ) {
655 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
656 $fieldData[$fieldname] = $field->getDefault();
658 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
663 foreach ( $fieldData as $name => &$value ) {
664 $field = $this->mFlatFields
[$name];
665 $value = $field->filter( $value, $this->mFlatFields
);
668 $this->mFieldData
= $fieldData;
672 * Stop a reset button being shown for this form
673 * @param $suppressReset Bool set to false to re-enable the
676 function suppressReset( $suppressReset = true ) {
677 $this->mShowReset
= !$suppressReset;
681 * Overload this if you want to apply special filtration routines
682 * to the form as a whole, after it's submitted but before it's
685 * @return unknown_type
687 function filterDataForSubmit( $data ) {
693 * The parent class to generate form fields. Any field type should
694 * be a subclass of this.
696 abstract class HTMLFormField
{
698 protected $mValidationCallback;
699 protected $mFilterCallback;
702 protected $mLabel; # String label. Set on construction
704 protected $mClass = '';
709 * This function must be implemented to return the HTML to generate
710 * the input object itself. It should not implement the surrounding
711 * table cells/rows, or labels/help messages.
712 * @param $value String the value to set the input to; eg a default
713 * text for a text input.
714 * @return String valid HTML.
716 abstract function getInputHTML( $value );
719 * Override this function to add specific validation checks on the
720 * field input. Don't forget to call parent::validate() to ensure
721 * that the user-defined callback mValidationCallback is still run
722 * @param $value String the value the field was submitted with
723 * @param $alldata Array the data collected from the form
724 * @return Mixed Bool true on success, or String error to display.
726 function validate( $value, $alldata ) {
727 if ( isset( $this->mValidationCallback
) ) {
728 return call_user_func( $this->mValidationCallback
, $value, $alldata );
731 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
732 return wfMsgExt( 'htmlform-required', 'parseinline' );
738 function filter( $value, $alldata ) {
739 if ( isset( $this->mFilterCallback
) ) {
740 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
747 * Should this field have a label, or is there no input element with the
748 * appropriate id for the label to point to?
750 * @return bool True to output a label, false to suppress
752 protected function needsLabel() {
757 * Get the value that this input has been set to from a posted form,
758 * or the input's default value if it has not been set.
759 * @param $request WebRequest
760 * @return String the value
762 function loadDataFromRequest( $request ) {
763 if ( $request->getCheck( $this->mName
) ) {
764 return $request->getText( $this->mName
);
766 return $this->getDefault();
771 * Initialise the object
772 * @param $params Associative Array. See HTMLForm doc for syntax.
774 function __construct( $params ) {
775 $this->mParams
= $params;
777 # Generate the label from a message, if possible
778 if ( isset( $params['label-message'] ) ) {
779 $msgInfo = $params['label-message'];
781 if ( is_array( $msgInfo ) ) {
782 $msg = array_shift( $msgInfo );
788 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
789 } elseif ( isset( $params['label'] ) ) {
790 $this->mLabel
= $params['label'];
793 if ( isset( $params['name'] ) ) {
794 $name = $params['name'];
795 $validName = Sanitizer
::escapeId( $name );
797 if ( $name != $validName ) {
798 throw new MWException( "Invalid name '$name' passed to " . __METHOD__
);
801 $this->mName
= 'wp' . $name;
802 $this->mID
= 'mw-input-' . $name;
805 if ( isset( $params['default'] ) ) {
806 $this->mDefault
= $params['default'];
809 if ( isset( $params['id'] ) ) {
811 $validId = Sanitizer
::escapeId( $id );
813 if ( $id != $validId ) {
814 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
820 if ( isset( $params['cssclass'] ) ) {
821 $this->mClass
= $params['cssclass'];
824 if ( isset( $params['validation-callback'] ) ) {
825 $this->mValidationCallback
= $params['validation-callback'];
828 if ( isset( $params['filter-callback'] ) ) {
829 $this->mFilterCallback
= $params['filter-callback'];
834 * Get the complete table row for the input, including help text,
835 * labels, and whatever.
836 * @param $value String the value to set the input to.
837 * @return String complete HTML table row.
839 function getTableRow( $value ) {
840 # Check for invalid data.
843 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
845 $cellAttributes = array();
846 $verticalLabel = false;
848 if ( !empty($this->mParams
['vertical-label']) ) {
849 $cellAttributes['colspan'] = 2;
850 $verticalLabel = true;
853 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
856 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
859 $label = $this->getLabelHtml( $cellAttributes );
860 $field = Html
::rawElement(
862 array( 'class' => 'mw-input' ) +
$cellAttributes,
863 $this->getInputHTML( $value ) . "\n$errors"
866 $fieldType = get_class( $this );
868 if ($verticalLabel) {
869 $html = Html
::rawElement( 'tr',
870 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
871 $html .= Html
::rawElement( 'tr',
872 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
875 $html = Html
::rawElement( 'tr',
876 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
882 if ( isset( $this->mParams
['help-message'] ) ) {
883 $msg = $this->mParams
['help-message'];
884 $helptext = wfMsgExt( $msg, 'parseinline' );
885 if ( wfEmptyMsg( $msg, $helptext ) ) {
889 } elseif ( isset( $this->mParams
['help'] ) ) {
890 $helptext = $this->mParams
['help'];
893 if ( !is_null( $helptext ) ) {
894 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
896 $row = Html
::rawElement( 'tr', array(), $row );
903 function getLabel() {
904 return $this->mLabel
;
906 function getLabelHtml( $cellAttributes = array() ) {
907 # Don't output a for= attribute for labels with no associated input.
908 # Kind of hacky here, possibly we don't want these to be <label>s at all.
911 if ( $this->needsLabel() ) {
912 $for['for'] = $this->mID
;
915 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
916 Html
::rawElement( 'label', $for, $this->getLabel() )
920 function getDefault() {
921 if ( isset( $this->mDefault
) ) {
922 return $this->mDefault
;
929 * Returns the attributes required for the tooltip and accesskey.
931 * @return array Attributes
933 public function getTooltipAndAccessKey() {
934 if ( empty( $this->mParams
['tooltip'] ) ) {
940 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
944 * flatten an array of options to a single array, for instance,
945 * a set of <options> inside <optgroups>.
946 * @param $options Associative Array with values either Strings
948 * @return Array flattened input
950 public static function flattenOptions( $options ) {
953 foreach ( $options as $value ) {
954 if ( is_array( $value ) ) {
955 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
957 $flatOpts[] = $value;
965 class HTMLTextField
extends HTMLFormField
{
967 return isset( $this->mParams
['size'] )
968 ?
$this->mParams
['size']
972 function getInputHTML( $value ) {
975 'name' => $this->mName
,
976 'size' => $this->getSize(),
978 ) +
$this->getTooltipAndAccessKey();
980 if ( isset( $this->mParams
['maxlength'] ) ) {
981 $attribs['maxlength'] = $this->mParams
['maxlength'];
984 if ( !empty( $this->mParams
['disabled'] ) ) {
985 $attribs['disabled'] = 'disabled';
988 # TODO: Enforce pattern, step, required, readonly on the server side as
990 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
991 'placeholder' ) as $param ) {
992 if ( isset( $this->mParams
[$param] ) ) {
993 $attribs[$param] = $this->mParams
[$param];
997 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
998 if ( isset( $this->mParams
[$param] ) ) {
999 $attribs[$param] = '';
1003 # Implement tiny differences between some field variants
1004 # here, rather than creating a new class for each one which
1005 # is essentially just a clone of this one.
1006 if ( isset( $this->mParams
['type'] ) ) {
1007 switch ( $this->mParams
['type'] ) {
1009 $attribs['type'] = 'email';
1012 $attribs['type'] = 'number';
1015 $attribs['type'] = 'number';
1016 $attribs['step'] = 'any';
1021 $attribs['type'] = $this->mParams
['type'];
1026 return Html
::element( 'input', $attribs );
1029 class HTMLTextAreaField
extends HTMLFormField
{
1030 function getCols() {
1031 return isset( $this->mParams
['cols'] )
1032 ?
$this->mParams
['cols']
1036 function getRows() {
1037 return isset( $this->mParams
['rows'] )
1038 ?
$this->mParams
['rows']
1042 function getInputHTML( $value ) {
1045 'name' => $this->mName
,
1046 'cols' => $this->getCols(),
1047 'rows' => $this->getRows(),
1048 ) +
$this->getTooltipAndAccessKey();
1051 if ( !empty( $this->mParams
['disabled'] ) ) {
1052 $attribs['disabled'] = 'disabled';
1055 if ( !empty( $this->mParams
['readonly'] ) ) {
1056 $attribs['readonly'] = 'readonly';
1059 foreach ( array( 'required', 'autofocus' ) as $param ) {
1060 if ( isset( $this->mParams
[$param] ) ) {
1061 $attribs[$param] = '';
1065 return Html
::element( 'textarea', $attribs, $value );
1070 * A field that will contain a numeric value
1072 class HTMLFloatField
extends HTMLTextField
{
1073 function getSize() {
1074 return isset( $this->mParams
['size'] )
1075 ?
$this->mParams
['size']
1079 function validate( $value, $alldata ) {
1080 $p = parent
::validate( $value, $alldata );
1082 if ( $p !== true ) {
1086 $value = trim( $value );
1088 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1089 # with the addition that a leading '+' sign is ok.
1090 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $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 ) {
1127 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1128 # with the addition that a leading '+' sign is ok. Note that leading zeros
1129 # are fine, and will be left in the input, which is useful for things like
1130 # phone numbers when you know that they are integers (the HTML5 type=tel
1131 # input does not require its value to be numeric). If you want a tidier
1132 # value to, eg, save in the DB, clean it up with intval().
1133 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1135 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1145 class HTMLCheckField
extends HTMLFormField
{
1146 function getInputHTML( $value ) {
1147 if ( !empty( $this->mParams
['invert'] ) ) {
1151 $attr = $this->getTooltipAndAccessKey();
1152 $attr['id'] = $this->mID
;
1154 if ( !empty( $this->mParams
['disabled'] ) ) {
1155 $attr['disabled'] = 'disabled';
1158 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1159 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1163 * For a checkbox, the label goes on the right hand side, and is
1164 * added in getInputHTML(), rather than HTMLFormField::getRow()
1166 function getLabel() {
1170 function loadDataFromRequest( $request ) {
1172 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1176 // GetCheck won't work like we want for checks.
1177 if ( $request->getCheck( 'wpEditToken' ) ) {
1178 // XOR has the following truth table, which is what we want
1179 // INVERT VALUE | OUTPUT
1180 // true true | false
1181 // false true | true
1182 // false false | false
1183 // true false | true
1184 return $request->getBool( $this->mName
) xor $invert;
1186 return $this->getDefault();
1192 * A select dropdown field. Basically a wrapper for Xmlselect class
1194 class HTMLSelectField
extends HTMLFormField
{
1195 function validate( $value, $alldata ) {
1196 $p = parent
::validate( $value, $alldata );
1198 if ( $p !== true ) {
1202 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1204 if ( in_array( $value, $validOptions ) )
1207 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1210 function getInputHTML( $value ) {
1211 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1213 # If one of the options' 'name' is int(0), it is automatically selected.
1214 # because PHP sucks and things int(0) == 'some string'.
1215 # Working around this by forcing all of them to strings.
1216 $options = array_map( 'strval', $this->mParams
['options'] );
1218 if ( !empty( $this->mParams
['disabled'] ) ) {
1219 $select->setAttribute( 'disabled', 'disabled' );
1222 $select->addOptions( $options );
1224 return $select->getHTML();
1229 * Select dropdown field, with an additional "other" textbox.
1231 class HTMLSelectOrOtherField
extends HTMLTextField
{
1232 static $jsAdded = false;
1234 function __construct( $params ) {
1235 if ( !in_array( 'other', $params['options'], true ) ) {
1236 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1239 parent
::__construct( $params );
1242 static function forceToStringRecursive( $array ) {
1243 if ( is_array( $array ) ) {
1244 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1246 return strval( $array );
1250 function getInputHTML( $value ) {
1251 $valInSelect = false;
1253 if ( $value !== false ) {
1254 $valInSelect = in_array(
1256 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1260 $selected = $valInSelect ?
$value : 'other';
1262 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1264 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1265 $select->addOptions( $opts );
1267 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1269 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1271 if ( !empty( $this->mParams
['disabled'] ) ) {
1272 $select->setAttribute( 'disabled', 'disabled' );
1273 $tbAttribs['disabled'] = 'disabled';
1276 $select = $select->getHTML();
1278 if ( isset( $this->mParams
['maxlength'] ) ) {
1279 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1282 $textbox = Html
::input(
1283 $this->mName
. '-other',
1284 $valInSelect ?
'' : $value,
1289 return "$select<br />\n$textbox";
1292 function loadDataFromRequest( $request ) {
1293 if ( $request->getCheck( $this->mName
) ) {
1294 $val = $request->getText( $this->mName
);
1296 if ( $val == 'other' ) {
1297 $val = $request->getText( $this->mName
. '-other' );
1302 return $this->getDefault();
1308 * Multi-select field
1310 class HTMLMultiSelectField
extends HTMLFormField
{
1311 function validate( $value, $alldata ) {
1312 $p = parent
::validate( $value, $alldata );
1314 if ( $p !== true ) {
1318 if ( !is_array( $value ) ) {
1322 # If all options are valid, array_intersect of the valid options
1323 # and the provided options will return the provided options.
1324 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1326 $validValues = array_intersect( $value, $validOptions );
1327 if ( count( $validValues ) == count( $value ) ) {
1330 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1334 function getInputHTML( $value ) {
1335 $html = $this->formatOptions( $this->mParams
['options'], $value );
1340 function formatOptions( $options, $value ) {
1345 if ( !empty( $this->mParams
['disabled'] ) ) {
1346 $attribs['disabled'] = 'disabled';
1349 foreach ( $options as $label => $info ) {
1350 if ( is_array( $info ) ) {
1351 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1352 $html .= $this->formatOptions( $info, $value );
1354 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1356 $checkbox = Xml
::check(
1357 $this->mName
. '[]',
1358 in_array( $info, $value, true ),
1359 $attribs +
$thisAttribs );
1360 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1362 $html .= $checkbox . '<br />';
1369 function loadDataFromRequest( $request ) {
1370 # won't work with getCheck
1371 if ( $request->getCheck( 'wpEditToken' ) ) {
1372 $arr = $request->getArray( $this->mName
);
1380 return $this->getDefault();
1384 function getDefault() {
1385 if ( isset( $this->mDefault
) ) {
1386 return $this->mDefault
;
1392 protected function needsLabel() {
1398 * Radio checkbox fields.
1400 class HTMLRadioField
extends HTMLFormField
{
1401 function validate( $value, $alldata ) {
1402 $p = parent
::validate( $value, $alldata );
1404 if ( $p !== true ) {
1408 if ( !is_string( $value ) && !is_int( $value ) ) {
1412 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1414 if ( in_array( $value, $validOptions ) ) {
1417 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1422 * This returns a block of all the radio options, in one cell.
1423 * @see includes/HTMLFormField#getInputHTML()
1425 function getInputHTML( $value ) {
1426 $html = $this->formatOptions( $this->mParams
['options'], $value );
1431 function formatOptions( $options, $value ) {
1435 if ( !empty( $this->mParams
['disabled'] ) ) {
1436 $attribs['disabled'] = 'disabled';
1439 # TODO: should this produce an unordered list perhaps?
1440 foreach ( $options as $label => $info ) {
1441 if ( is_array( $info ) ) {
1442 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1443 $html .= $this->formatOptions( $info, $value );
1445 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1446 $html .= Xml
::radio(
1450 $attribs +
array( 'id' => $id )
1453 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1455 $html .= "<br />\n";
1462 protected function needsLabel() {
1468 * An information field (text blob), not a proper input.
1470 class HTMLInfoField
extends HTMLFormField
{
1471 function __construct( $info ) {
1472 $info['nodata'] = true;
1474 parent
::__construct( $info );
1477 function getInputHTML( $value ) {
1478 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1481 function getTableRow( $value ) {
1482 if ( !empty( $this->mParams
['rawrow'] ) ) {
1486 return parent
::getTableRow( $value );
1489 protected function needsLabel() {
1494 class HTMLHiddenField
extends HTMLFormField
{
1495 public function __construct( $params ) {
1496 parent
::__construct( $params );
1497 # forcing the 'wp' prefix on hidden field names
1499 $this->mName
= substr( $this->mName
, 2 );
1501 # Per HTML5 spec, hidden fields cannot be 'required'
1502 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1503 unset( $this->mParams
['required'] );
1506 public function getTableRow( $value ) {
1509 $params['id'] = $this->mID
;
1512 $this->mParent
->addHiddenField(
1521 public function getInputHTML( $value ) { return ''; }
1525 * Add a submit button inline in the form (as opposed to
1526 * HTMLForm::addButton(), which will add it at the end).
1528 class HTMLSubmitField
extends HTMLFormField
{
1530 function __construct( $info ) {
1531 $info['nodata'] = true;
1532 parent
::__construct( $info );
1535 function getInputHTML( $value ) {
1536 return Xml
::submitButton(
1539 'class' => 'mw-htmlform-submit',
1540 'name' => $this->mName
,
1546 protected function needsLabel() {
1551 * Button cannot be invalid
1553 public function validate( $value, $alldata ){
1558 class HTMLEditTools
extends HTMLFormField
{
1559 public function getInputHTML( $value ) {
1563 public function getTableRow( $value ) {
1564 return "<tr><td></td><td class=\"mw-input\">"
1565 . '<div class="mw-editTools">'
1566 . wfMsgExt( empty( $this->mParams
['message'] )
1567 ?
'edittools' : $this->mParams
['message'],
1568 array( 'parse', 'content' ) )
1569 . "</div></td></tr>\n";