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 $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;
159 global $wgOut, $wgStylePath;
161 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
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.
197 # Load data from the request.
201 global $wgUser, $wgRequest;
202 $editToken = $wgRequest->getVal( 'wpEditToken' );
205 if ( $wgUser->matchEditToken( $editToken ) )
206 $result = $this->trySubmit();
208 if( $result === true )
212 $this->displayForm( $result );
217 * Validate all the fields, and call the submision callback
218 * function if everything is kosher.
219 * @return Mixed Bool true == Successful submission, Bool false
220 * == No submission attempted, anything else == Error to
223 function trySubmit() {
224 # Check for validation
225 foreach( $this->mFlatFields
as $fieldname => $field ) {
226 if ( !empty( $field->mParams
['nodata'] ) ){
229 if ( $field->validate(
230 $this->mFieldData
[$fieldname],
234 return isset( $this->mValidationErrorMessage
)
235 ?
$this->mValidationErrorMessage
236 : array( 'htmlform-invalid-input' );
240 $callback = $this->mSubmitCallback
;
242 $data = $this->filterDataForSubmit( $this->mFieldData
);
244 $res = call_user_func( $callback, $data );
250 * Set a callback to a function to do something with the form
251 * once it's been successfully validated.
252 * @param $cb String function name. The function will be passed
253 * the output from HTMLForm::filterDataForSubmit, and must
254 * return Bool true on success, Bool false if no submission
255 * was attempted, or String HTML output to display on error.
257 function setSubmitCallback( $cb ) {
258 $this->mSubmitCallback
= $cb;
262 * Set a message to display on a validation error.
263 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
264 * (so each entry can be either a String or Array)
266 function setValidationErrorMessage( $msg ) {
267 $this->mValidationErrorMessage
= $msg;
271 * Set the introductory message, overwriting any existing message.
272 * @param $msg String complete text of message to display
274 function setIntro( $msg ) { $this->mPre
= $msg; }
277 * Add introductory text.
278 * @param $msg String complete text of message to display
280 function addPreText( $msg ) { $this->mPre
.= $msg; }
283 * Add header text, inside the form.
284 * @param $msg String complete text of message to display
286 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
289 * Add text to the end of the display.
290 * @param $msg String complete text of message to display
292 function addPostText( $msg ) { $this->mPost
.= $msg; }
295 * Add a hidden field to the output
296 * @param $name String field name
297 * @param $value String field value
298 * @param $attribs Array
300 public function addHiddenField( $name, $value, $attribs=array() ){
301 $this->mHiddenFields
[ $name ] = array( $value, $attribs );
304 public function addButton( $name, $value, $id=null, $attribs=null ){
305 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
309 * Display the form (sending to wgOut), with an appropriate error
310 * message or stack of messages, and any validation errors, etc.
311 * @param $submitResult Mixed output from HTMLForm::trySubmit()
313 function displayForm( $submitResult ) {
316 if ( $submitResult !== false ) {
317 $this->displayErrors( $submitResult );
323 . $this->getHiddenFields()
324 . $this->getButtons()
327 $html = $this->wrapForm( $html );
337 * Wrap the form innards in an actual <form> element
338 * @param $html String HTML contents to wrap.
339 * @return String wrapped HTML.
341 function wrapForm( $html ) {
343 # Include a <fieldset> wrapper for style, if requested.
344 if ( $this->mWrapperLegend
!== false ){
345 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
347 # Use multipart/form-data
348 $encType = $this->mUseMultipart
349 ?
'multipart/form-data'
350 : 'application/x-www-form-urlencoded';
353 'action' => $this->getTitle()->getFullURL(),
355 'class' => 'visualClear',
356 'enctype' => $encType,
358 if ( !empty( $this->mId
) )
359 $attribs['id'] = $this->mId
;
361 return Html
::rawElement( 'form', $attribs, $html );
365 * Get the hidden fields that should go inside the form.
366 * @return String HTML.
368 function getHiddenFields() {
372 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
373 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
375 foreach( $this->mHiddenFields
as $name => $value ){
376 list( $value, $attribs ) = $value;
377 $html .= Html
::hidden( $name, $value, $attribs ) . "\n";
384 * Get the submit and (potentially) reset buttons.
385 * @return String HTML.
387 function getButtons() {
392 if ( isset( $this->mSubmitID
) )
393 $attribs['id'] = $this->mSubmitID
;
394 if ( isset( $this->mSubmitName
) )
395 $attribs['name'] = $this->mSubmitName
;
396 if ( isset( $this->mSubmitTooltip
) ) {
398 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
401 $attribs['class'] = 'mw-htmlform-submit';
403 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
405 if( $this->mShowReset
) {
406 $html .= Html
::element(
410 'value' => wfMsg( 'htmlform-reset' )
415 foreach( $this->mButtons
as $button ){
418 'name' => $button['name'],
419 'value' => $button['value']
421 if ( $button['attribs'] )
422 $attrs +
= $button['attribs'];
423 if( isset( $button['id'] ) )
424 $attrs['id'] = $button['id'];
425 $html .= Html
::element( 'input', $attrs );
432 * Get the whole body of the form.
435 return $this->displaySection( $this->mFieldTree
);
439 * Format and display an error message stack.
440 * @param $errors Mixed String or Array of message keys
442 function displayErrors( $errors ) {
443 if ( is_array( $errors ) ) {
444 $errorstr = $this->formatErrors( $errors );
449 $errorstr = Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
452 $wgOut->addHTML( $errorstr );
456 * Format a stack of error messages into a single HTML string
457 * @param $errors Array of message keys/values
458 * @return String HTML, a <ul> list of errors
460 static function formatErrors( $errors ) {
462 foreach ( $errors as $error ) {
463 if( is_array( $error ) ) {
464 $msg = array_shift( $error );
469 $errorstr .= Html
::rawElement(
472 wfMsgExt( $msg, array( 'parseinline' ), $error )
476 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
482 * Set the text for the submit button
483 * @param $t String plaintext.
485 function setSubmitText( $t ) {
486 $this->mSubmitText
= $t;
490 * Get the text for the submit button, either customised or a default.
491 * @return unknown_type
493 function getSubmitText() {
494 return $this->mSubmitText
496 : wfMsg( 'htmlform-submit' );
499 public function setSubmitName( $name ) {
500 $this->mSubmitName
= $name;
503 public function setSubmitTooltip( $name ) {
504 $this->mSubmitTooltip
= $name;
509 * Set the id for the submit button.
510 * @param $t String. FIXME: Integrity is *not* validated
512 function setSubmitID( $t ) {
513 $this->mSubmitID
= $t;
516 public function setId( $id ) {
520 * Prompt the whole form to be wrapped in a <fieldset>, with
521 * this text as its <legend> element.
522 * @param $legend String HTML to go inside the <legend> element.
525 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
528 * Set the prefix for various default messages
529 * TODO: currently only used for the <fieldset> legend on forms
530 * with multiple sections; should be used elsewhre?
533 function setMessagePrefix( $p ) {
534 $this->mMessagePrefix
= $p;
538 * Set the title for form submission
539 * @param $t Title of page the form is on/should be posted to
541 function setTitle( $t ) {
549 function getTitle() {
550 return $this->mTitle
;
557 function displaySection( $fields, $sectionName = '' ) {
559 $subsectionHtml = '';
560 $hasLeftColumn = false;
562 foreach( $fields as $key => $value ) {
563 if ( is_object( $value ) ) {
564 $v = empty( $value->mParams
['nodata'] )
565 ?
$this->mFieldData
[$key]
566 : $value->getDefault();
567 $tableHtml .= $value->getTableRow( $v );
569 if( $value->getLabel() != ' ' )
570 $hasLeftColumn = true;
571 } elseif ( is_array( $value ) ) {
572 $section = $this->displaySection( $value, $key );
573 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
574 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
579 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
580 $classes[] = 'mw-htmlform-nolabel';
582 'class' => implode( ' ', $classes ),
585 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
587 $tableHtml = Html
::rawElement( 'table', $attribs,
588 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
590 return $subsectionHtml . "\n" . $tableHtml;
594 * Construct the form fields from the Descriptor array
596 function loadData() {
599 $fieldData = array();
601 foreach( $this->mFlatFields
as $fieldname => $field ) {
602 if ( !empty( $field->mParams
['nodata'] ) ){
604 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
605 $fieldData[$fieldname] = $field->getDefault();
607 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
612 foreach( $fieldData as $name => &$value ) {
613 $field = $this->mFlatFields
[$name];
614 $value = $field->filter( $value, $this->mFlatFields
);
617 $this->mFieldData
= $fieldData;
621 * Stop a reset button being shown for this form
622 * @param $suppressReset Bool set to false to re-enable the
625 function suppressReset( $suppressReset = true ) {
626 $this->mShowReset
= !$suppressReset;
630 * Overload this if you want to apply special filtration routines
631 * to the form as a whole, after it's submitted but before it's
634 * @return unknown_type
636 function filterDataForSubmit( $data ) {
642 * The parent class to generate form fields. Any field type should
643 * be a subclass of this.
645 abstract class HTMLFormField
{
647 protected $mValidationCallback;
648 protected $mFilterCallback;
651 protected $mLabel; # String label. Set on construction
653 protected $mClass = '';
658 * This function must be implemented to return the HTML to generate
659 * the input object itself. It should not implement the surrounding
660 * table cells/rows, or labels/help messages.
661 * @param $value String the value to set the input to; eg a default
662 * text for a text input.
663 * @return String valid HTML.
665 abstract function getInputHTML( $value );
668 * Override this function to add specific validation checks on the
669 * field input. Don't forget to call parent::validate() to ensure
670 * that the user-defined callback mValidationCallback is still run
671 * @param $value String the value the field was submitted with
672 * @param $alldata Array the data collected from the form
673 * @return Mixed Bool true on success, or String error to display.
675 function validate( $value, $alldata ) {
676 if ( isset( $this->mValidationCallback
) ) {
677 return call_user_func( $this->mValidationCallback
, $value, $alldata );
683 function filter( $value, $alldata ) {
684 if( isset( $this->mFilterCallback
) ) {
685 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
692 * Should this field have a label, or is there no input element with the
693 * appropriate id for the label to point to?
695 * @return bool True to output a label, false to suppress
697 protected function needsLabel() {
702 * Get the value that this input has been set to from a posted form,
703 * or the input's default value if it has not been set.
704 * @param $request WebRequest
705 * @return String the value
707 function loadDataFromRequest( $request ) {
708 if( $request->getCheck( $this->mName
) ) {
709 return $request->getText( $this->mName
);
711 return $this->getDefault();
716 * Initialise the object
717 * @param $params Associative Array. See HTMLForm doc for syntax.
719 function __construct( $params ) {
720 $this->mParams
= $params;
722 # Generate the label from a message, if possible
723 if( isset( $params['label-message'] ) ) {
724 $msgInfo = $params['label-message'];
726 if ( is_array( $msgInfo ) ) {
727 $msg = array_shift( $msgInfo );
733 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
734 } elseif ( isset( $params['label'] ) ) {
735 $this->mLabel
= $params['label'];
738 if ( isset( $params['name'] ) ) {
739 $name = $params['name'];
740 $validName = Sanitizer
::escapeId( $name );
741 if( $name != $validName ) {
742 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
744 $this->mName
= 'wp'.$name;
745 $this->mID
= 'mw-input-'.$name;
748 if ( isset( $params['default'] ) ) {
749 $this->mDefault
= $params['default'];
752 if ( isset( $params['id'] ) ) {
754 $validId = Sanitizer
::escapeId( $id );
755 if( $id != $validId ) {
756 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
761 if ( isset( $params['cssclass'] ) ) {
762 $this->mClass
= $params['cssclass'];
765 if ( isset( $params['validation-callback'] ) ) {
766 $this->mValidationCallback
= $params['validation-callback'];
769 if ( isset( $params['filter-callback'] ) ) {
770 $this->mFilterCallback
= $params['filter-callback'];
775 * Get the complete table row for the input, including help text,
776 * labels, and whatever.
777 * @param $value String the value to set the input to.
778 * @return String complete HTML table row.
780 function getTableRow( $value ) {
781 # Check for invalid data.
784 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
785 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
788 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
791 $html = $this->getLabelHtml();
792 $html .= Html
::rawElement(
794 array( 'class' => 'mw-input' ),
795 $this->getInputHTML( $value ) ."\n$errors"
798 $fieldType = get_class( $this );
800 $html = Html
::rawElement(
802 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
807 if ( isset( $this->mParams
['help-message'] ) ) {
808 $msg = $this->mParams
['help-message'];
809 $helptext = wfMsgExt( $msg, 'parseinline' );
810 if ( wfEmptyMsg( $msg, $helptext ) ) {
814 } elseif ( isset( $this->mParams
['help'] ) ) {
815 $helptext = $this->mParams
['help'];
818 if ( !is_null( $helptext ) ) {
819 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
821 $row = Html
::rawElement( 'tr', array(), $row );
828 function getLabel() {
829 return $this->mLabel
;
831 function getLabelHtml() {
832 # Don't output a for= attribute for labels with no associated input.
833 # Kind of hacky here, possibly we don't want these to be <label>s at all.
835 if ( $this->needsLabel() ) {
836 $for['for'] = $this->mID
;
838 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
839 Html
::rawElement( 'label', $for, $this->getLabel() )
843 function getDefault() {
844 if ( isset( $this->mDefault
) ) {
845 return $this->mDefault
;
852 * Returns the attributes required for the tooltip and accesskey.
854 * @return array Attributes
856 public function getTooltipAndAccessKey() {
857 if ( empty( $this->mParams
['tooltip'] ) )
861 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
865 * flatten an array of options to a single array, for instance,
866 * a set of <options> inside <optgroups>.
867 * @param $options Associative Array with values either Strings
869 * @return Array flattened input
871 public static function flattenOptions( $options ) {
874 foreach( $options as $key => $value ) {
875 if ( is_array( $value ) ) {
876 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
878 $flatOpts[] = $value;
887 class HTMLTextField
extends HTMLFormField
{
890 return isset( $this->mParams
['size'] )
891 ?
$this->mParams
['size']
895 function getInputHTML( $value ) {
898 'name' => $this->mName
,
899 'size' => $this->getSize(),
901 ) +
$this->getTooltipAndAccessKey();
903 if ( isset( $this->mParams
['maxlength'] ) ) {
904 $attribs['maxlength'] = $this->mParams
['maxlength'];
907 if ( !empty( $this->mParams
['disabled'] ) ) {
908 $attribs['disabled'] = 'disabled';
911 # TODO: Enforce pattern, step, required, readonly on the server side as
913 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
914 'placeholder' ) as $param ) {
915 if ( isset( $this->mParams
[$param] ) ) {
916 $attribs[$param] = $this->mParams
[$param];
919 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
921 if ( isset( $this->mParams
[$param] ) ) {
922 $attribs[$param] = '';
926 # Implement tiny differences between some field variants
927 # here, rather than creating a new class for each one which
928 # is essentially just a clone of this one.
929 if ( isset( $this->mParams
['type'] ) ) {
930 switch ( $this->mParams
['type'] ) {
932 $attribs['type'] = 'email';
935 $attribs['type'] = 'number';
938 $attribs['type'] = 'number';
939 $attribs['step'] = 'any';
944 $attribs['type'] = $this->mParams
['type'];
949 return Html
::element( 'input', $attribs );
952 public function validate( $value, $alldata ){
953 $p = parent
::validate( $value, $alldata );
954 if( $p !== true ) return $p;
956 if( isset( $this->mParams
['required'] ) && $value === '' ){
957 return wfMsgExt( 'htmlform-required', 'parseinline' );
962 class HTMLTextAreaField
extends HTMLFormField
{
965 return isset( $this->mParams
['cols'] )
966 ?
$this->mParams
['cols']
970 return isset( $this->mParams
['rows'] )
971 ?
$this->mParams
['rows']
975 function getInputHTML( $value ) {
978 'name' => $this->mName
,
979 'cols' => $this->getCols(),
980 'rows' => $this->getRows(),
981 ) +
$this->getTooltipAndAccessKey();
984 if ( !empty( $this->mParams
['disabled'] ) ) {
985 $attribs['disabled'] = 'disabled';
987 if ( !empty( $this->mParams
['readonly'] ) ) {
988 $attribs['readonly'] = 'readonly';
991 foreach ( array( 'required', 'autofocus' ) as $param ) {
992 if ( isset( $this->mParams
[$param] ) ) {
993 $attribs[$param] = '';
997 return Html
::element( 'textarea', $attribs, $value );
1002 * A field that will contain a numeric value
1004 class HTMLFloatField
extends HTMLTextField
{
1006 function getSize() {
1007 return isset( $this->mParams
['size'] )
1008 ?
$this->mParams
['size']
1012 function validate( $value, $alldata ) {
1013 $p = parent
::validate( $value, $alldata );
1015 if ( $p !== true ) return $p;
1017 if ( floatval( $value ) != $value ) {
1018 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1023 # The "int" part of these message names is rather confusing.
1024 # They make equal sense for all numbers.
1025 if ( isset( $this->mParams
['min'] ) ) {
1026 $min = $this->mParams
['min'];
1027 if ( $min > $value )
1028 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1031 if ( isset( $this->mParams
['max'] ) ) {
1032 $max = $this->mParams
['max'];
1034 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1042 * A field that must contain a number
1044 class HTMLIntField
extends HTMLFloatField
{
1045 function validate( $value, $alldata ) {
1046 $p = parent
::validate( $value, $alldata );
1048 if ( $p !== true ) return $p;
1051 && ( !is_numeric( $value ) ||
round( $value ) != $value ) )
1053 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1063 class HTMLCheckField
extends HTMLFormField
{
1064 function getInputHTML( $value ) {
1065 if ( !empty( $this->mParams
['invert'] ) )
1068 $attr = $this->getTooltipAndAccessKey();
1069 $attr['id'] = $this->mID
;
1070 if( !empty( $this->mParams
['disabled'] ) ) {
1071 $attr['disabled'] = 'disabled';
1074 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1075 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1079 * For a checkbox, the label goes on the right hand side, and is
1080 * added in getInputHTML(), rather than HTMLFormField::getRow()
1082 function getLabel() {
1086 function loadDataFromRequest( $request ) {
1088 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1092 // GetCheck won't work like we want for checks.
1093 if( $request->getCheck( 'wpEditToken' ) ) {
1094 // XOR has the following truth table, which is what we want
1095 // INVERT VALUE | OUTPUT
1096 // true true | false
1097 // false true | true
1098 // false false | false
1099 // true false | true
1100 return $request->getBool( $this->mName
) xor $invert;
1102 return $this->getDefault();
1108 * A select dropdown field. Basically a wrapper for Xmlselect class
1110 class HTMLSelectField
extends HTMLFormField
{
1112 function validate( $value, $alldata ) {
1113 $p = parent
::validate( $value, $alldata );
1114 if( $p !== true ) return $p;
1116 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1117 if ( in_array( $value, $validOptions ) )
1120 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1123 function getInputHTML( $value ) {
1124 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1126 # If one of the options' 'name' is int(0), it is automatically selected.
1127 # because PHP sucks and things int(0) == 'some string'.
1128 # Working around this by forcing all of them to strings.
1129 $options = array_map( 'strval', $this->mParams
['options'] );
1131 if( !empty( $this->mParams
['disabled'] ) ) {
1132 $select->setAttribute( 'disabled', 'disabled' );
1135 $select->addOptions( $options );
1137 return $select->getHTML();
1142 * Select dropdown field, with an additional "other" textbox.
1144 class HTMLSelectOrOtherField
extends HTMLTextField
{
1145 static $jsAdded = false;
1147 function __construct( $params ) {
1148 if( !in_array( 'other', $params['options'], true ) ) {
1149 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1152 parent
::__construct( $params );
1155 static function forceToStringRecursive( $array ) {
1156 if ( is_array($array) ) {
1157 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1159 return strval($array);
1163 function getInputHTML( $value ) {
1164 $valInSelect = false;
1166 if( $value !== false )
1167 $valInSelect = in_array( $value,
1168 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1170 $selected = $valInSelect ?
$value : 'other';
1172 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1174 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1175 $select->addOptions( $opts );
1177 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1179 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1180 if( !empty( $this->mParams
['disabled'] ) ) {
1181 $select->setAttribute( 'disabled', 'disabled' );
1182 $tbAttribs['disabled'] = 'disabled';
1185 $select = $select->getHTML();
1187 if ( isset( $this->mParams
['maxlength'] ) ) {
1188 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1191 $textbox = Html
::input( $this->mName
. '-other',
1192 $valInSelect ?
'' : $value,
1196 return "$select<br />\n$textbox";
1199 function loadDataFromRequest( $request ) {
1200 if( $request->getCheck( $this->mName
) ) {
1201 $val = $request->getText( $this->mName
);
1203 if( $val == 'other' ) {
1204 $val = $request->getText( $this->mName
. '-other' );
1209 return $this->getDefault();
1215 * Multi-select field
1217 class HTMLMultiSelectField
extends HTMLFormField
{
1219 function validate( $value, $alldata ) {
1220 $p = parent
::validate( $value, $alldata );
1221 if( $p !== true ) return $p;
1223 if( !is_array( $value ) ) return false;
1225 # If all options are valid, array_intersect of the valid options
1226 # and the provided options will return the provided options.
1227 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1229 $validValues = array_intersect( $value, $validOptions );
1230 if ( count( $validValues ) == count( $value ) )
1233 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1236 function getInputHTML( $value ) {
1237 $html = $this->formatOptions( $this->mParams
['options'], $value );
1242 function formatOptions( $options, $value ) {
1246 if ( !empty( $this->mParams
['disabled'] ) ) {
1247 $attribs['disabled'] = 'disabled';
1250 foreach( $options as $label => $info ) {
1251 if( is_array( $info ) ) {
1252 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1253 $html .= $this->formatOptions( $info, $value );
1255 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1257 $checkbox = Xml
::check( $this->mName
. '[]', $info === $value,
1258 $attribs +
$thisAttribs );
1259 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1261 $html .= $checkbox . '<br />';
1268 function loadDataFromRequest( $request ) {
1269 # won't work with getCheck
1270 if( $request->getCheck( 'wpEditToken' ) ) {
1271 $arr = $request->getArray( $this->mName
);
1278 return $this->getDefault();
1282 function getDefault() {
1283 if ( isset( $this->mDefault
) ) {
1284 return $this->mDefault
;
1290 protected function needsLabel() {
1296 * Radio checkbox fields.
1298 class HTMLRadioField
extends HTMLFormField
{
1299 function validate( $value, $alldata ) {
1300 $p = parent
::validate( $value, $alldata );
1301 if( $p !== true ) return $p;
1303 if( !is_string( $value ) && !is_int( $value ) )
1306 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1308 if ( in_array( $value, $validOptions ) )
1311 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1315 * This returns a block of all the radio options, in one cell.
1316 * @see includes/HTMLFormField#getInputHTML()
1318 function getInputHTML( $value ) {
1319 $html = $this->formatOptions( $this->mParams
['options'], $value );
1324 function formatOptions( $options, $value ) {
1328 if ( !empty( $this->mParams
['disabled'] ) ) {
1329 $attribs['disabled'] = 'disabled';
1332 # TODO: should this produce an unordered list perhaps?
1333 foreach( $options as $label => $info ) {
1334 if( is_array( $info ) ) {
1335 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1336 $html .= $this->formatOptions( $info, $value );
1338 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1339 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1340 $attribs +
array( 'id' => $id ) );
1342 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1344 $html .= "<br />\n";
1351 protected function needsLabel() {
1357 * An information field (text blob), not a proper input.
1359 class HTMLInfoField
extends HTMLFormField
{
1360 function __construct( $info ) {
1361 $info['nodata'] = true;
1363 parent
::__construct( $info );
1366 function getInputHTML( $value ) {
1367 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1370 function getTableRow( $value ) {
1371 if ( !empty( $this->mParams
['rawrow'] ) ) {
1375 return parent
::getTableRow( $value );
1378 protected function needsLabel() {
1383 class HTMLHiddenField
extends HTMLFormField
{
1385 public function getTableRow( $value ){
1388 $params['id'] = $this->mID
;
1390 $this->mParent
->addHiddenField(
1398 public function getInputHTML( $value ){ return ''; }
1402 * Add a submit button inline in the form (as opposed to
1403 * HTMLForm::addButton(), which will add it at the end).
1405 class HTMLSubmitField
extends HTMLFormField
{
1407 function __construct( $info ) {
1408 $info['nodata'] = true;
1409 parent
::__construct( $info );
1412 function getInputHTML( $value ) {
1413 return Xml
::submitButton(
1416 'class' => 'mw-htmlform-submit',
1417 'name' => $this->mName
,
1423 protected function needsLabel() {
1428 class HTMLEditTools
extends HTMLFormField
{
1429 public function getInputHTML( $value ) {
1432 public function getTableRow( $value ) {
1433 return "<tr><td></td><td class=\"mw-input\">"
1434 . '<div class="mw-editTools">'
1435 . wfMsgExt( empty( $this->mParams
['message'] )
1436 ?
'edittools' : $this->mParams
['message'],
1437 array( 'parse', 'content' ) )
1438 . "</div></td></tr>\n";