4 * Object handling generic submission, CSRF protection, layout and
5 * other logic for UI forms. in a reusable manner.
7 * In order to generate the form, the HTMLForm object takes an array
8 * structure detailing the form fields available. Each element of the
9 * array is a basic property-list, including the type of field, the
10 * label it is to be given in the form, callbacks for validation and
11 * 'filtering', and other pertinent information.
13 * Field types are implemented as subclasses of the generic HTMLFormField
14 * object, and typically implement at least getInputHTML, which generates
15 * the HTML for the input field to be placed in the table.
17 * The constructor input is an associative array of $fieldname => $info,
18 * where $info is an Associative Array with any of the following:
20 * 'class' -- the subclass of HTMLFormField that will be used
21 * to create the object. *NOT* the CSS class!
22 * 'type' -- roughly translates into the <select> type attribute.
23 * if 'class' is not specified, this is used as a map
24 * through HTMLForm::$typeMappings to get the class name.
25 * 'default' -- default value when the form is displayed
26 * 'id' -- HTML id attribute
27 * 'cssclass' -- CSS class
28 * 'options' -- varies according to the specific object.
29 * 'label-message' -- message key for a message to use as the label.
30 * can be an array of msg key and then parameters to
32 * 'label' -- alternatively, a raw text message. Overridden by
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 * 'required' -- passed through to the object, indicating that it
38 * is a required field.
39 * 'size' -- the length of text fields
40 * 'filter-callback -- a function name to give you the chance to
41 * massage the inputted value before it's processed.
42 * @see HTMLForm::filter()
43 * 'validation-callback' -- a function name to give you the chance
44 * to impose extra validation on the field input.
45 * @see HTMLForm::validate()
47 * TODO: Document 'section' / 'subsection' stuff
50 static $jsAdded = false;
52 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
53 static $typeMappings = array(
54 'text' => 'HTMLTextField',
55 'textarea' => 'HTMLTextAreaField',
56 'select' => 'HTMLSelectField',
57 'radio' => 'HTMLRadioField',
58 'multiselect' => 'HTMLMultiSelectField',
59 'check' => 'HTMLCheckField',
60 'toggle' => 'HTMLCheckField',
61 'int' => 'HTMLIntField',
62 'float' => 'HTMLFloatField',
63 'info' => 'HTMLInfoField',
64 'selectorother' => 'HTMLSelectOrOtherField',
65 'submit' => 'HTMLSubmitField',
66 'hidden' => 'HTMLHiddenField',
67 'edittools' => 'HTMLEditTools',
69 # HTMLTextField will output the correct type="" attribute automagically.
70 # There are about four zillion other HTML5 input types, like url, but
71 # we don't use those at the moment, so no point in adding all of them.
72 'email' => 'HTMLTextField',
73 'password' => 'HTMLTextField',
76 protected $mMessagePrefix;
77 protected $mFlatFields;
78 protected $mFieldTree;
79 protected $mShowReset = false;
82 protected $mSubmitCallback;
83 protected $mValidationErrorMessage;
86 protected $mHeader = '';
87 protected $mFooter = '';
88 protected $mPost = '';
92 protected $mSubmitName;
93 protected $mSubmitText;
94 protected $mSubmitTooltip;
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;
160 global $wgOut, $wgStylePath;
162 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
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 * The here's-one-I-made-earlier option: do the submission if
189 * posted, or display the form with or without funky valiation
191 * @return Bool whether submission was successful.
198 # Load data from the request.
202 global $wgUser, $wgRequest;
203 $editToken = $wgRequest->getVal( 'wpEditToken' );
206 if ( $wgUser->matchEditToken( $editToken ) )
207 $result = $this->trySubmit();
209 if( $result === true )
213 $this->displayForm( $result );
218 * Validate all the fields, and call the submision callback
219 * function if everything is kosher.
220 * @return Mixed Bool true == Successful submission, Bool false
221 * == No submission attempted, anything else == Error to
224 function trySubmit() {
225 # Check for validation
226 foreach( $this->mFlatFields
as $fieldname => $field ) {
227 if ( !empty( $field->mParams
['nodata'] ) ){
230 if ( $field->validate(
231 $this->mFieldData
[$fieldname],
235 return isset( $this->mValidationErrorMessage
)
236 ?
$this->mValidationErrorMessage
237 : array( 'htmlform-invalid-input' );
241 $callback = $this->mSubmitCallback
;
243 $data = $this->filterDataForSubmit( $this->mFieldData
);
245 $res = call_user_func( $callback, $data );
251 * Set a callback to a function to do something with the form
252 * once it's been successfully validated.
253 * @param $cb String function name. The function will be passed
254 * the output from HTMLForm::filterDataForSubmit, and must
255 * return Bool true on success, Bool false if no submission
256 * was attempted, or String HTML output to display on error.
258 function setSubmitCallback( $cb ) {
259 $this->mSubmitCallback
= $cb;
263 * Set a message to display on a validation error.
264 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
265 * (so each entry can be either a String or Array)
267 function setValidationErrorMessage( $msg ) {
268 $this->mValidationErrorMessage
= $msg;
272 * Set the introductory message, overwriting any existing message.
273 * @param $msg String complete text of message to display
275 function setIntro( $msg ) { $this->mPre
= $msg; }
278 * Add introductory text.
279 * @param $msg String complete text of message to display
281 function addPreText( $msg ) { $this->mPre
.= $msg; }
284 * Add header text, inside the form.
285 * @param $msg String complete text of message to display
287 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
290 * Add footer text, inside the form.
291 * @param $msg String complete text of message to display
293 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
296 * Add text to the end of the display.
297 * @param $msg String complete text of message to display
299 function addPostText( $msg ) { $this->mPost
.= $msg; }
302 * Add a hidden field to the output
303 * @param $name String field name
304 * @param $value String field value
305 * @param $attribs Array
307 public function addHiddenField( $name, $value, $attribs=array() ){
308 $this->mHiddenFields
[ $name ] = array( $value, $attribs );
311 public function addButton( $name, $value, $id=null, $attribs=null ){
312 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
316 * Display the form (sending to wgOut), with an appropriate error
317 * message or stack of messages, and any validation errors, etc.
318 * @param $submitResult Mixed output from HTMLForm::trySubmit()
320 function displayForm( $submitResult ) {
324 . $this->getErrors( $submitResult )
327 . $this->getHiddenFields()
328 . $this->getButtons()
332 $html = $this->wrapForm( $html );
342 * Wrap the form innards in an actual <form> element
343 * @param $html String HTML contents to wrap.
344 * @return String wrapped HTML.
346 function wrapForm( $html ) {
348 # Include a <fieldset> wrapper for style, if requested.
349 if ( $this->mWrapperLegend
!== false ){
350 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
352 # Use multipart/form-data
353 $encType = $this->mUseMultipart
354 ?
'multipart/form-data'
355 : 'application/x-www-form-urlencoded';
358 'action' => $this->getTitle()->getFullURL(),
360 'class' => 'visualClear',
361 'enctype' => $encType,
363 if ( !empty( $this->mId
) )
364 $attribs['id'] = $this->mId
;
366 return Html
::rawElement( 'form', $attribs, $html );
370 * Get the hidden fields that should go inside the form.
371 * @return String HTML.
373 function getHiddenFields() {
377 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
378 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
380 foreach( $this->mHiddenFields
as $name => $value ){
381 list( $value, $attribs ) = $value;
382 $html .= Html
::hidden( $name, $value, $attribs ) . "\n";
389 * Get the submit and (potentially) reset buttons.
390 * @return String HTML.
392 function getButtons() {
397 if ( isset( $this->mSubmitID
) )
398 $attribs['id'] = $this->mSubmitID
;
399 if ( isset( $this->mSubmitName
) )
400 $attribs['name'] = $this->mSubmitName
;
401 if ( isset( $this->mSubmitTooltip
) ) {
403 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
406 $attribs['class'] = 'mw-htmlform-submit';
408 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
410 if( $this->mShowReset
) {
411 $html .= Html
::element(
415 'value' => wfMsg( 'htmlform-reset' )
420 foreach( $this->mButtons
as $button ){
423 'name' => $button['name'],
424 'value' => $button['value']
426 if ( $button['attribs'] )
427 $attrs +
= $button['attribs'];
428 if( isset( $button['id'] ) )
429 $attrs['id'] = $button['id'];
430 $html .= Html
::element( 'input', $attrs );
437 * Get the whole body of the form.
440 return $this->displaySection( $this->mFieldTree
);
444 * Format and display an error message stack.
445 * @param $errors Mixed String or Array of message keys
448 function getErrors( $errors ) {
449 if ( is_array( $errors ) ) {
450 $errorstr = $this->formatErrors( $errors );
456 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
461 * Format a stack of error messages into a single HTML string
462 * @param $errors Array of message keys/values
463 * @return String HTML, a <ul> list of errors
465 static function formatErrors( $errors ) {
467 foreach ( $errors as $error ) {
468 if( is_array( $error ) ) {
469 $msg = array_shift( $error );
474 $errorstr .= Html
::rawElement(
477 wfMsgExt( $msg, array( 'parseinline' ), $error )
481 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
487 * Set the text for the submit button
488 * @param $t String plaintext.
490 function setSubmitText( $t ) {
491 $this->mSubmitText
= $t;
495 * Get the text for the submit button, either customised or a default.
496 * @return unknown_type
498 function getSubmitText() {
499 return $this->mSubmitText
501 : wfMsg( 'htmlform-submit' );
504 public function setSubmitName( $name ) {
505 $this->mSubmitName
= $name;
508 public function setSubmitTooltip( $name ) {
509 $this->mSubmitTooltip
= $name;
514 * Set the id for the submit button.
515 * @param $t String. FIXME: Integrity is *not* validated
517 function setSubmitID( $t ) {
518 $this->mSubmitID
= $t;
521 public function setId( $id ) {
525 * Prompt the whole form to be wrapped in a <fieldset>, with
526 * this text as its <legend> element.
527 * @param $legend String HTML to go inside the <legend> element.
530 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
533 * Set the prefix for various default messages
534 * TODO: currently only used for the <fieldset> legend on forms
535 * with multiple sections; should be used elsewhre?
538 function setMessagePrefix( $p ) {
539 $this->mMessagePrefix
= $p;
543 * Set the title for form submission
544 * @param $t Title of page the form is on/should be posted to
546 function setTitle( $t ) {
554 function getTitle() {
555 return $this->mTitle
;
562 function displaySection( $fields, $sectionName = '' ) {
564 $subsectionHtml = '';
565 $hasLeftColumn = false;
567 foreach( $fields as $key => $value ) {
568 if ( is_object( $value ) ) {
569 $v = empty( $value->mParams
['nodata'] )
570 ?
$this->mFieldData
[$key]
571 : $value->getDefault();
572 $tableHtml .= $value->getTableRow( $v );
574 if( $value->getLabel() != ' ' )
575 $hasLeftColumn = true;
576 } elseif ( is_array( $value ) ) {
577 $section = $this->displaySection( $value, $key );
578 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
579 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
584 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
585 $classes[] = 'mw-htmlform-nolabel';
587 'class' => implode( ' ', $classes ),
590 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
592 $tableHtml = Html
::rawElement( 'table', $attribs,
593 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
595 return $subsectionHtml . "\n" . $tableHtml;
599 * Construct the form fields from the Descriptor array
601 function loadData() {
604 $fieldData = array();
606 foreach( $this->mFlatFields
as $fieldname => $field ) {
607 if ( !empty( $field->mParams
['nodata'] ) ){
609 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
610 $fieldData[$fieldname] = $field->getDefault();
612 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
617 foreach( $fieldData as $name => &$value ) {
618 $field = $this->mFlatFields
[$name];
619 $value = $field->filter( $value, $this->mFlatFields
);
622 $this->mFieldData
= $fieldData;
626 * Stop a reset button being shown for this form
627 * @param $suppressReset Bool set to false to re-enable the
630 function suppressReset( $suppressReset = true ) {
631 $this->mShowReset
= !$suppressReset;
635 * Overload this if you want to apply special filtration routines
636 * to the form as a whole, after it's submitted but before it's
639 * @return unknown_type
641 function filterDataForSubmit( $data ) {
647 * The parent class to generate form fields. Any field type should
648 * be a subclass of this.
650 abstract class HTMLFormField
{
652 protected $mValidationCallback;
653 protected $mFilterCallback;
656 protected $mLabel; # String label. Set on construction
658 protected $mClass = '';
663 * This function must be implemented to return the HTML to generate
664 * the input object itself. It should not implement the surrounding
665 * table cells/rows, or labels/help messages.
666 * @param $value String the value to set the input to; eg a default
667 * text for a text input.
668 * @return String valid HTML.
670 abstract function getInputHTML( $value );
673 * Override this function to add specific validation checks on the
674 * field input. Don't forget to call parent::validate() to ensure
675 * that the user-defined callback mValidationCallback is still run
676 * @param $value String the value the field was submitted with
677 * @param $alldata Array the data collected from the form
678 * @return Mixed Bool true on success, or String error to display.
680 function validate( $value, $alldata ) {
681 if ( isset( $this->mValidationCallback
) ) {
682 return call_user_func( $this->mValidationCallback
, $value, $alldata );
688 function filter( $value, $alldata ) {
689 if( isset( $this->mFilterCallback
) ) {
690 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
697 * Should this field have a label, or is there no input element with the
698 * appropriate id for the label to point to?
700 * @return bool True to output a label, false to suppress
702 protected function needsLabel() {
707 * Get the value that this input has been set to from a posted form,
708 * or the input's default value if it has not been set.
709 * @param $request WebRequest
710 * @return String the value
712 function loadDataFromRequest( $request ) {
713 if( $request->getCheck( $this->mName
) ) {
714 return $request->getText( $this->mName
);
716 return $this->getDefault();
721 * Initialise the object
722 * @param $params Associative Array. See HTMLForm doc for syntax.
724 function __construct( $params ) {
725 $this->mParams
= $params;
727 # Generate the label from a message, if possible
728 if( isset( $params['label-message'] ) ) {
729 $msgInfo = $params['label-message'];
731 if ( is_array( $msgInfo ) ) {
732 $msg = array_shift( $msgInfo );
738 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
739 } elseif ( isset( $params['label'] ) ) {
740 $this->mLabel
= $params['label'];
743 if ( isset( $params['name'] ) ) {
744 $name = $params['name'];
745 $validName = Sanitizer
::escapeId( $name );
746 if( $name != $validName ) {
747 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
749 $this->mName
= 'wp'.$name;
750 $this->mID
= 'mw-input-'.$name;
753 if ( isset( $params['default'] ) ) {
754 $this->mDefault
= $params['default'];
757 if ( isset( $params['id'] ) ) {
759 $validId = Sanitizer
::escapeId( $id );
760 if( $id != $validId ) {
761 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
766 if ( isset( $params['cssclass'] ) ) {
767 $this->mClass
= $params['cssclass'];
770 if ( isset( $params['validation-callback'] ) ) {
771 $this->mValidationCallback
= $params['validation-callback'];
774 if ( isset( $params['filter-callback'] ) ) {
775 $this->mFilterCallback
= $params['filter-callback'];
780 * Get the complete table row for the input, including help text,
781 * labels, and whatever.
782 * @param $value String the value to set the input to.
783 * @return String complete HTML table row.
785 function getTableRow( $value ) {
786 # Check for invalid data.
789 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
790 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
793 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
796 $html = $this->getLabelHtml();
797 $html .= Html
::rawElement(
799 array( 'class' => 'mw-input' ),
800 $this->getInputHTML( $value ) ."\n$errors"
803 $fieldType = get_class( $this );
805 $html = Html
::rawElement(
807 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
812 if ( isset( $this->mParams
['help-message'] ) ) {
813 $msg = $this->mParams
['help-message'];
814 $helptext = wfMsgExt( $msg, 'parseinline' );
815 if ( wfEmptyMsg( $msg, $helptext ) ) {
819 } elseif ( isset( $this->mParams
['help'] ) ) {
820 $helptext = $this->mParams
['help'];
823 if ( !is_null( $helptext ) ) {
824 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
826 $row = Html
::rawElement( 'tr', array(), $row );
833 function getLabel() {
834 return $this->mLabel
;
836 function getLabelHtml() {
837 # Don't output a for= attribute for labels with no associated input.
838 # Kind of hacky here, possibly we don't want these to be <label>s at all.
840 if ( $this->needsLabel() ) {
841 $for['for'] = $this->mID
;
843 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
844 Html
::rawElement( 'label', $for, $this->getLabel() )
848 function getDefault() {
849 if ( isset( $this->mDefault
) ) {
850 return $this->mDefault
;
857 * Returns the attributes required for the tooltip and accesskey.
859 * @return array Attributes
861 public function getTooltipAndAccessKey() {
862 if ( empty( $this->mParams
['tooltip'] ) )
866 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
870 * flatten an array of options to a single array, for instance,
871 * a set of <options> inside <optgroups>.
872 * @param $options Associative Array with values either Strings
874 * @return Array flattened input
876 public static function flattenOptions( $options ) {
879 foreach( $options as $key => $value ) {
880 if ( is_array( $value ) ) {
881 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
883 $flatOpts[] = $value;
892 class HTMLTextField
extends HTMLFormField
{
895 return isset( $this->mParams
['size'] )
896 ?
$this->mParams
['size']
900 function getInputHTML( $value ) {
903 'name' => $this->mName
,
904 'size' => $this->getSize(),
906 ) +
$this->getTooltipAndAccessKey();
908 if ( isset( $this->mParams
['maxlength'] ) ) {
909 $attribs['maxlength'] = $this->mParams
['maxlength'];
912 if ( !empty( $this->mParams
['disabled'] ) ) {
913 $attribs['disabled'] = 'disabled';
916 # TODO: Enforce pattern, step, required, readonly on the server side as
918 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
919 'placeholder' ) as $param ) {
920 if ( isset( $this->mParams
[$param] ) ) {
921 $attribs[$param] = $this->mParams
[$param];
924 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
926 if ( isset( $this->mParams
[$param] ) ) {
927 $attribs[$param] = '';
931 # Implement tiny differences between some field variants
932 # here, rather than creating a new class for each one which
933 # is essentially just a clone of this one.
934 if ( isset( $this->mParams
['type'] ) ) {
935 switch ( $this->mParams
['type'] ) {
937 $attribs['type'] = 'email';
940 $attribs['type'] = 'number';
943 $attribs['type'] = 'number';
944 $attribs['step'] = 'any';
949 $attribs['type'] = $this->mParams
['type'];
954 return Html
::element( 'input', $attribs );
957 public function validate( $value, $alldata ){
958 $p = parent
::validate( $value, $alldata );
959 if( $p !== true ) return $p;
961 if( isset( $this->mParams
['required'] ) && $value === '' ){
962 return wfMsgExt( 'htmlform-required', 'parseinline' );
967 class HTMLTextAreaField
extends HTMLFormField
{
970 return isset( $this->mParams
['cols'] )
971 ?
$this->mParams
['cols']
975 return isset( $this->mParams
['rows'] )
976 ?
$this->mParams
['rows']
980 function getInputHTML( $value ) {
983 'name' => $this->mName
,
984 'cols' => $this->getCols(),
985 'rows' => $this->getRows(),
986 ) +
$this->getTooltipAndAccessKey();
989 if ( !empty( $this->mParams
['disabled'] ) ) {
990 $attribs['disabled'] = 'disabled';
992 if ( !empty( $this->mParams
['readonly'] ) ) {
993 $attribs['readonly'] = 'readonly';
996 foreach ( array( 'required', 'autofocus' ) as $param ) {
997 if ( isset( $this->mParams
[$param] ) ) {
998 $attribs[$param] = '';
1002 return Html
::element( 'textarea', $attribs, $value );
1005 public function validate( $value, $alldata ){
1006 $p = parent
::validate( $value, $alldata );
1007 if( $p !== true ) return $p;
1009 if( isset( $this->mParams
['required'] ) && $value === '' ){
1010 return wfMsgExt( 'htmlform-required', 'parseinline' );
1017 * A field that will contain a numeric value
1019 class HTMLFloatField
extends HTMLTextField
{
1021 function getSize() {
1022 return isset( $this->mParams
['size'] )
1023 ?
$this->mParams
['size']
1027 function validate( $value, $alldata ) {
1028 $p = parent
::validate( $value, $alldata );
1030 if ( $p !== true ) return $p;
1032 if ( floatval( $value ) != $value ) {
1033 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1038 # The "int" part of these message names is rather confusing.
1039 # They make equal sense for all numbers.
1040 if ( isset( $this->mParams
['min'] ) ) {
1041 $min = $this->mParams
['min'];
1042 if ( $min > $value )
1043 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1046 if ( isset( $this->mParams
['max'] ) ) {
1047 $max = $this->mParams
['max'];
1049 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1057 * A field that must contain a number
1059 class HTMLIntField
extends HTMLFloatField
{
1060 function validate( $value, $alldata ) {
1061 $p = parent
::validate( $value, $alldata );
1063 if ( $p !== true ) return $p;
1066 && ( !is_numeric( $value ) ||
round( $value ) != $value ) )
1068 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1078 class HTMLCheckField
extends HTMLFormField
{
1079 function getInputHTML( $value ) {
1080 if ( !empty( $this->mParams
['invert'] ) )
1083 $attr = $this->getTooltipAndAccessKey();
1084 $attr['id'] = $this->mID
;
1085 if( !empty( $this->mParams
['disabled'] ) ) {
1086 $attr['disabled'] = 'disabled';
1089 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1090 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1094 * For a checkbox, the label goes on the right hand side, and is
1095 * added in getInputHTML(), rather than HTMLFormField::getRow()
1097 function getLabel() {
1101 function loadDataFromRequest( $request ) {
1103 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1107 // GetCheck won't work like we want for checks.
1108 if( $request->getCheck( 'wpEditToken' ) ) {
1109 // XOR has the following truth table, which is what we want
1110 // INVERT VALUE | OUTPUT
1111 // true true | false
1112 // false true | true
1113 // false false | false
1114 // true false | true
1115 return $request->getBool( $this->mName
) xor $invert;
1117 return $this->getDefault();
1123 * A select dropdown field. Basically a wrapper for Xmlselect class
1125 class HTMLSelectField
extends HTMLFormField
{
1127 function validate( $value, $alldata ) {
1128 $p = parent
::validate( $value, $alldata );
1129 if( $p !== true ) return $p;
1131 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1132 if ( in_array( $value, $validOptions ) )
1135 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1138 function getInputHTML( $value ) {
1139 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1141 # If one of the options' 'name' is int(0), it is automatically selected.
1142 # because PHP sucks and things int(0) == 'some string'.
1143 # Working around this by forcing all of them to strings.
1144 $options = array_map( 'strval', $this->mParams
['options'] );
1146 if( !empty( $this->mParams
['disabled'] ) ) {
1147 $select->setAttribute( 'disabled', 'disabled' );
1150 $select->addOptions( $options );
1152 return $select->getHTML();
1157 * Select dropdown field, with an additional "other" textbox.
1159 class HTMLSelectOrOtherField
extends HTMLTextField
{
1160 static $jsAdded = false;
1162 function __construct( $params ) {
1163 if( !in_array( 'other', $params['options'], true ) ) {
1164 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1167 parent
::__construct( $params );
1170 static function forceToStringRecursive( $array ) {
1171 if ( is_array($array) ) {
1172 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1174 return strval($array);
1178 function getInputHTML( $value ) {
1179 $valInSelect = false;
1181 if( $value !== false )
1182 $valInSelect = in_array( $value,
1183 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1185 $selected = $valInSelect ?
$value : 'other';
1187 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1189 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1190 $select->addOptions( $opts );
1192 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1194 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1195 if( !empty( $this->mParams
['disabled'] ) ) {
1196 $select->setAttribute( 'disabled', 'disabled' );
1197 $tbAttribs['disabled'] = 'disabled';
1200 $select = $select->getHTML();
1202 if ( isset( $this->mParams
['maxlength'] ) ) {
1203 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1206 $textbox = Html
::input( $this->mName
. '-other',
1207 $valInSelect ?
'' : $value,
1211 return "$select<br />\n$textbox";
1214 function loadDataFromRequest( $request ) {
1215 if( $request->getCheck( $this->mName
) ) {
1216 $val = $request->getText( $this->mName
);
1218 if( $val == 'other' ) {
1219 $val = $request->getText( $this->mName
. '-other' );
1224 return $this->getDefault();
1230 * Multi-select field
1232 class HTMLMultiSelectField
extends HTMLFormField
{
1234 function validate( $value, $alldata ) {
1235 $p = parent
::validate( $value, $alldata );
1236 if( $p !== true ) return $p;
1238 if( !is_array( $value ) ) return false;
1240 # If all options are valid, array_intersect of the valid options
1241 # and the provided options will return the provided options.
1242 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1244 $validValues = array_intersect( $value, $validOptions );
1245 if ( count( $validValues ) == count( $value ) )
1248 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1251 function getInputHTML( $value ) {
1252 $html = $this->formatOptions( $this->mParams
['options'], $value );
1257 function formatOptions( $options, $value ) {
1261 if ( !empty( $this->mParams
['disabled'] ) ) {
1262 $attribs['disabled'] = 'disabled';
1265 foreach( $options as $label => $info ) {
1266 if( is_array( $info ) ) {
1267 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1268 $html .= $this->formatOptions( $info, $value );
1270 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1272 $checkbox = Xml
::check( $this->mName
. '[]', $info === $value,
1273 $attribs +
$thisAttribs );
1274 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1276 $html .= $checkbox . '<br />';
1283 function loadDataFromRequest( $request ) {
1284 # won't work with getCheck
1285 if( $request->getCheck( 'wpEditToken' ) ) {
1286 $arr = $request->getArray( $this->mName
);
1293 return $this->getDefault();
1297 function getDefault() {
1298 if ( isset( $this->mDefault
) ) {
1299 return $this->mDefault
;
1305 protected function needsLabel() {
1311 * Radio checkbox fields.
1313 class HTMLRadioField
extends HTMLFormField
{
1314 function validate( $value, $alldata ) {
1315 $p = parent
::validate( $value, $alldata );
1316 if( $p !== true ) return $p;
1318 if( !is_string( $value ) && !is_int( $value ) )
1321 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1323 if ( in_array( $value, $validOptions ) )
1326 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1330 * This returns a block of all the radio options, in one cell.
1331 * @see includes/HTMLFormField#getInputHTML()
1333 function getInputHTML( $value ) {
1334 $html = $this->formatOptions( $this->mParams
['options'], $value );
1339 function formatOptions( $options, $value ) {
1343 if ( !empty( $this->mParams
['disabled'] ) ) {
1344 $attribs['disabled'] = 'disabled';
1347 # TODO: should this produce an unordered list perhaps?
1348 foreach( $options as $label => $info ) {
1349 if( is_array( $info ) ) {
1350 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1351 $html .= $this->formatOptions( $info, $value );
1353 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1354 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1355 $attribs +
array( 'id' => $id ) );
1357 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1359 $html .= "<br />\n";
1366 protected function needsLabel() {
1372 * An information field (text blob), not a proper input.
1374 class HTMLInfoField
extends HTMLFormField
{
1375 function __construct( $info ) {
1376 $info['nodata'] = true;
1378 parent
::__construct( $info );
1381 function getInputHTML( $value ) {
1382 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1385 function getTableRow( $value ) {
1386 if ( !empty( $this->mParams
['rawrow'] ) ) {
1390 return parent
::getTableRow( $value );
1393 protected function needsLabel() {
1398 class HTMLHiddenField
extends HTMLFormField
{
1400 public function getTableRow( $value ){
1403 $params['id'] = $this->mID
;
1405 $this->mParent
->addHiddenField(
1413 public function getInputHTML( $value ){ return ''; }
1417 * Add a submit button inline in the form (as opposed to
1418 * HTMLForm::addButton(), which will add it at the end).
1420 class HTMLSubmitField
extends HTMLFormField
{
1422 function __construct( $info ) {
1423 $info['nodata'] = true;
1424 parent
::__construct( $info );
1427 function getInputHTML( $value ) {
1428 return Xml
::submitButton(
1431 'class' => 'mw-htmlform-submit',
1432 'name' => $this->mName
,
1438 protected function needsLabel() {
1443 class HTMLEditTools
extends HTMLFormField
{
1444 public function getInputHTML( $value ) {
1447 public function getTableRow( $value ) {
1448 return "<tr><td></td><td class=\"mw-input\">"
1449 . '<div class="mw-editTools">'
1450 . wfMsgExt( empty( $this->mParams
['message'] )
1451 ?
'edittools' : $this->mParams
['message'],
1452 array( 'parse', 'content' ) )
1453 . "</div></td></tr>\n";