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 * '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 'select' => 'HTMLSelectField',
55 'radio' => 'HTMLRadioField',
56 'multiselect' => 'HTMLMultiSelectField',
57 'check' => 'HTMLCheckField',
58 'toggle' => 'HTMLCheckField',
59 'int' => 'HTMLIntField',
60 'float' => 'HTMLFloatField',
61 'info' => 'HTMLInfoField',
62 'selectorother' => 'HTMLSelectOrOtherField',
63 'submit' => 'HTMLSubmitField',
64 'hidden' => 'HTMLHiddenField',
66 # HTMLTextField will output the correct type="" attribute automagically.
67 # There are about four zillion other HTML 5 input types, like url, but
68 # we don't use those at the moment, so no point in adding all of them.
69 'email' => 'HTMLTextField',
70 'password' => 'HTMLTextField',
73 protected $mMessagePrefix;
74 protected $mFlatFields;
75 protected $mFieldTree;
76 protected $mShowReset;
78 protected $mSubmitCallback;
79 protected $mValidationErrorMessage;
82 protected $mSubmitText;
85 protected $mHiddenFields = array();
86 protected $mButtons = array();
89 * Build a new HTMLForm from an array of field attributes
90 * @param $descriptor Array of Field constructs, as described above
91 * @param $messagePrefix String a prefix to go in front of default messages
93 public function __construct( $descriptor, $messagePrefix='' ) {
94 $this->mMessagePrefix
= $messagePrefix;
96 // Expand out into a tree.
97 $loadedDescriptor = array();
98 $this->mFlatFields
= array();
100 foreach( $descriptor as $fieldname => $info ) {
102 if ( isset( $info['section'] ) )
103 $section = $info['section'];
105 $info['name'] = $fieldname;
107 $field = self
::loadInputFromParameters( $info );
108 $field->mParent
= $this;
110 $setSection =& $loadedDescriptor;
112 $sectionParts = explode( '/', $section );
114 while( count( $sectionParts ) ) {
115 $newName = array_shift( $sectionParts );
117 if ( !isset( $setSection[$newName] ) ) {
118 $setSection[$newName] = array();
121 $setSection =& $setSection[$newName];
125 $setSection[$fieldname] = $field;
126 $this->mFlatFields
[$fieldname] = $field;
129 $this->mFieldTree
= $loadedDescriptor;
131 $this->mShowReset
= true;
135 * Add the HTMLForm-specific JavaScript, if it hasn't been
138 static function addJS() {
139 if( self
::$jsAdded ) return;
143 $wgOut->addScriptClass( 'htmlform' );
147 * Initialise a new Object for the field
148 * @param $descriptor input Descriptor, as described above
149 * @return HTMLFormField subclass
151 static function loadInputFromParameters( $descriptor ) {
152 if ( isset( $descriptor['class'] ) ) {
153 $class = $descriptor['class'];
154 } elseif ( isset( $descriptor['type'] ) ) {
155 $class = self
::$typeMappings[$descriptor['type']];
156 $descriptor['class'] = $class;
160 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
163 $obj = new $class( $descriptor );
169 * The here's-one-I-made-earlier option: do the submission if
170 * posted, or display the form with or without funky valiation
172 * @return Bool whether submission was successful.
179 # Load data from the request.
183 global $wgUser, $wgRequest;
184 $editToken = $wgRequest->getVal( 'wpEditToken' );
187 if ( $wgUser->matchEditToken( $editToken ) )
188 $result = $this->trySubmit();
190 if( $result === true )
194 $this->displayForm( $result );
199 * Validate all the fields, and call the submision callback
200 * function if everything is kosher.
201 * @return Mixed Bool true == Successful submission, Bool false
202 * == No submission attempted, anything else == Error to
205 function trySubmit() {
206 # Check for validation
207 foreach( $this->mFlatFields
as $fieldname => $field ) {
208 if ( !empty( $field->mParams
['nodata'] ) )
210 if ( $field->validate(
211 $this->mFieldData
[$fieldname],
215 return isset( $this->mValidationErrorMessage
)
216 ?
$this->mValidationErrorMessage
217 : array( 'htmlform-invalid-input' );
221 $callback = $this->mSubmitCallback
;
223 $data = $this->filterDataForSubmit( $this->mFieldData
);
225 $res = call_user_func( $callback, $data );
231 * Set a callback to a function to do something with the form
232 * once it's been successfully validated.
233 * @param $cb String function name. The function will be passed
234 * the output from HTMLForm::filterDataForSubmit, and must
235 * return Bool true on success, Bool false if no submission
236 * was attempted, or String HTML output to display on error.
238 function setSubmitCallback( $cb ) {
239 $this->mSubmitCallback
= $cb;
243 * Set a message to display on a validation error.
244 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
245 * (so each entry can be either a String or Array)
247 function setValidationErrorMessage( $msg ) {
248 $this->mValidationErrorMessage
= $msg;
252 * Set the introductory message
253 * @param $msg String complete text of message to display
255 function setIntro( $msg ) {
256 $this->mIntro
= $msg;
260 * Add a hidden field to the output
261 * @param $name String field name
262 * @param $value String field value
264 public function addHiddenField( $name, $value ){
265 $this->mHiddenFields
[ $name ] = $value;
268 public function addButton( $name, $value, $id=null ){
269 $this->mButtons
[] = compact( 'name', 'value', 'id' );
273 * Display the form (sending to wgOut), with an appropriate error
274 * message or stack of messages, and any validation errors, etc.
275 * @param $submitResult Mixed output from HTMLForm::trySubmit()
277 function displayForm( $submitResult ) {
280 if ( $submitResult !== false ) {
281 $this->displayErrors( $submitResult );
284 if ( isset( $this->mIntro
) ) {
285 $wgOut->addHTML( $this->mIntro
);
288 $html = $this->getBody();
291 $html .= $this->getHiddenFields();
294 $html .= $this->getButtons();
296 $html = $this->wrapForm( $html );
298 $wgOut->addHTML( $html );
302 * Wrap the form innards in an actual <form> element
303 * @param $html String HTML contents to wrap.
304 * @return String wrapped HTML.
306 function wrapForm( $html ) {
307 return Html
::rawElement(
310 'action' => $this->getTitle()->getFullURL(),
318 * Get the hidden fields that should go inside the form.
319 * @return String HTML.
321 function getHiddenFields() {
325 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
326 $html .= Html
::hidden( 'title', $this->getTitle() ) . "\n";
328 foreach( $this->mHiddenFields
as $name => $value ){
329 $html .= Html
::hidden( $name, $value ) . "\n";
336 * Get the submit and (potentially) reset buttons.
337 * @return String HTML.
339 function getButtons() {
344 if ( isset( $this->mSubmitID
) )
345 $attribs['id'] = $this->mSubmitID
;
347 $attribs['class'] = 'mw-htmlform-submit';
349 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
351 if( $this->mShowReset
) {
352 $html .= Html
::element(
356 'value' => wfMsg( 'htmlform-reset' )
361 foreach( $this->mButtons
as $button ){
364 'name' => $button['name'],
365 'value' => $button['value']
367 if( isset( $button['id'] ) )
368 $attrs['id'] = $button['id'];
369 $html .= Html
::element( 'input', $attrs );
376 * Get the whole body of the form.
379 return $this->displaySection( $this->mFieldTree
);
383 * Format and display an error message stack.
384 * @param $errors Mixed String or Array of message keys
386 function displayErrors( $errors ) {
387 if ( is_array( $errors ) ) {
388 $errorstr = $this->formatErrors( $errors );
393 $errorstr = Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
396 $wgOut->addHTML( $errorstr );
400 * Format a stack of error messages into a single HTML string
401 * @param $errors Array of message keys/values
402 * @return String HTML, a <ul> list of errors
404 static function formatErrors( $errors ) {
406 foreach ( $errors as $error ) {
407 if( is_array( $error ) ) {
408 $msg = array_shift( $error );
413 $errorstr .= Html
::rawElement(
416 wfMsgExt( $msg, array( 'parseinline' ), $error )
420 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
426 * Set the text for the submit button
427 * @param $t String plaintext.
429 function setSubmitText( $t ) {
430 $this->mSubmitText
= $t;
434 * Get the text for the submit button, either customised or a default.
435 * @return unknown_type
437 function getSubmitText() {
438 return $this->mSubmitText
440 : wfMsg( 'htmlform-submit' );
444 * Set the id for the submit button.
445 * @param $t String. FIXME: Integrity is *not* validated
447 function setSubmitID( $t ) {
448 $this->mSubmitID
= $t;
452 * Set the prefix for various default messages
453 * TODO: currently only used for the <fieldset> legend on forms
454 * with multiple sections; should be used elsewhre?
457 function setMessagePrefix( $p ) {
458 $this->mMessagePrefix
= $p;
462 * Set the title for form submission
463 * @param $t Title of page the form is on/should be posted to
465 function setTitle( $t ) {
473 function getTitle() {
474 return $this->mTitle
;
481 function displaySection( $fields ) {
483 $subsectionHtml = '';
484 $hasLeftColumn = false;
486 foreach( $fields as $key => $value ) {
487 if ( is_object( $value ) ) {
488 $v = empty( $value->mParams
['nodata'] )
489 ?
$this->mFieldData
[$key]
490 : $value->getDefault();
491 $tableHtml .= $value->getTableRow( $v );
493 if( $value->getLabel() != ' ' )
494 $hasLeftColumn = true;
495 } elseif ( is_array( $value ) ) {
496 $section = $this->displaySection( $value );
497 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
498 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
503 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
504 $classes[] = 'mw-htmlform-nolabel';
505 $classes = implode( ' ', $classes );
507 $tableHtml = Html
::rawElement( 'table', array( 'class' => $classes ),
508 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
510 return $subsectionHtml . "\n" . $tableHtml;
514 * Construct the form fields from the Descriptor array
516 function loadData() {
519 $fieldData = array();
521 foreach( $this->mFlatFields
as $fieldname => $field ) {
522 if ( !empty( $field->mParams
['nodata'] ) ) continue;
523 if ( !empty( $field->mParams
['disabled'] ) ) {
524 $fieldData[$fieldname] = $field->getDefault();
526 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
531 foreach( $fieldData as $name => &$value ) {
532 $field = $this->mFlatFields
[$name];
533 $value = $field->filter( $value, $this->mFlatFields
);
536 $this->mFieldData
= $fieldData;
540 * Stop a reset button being shown for this form
541 * @param $suppressReset Bool set to false to re-enable the
544 function suppressReset( $suppressReset = true ) {
545 $this->mShowReset
= !$suppressReset;
549 * Overload this if you want to apply special filtration routines
550 * to the form as a whole, after it's submitted but before it's
553 * @return unknown_type
555 function filterDataForSubmit( $data ) {
561 * The parent class to generate form fields. Any field type should
562 * be a subclass of this.
564 abstract class HTMLFormField
{
566 protected $mValidationCallback;
567 protected $mFilterCallback;
570 protected $mLabel; # String label. Set on construction
576 * This function must be implemented to return the HTML to generate
577 * the input object itself. It should not implement the surrounding
578 * table cells/rows, or labels/help messages.
579 * @param $value String the value to set the input to; eg a default
580 * text for a text input.
581 * @return String valid HTML.
583 abstract function getInputHTML( $value );
586 * Override this function to add specific validation checks on the
587 * field input. Don't forget to call parent::validate() to ensure
588 * that the user-defined callback mValidationCallback is still run
589 * @param $value String the value the field was submitted with
590 * @param $alldata $all the data collected from the form
591 * @return Mixed Bool true on success, or String error to display.
593 function validate( $value, $alldata ) {
594 if ( isset( $this->mValidationCallback
) ) {
595 return call_user_func( $this->mValidationCallback
, $value, $alldata );
601 function filter( $value, $alldata ) {
602 if( isset( $this->mFilterCallback
) ) {
603 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
610 * Should this field have a label, or is there no input element with the
611 * appropriate id for the label to point to?
613 * @return bool True to output a label, false to suppress
615 protected function needsLabel() {
620 * Get the value that this input has been set to from a posted form,
621 * or the input's default value if it has not been set.
622 * @param $request WebRequest
623 * @return String the value
625 function loadDataFromRequest( $request ) {
626 if( $request->getCheck( $this->mName
) ) {
627 return $request->getText( $this->mName
);
629 return $this->getDefault();
634 * Initialise the object
635 * @param $params Associative Array. See HTMLForm doc for syntax.
637 function __construct( $params ) {
638 $this->mParams
= $params;
640 # Generate the label from a message, if possible
641 if( isset( $params['label-message'] ) ) {
642 $msgInfo = $params['label-message'];
644 if ( is_array( $msgInfo ) ) {
645 $msg = array_shift( $msgInfo );
651 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
652 } elseif ( isset( $params['label'] ) ) {
653 $this->mLabel
= $params['label'];
656 if ( isset( $params['name'] ) ) {
657 $name = $params['name'];
658 $validName = Sanitizer
::escapeId( $name );
659 if( $name != $validName ) {
660 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
662 $this->mName
= 'wp'.$name;
663 $this->mID
= 'mw-input-'.$name;
666 if ( isset( $params['default'] ) ) {
667 $this->mDefault
= $params['default'];
670 if ( isset( $params['id'] ) ) {
672 $validId = Sanitizer
::escapeId( $id );
673 if( $id != $validId ) {
674 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
679 if ( isset( $params['validation-callback'] ) ) {
680 $this->mValidationCallback
= $params['validation-callback'];
683 if ( isset( $params['filter-callback'] ) ) {
684 $this->mFilterCallback
= $params['filter-callback'];
689 * Get the complete table row for the input, including help text,
690 * labels, and whatever.
691 * @param $value String the value to set the input to.
692 * @return String complete HTML table row.
694 function getTableRow( $value ) {
695 # Check for invalid data.
698 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
699 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
702 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
707 # Don't output a for= attribute for labels with no associated input.
708 # Kind of hacky here, possibly we don't want these to be <label>s at all.
710 if ( $this->needsLabel() ) {
711 $for['for'] = $this->mID
;
713 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
714 Html
::rawElement( 'label', $for, $this->getLabel() )
716 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-input' ),
717 $this->getInputHTML( $value ) ."\n$errors" );
719 $fieldType = get_class( $this );
721 $html = Html
::rawElement( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
725 if ( isset( $this->mParams
['help-message'] ) ) {
726 $msg = $this->mParams
['help-message'];
727 $helptext = wfMsgExt( $msg, 'parseinline' );
728 if ( wfEmptyMsg( $msg, $helptext ) ) {
732 } elseif ( isset( $this->mParams
['help'] ) ) {
733 $helptext = $this->mParams
['help'];
736 if ( !is_null( $helptext ) ) {
737 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
739 $row = Html
::rawElement( 'tr', array(), $row );
746 function getLabel() {
747 return $this->mLabel
;
750 function getDefault() {
751 if ( isset( $this->mDefault
) ) {
752 return $this->mDefault
;
759 * flatten an array of options to a single array, for instance,
760 * a set of <options> inside <optgroups>.
761 * @param $options Associative Array with values either Strings
763 * @return Array flattened input
765 public static function flattenOptions( $options ) {
768 foreach( $options as $key => $value ) {
769 if ( is_array( $value ) ) {
770 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
772 $flatOpts[] = $value;
780 class HTMLTextField
extends HTMLFormField
{
783 return isset( $this->mParams
['size'] )
784 ?
$this->mParams
['size']
788 function getInputHTML( $value ) {
792 'name' => $this->mName
,
793 'size' => $this->getSize(),
797 if ( isset( $this->mParams
['maxlength'] ) ) {
798 $attribs['maxlength'] = $this->mParams
['maxlength'];
801 if ( !empty( $this->mParams
['disabled'] ) ) {
802 $attribs['disabled'] = 'disabled';
806 # TODO: Enforce pattern, step, required, readonly on the server
808 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
809 'placeholder' ) as $param ) {
810 if ( isset( $this->mParams
[$param] ) ) {
811 $attribs[$param] = $this->mParams
[$param];
814 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
816 if ( isset( $this->mParams
[$param] ) ) {
817 $attribs[$param] = '';
821 # Implement tiny differences between some field variants
822 # here, rather than creating a new class for each one which
823 # is essentially just a clone of this one.
824 if ( isset( $this->mParams
['type'] ) ) {
825 switch ( $this->mParams
['type'] ) {
827 $attribs['type'] = 'email';
830 $attribs['type'] = 'number';
833 $attribs['type'] = 'number';
834 $attribs['step'] = 'any';
837 $attribs['type'] = 'password';
843 return Html
::element( 'input', $attribs );
848 * A field that will contain a numeric value
850 class HTMLFloatField
extends HTMLTextField
{
853 return isset( $this->mParams
['size'] )
854 ?
$this->mParams
['size']
858 function validate( $value, $alldata ) {
859 $p = parent
::validate( $value, $alldata );
861 if ( $p !== true ) return $p;
863 if ( floatval( $value ) != $value ) {
864 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
869 # The "int" part of these message names is rather confusing.
870 # They make equal sense for all numbers.
871 if ( isset( $this->mParams
['min'] ) ) {
872 $min = $this->mParams
['min'];
874 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
877 if ( isset( $this->mParams
['max'] ) ) {
878 $max = $this->mParams
['max'];
880 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
888 * A field that must contain a number
890 class HTMLIntField
extends HTMLFloatField
{
891 function validate( $value, $alldata ) {
892 $p = parent
::validate( $value, $alldata );
894 if ( $p !== true ) return $p;
896 if ( intval( $value ) != $value ) {
897 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
907 class HTMLCheckField
extends HTMLFormField
{
908 function getInputHTML( $value ) {
909 if ( !empty( $this->mParams
['invert'] ) )
912 $attr = array( 'id' => $this->mID
);
913 if( !empty( $this->mParams
['disabled'] ) ) {
914 $attr['disabled'] = 'disabled';
917 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
918 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
922 * For a checkbox, the label goes on the right hand side, and is
923 * added in getInputHTML(), rather than HTMLFormField::getRow()
925 function getLabel() {
929 function loadDataFromRequest( $request ) {
931 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
935 // GetCheck won't work like we want for checks.
936 if( $request->getCheck( 'wpEditToken' ) ) {
937 // XOR has the following truth table, which is what we want
938 // INVERT VALUE | OUTPUT
941 // false false | false
943 return $request->getBool( $this->mName
) xor $invert;
945 return $this->getDefault();
951 * A select dropdown field. Basically a wrapper for Xmlselect class
953 class HTMLSelectField
extends HTMLFormField
{
955 function validate( $value, $alldata ) {
956 $p = parent
::validate( $value, $alldata );
957 if( $p !== true ) return $p;
959 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
960 if ( in_array( $value, $validOptions ) )
963 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
966 function getInputHTML( $value ) {
967 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
969 # If one of the options' 'name' is int(0), it is automatically selected.
970 # because PHP sucks and things int(0) == 'some string'.
971 # Working around this by forcing all of them to strings.
972 $options = array_map( 'strval', $this->mParams
['options'] );
974 if( !empty( $this->mParams
['disabled'] ) ) {
975 $select->setAttribute( 'disabled', 'disabled' );
978 $select->addOptions( $options );
980 return $select->getHTML();
985 * Select dropdown field, with an additional "other" textbox.
987 class HTMLSelectOrOtherField
extends HTMLTextField
{
988 static $jsAdded = false;
990 function __construct( $params ) {
991 if( !in_array( 'other', $params['options'], true ) ) {
992 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
995 parent
::__construct( $params );
998 static function forceToStringRecursive( $array ) {
999 if ( is_array($array) ) {
1000 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1002 return strval($array);
1006 function getInputHTML( $value ) {
1007 $valInSelect = false;
1009 if( $value !== false )
1010 $valInSelect = in_array( $value,
1011 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1013 $selected = $valInSelect ?
$value : 'other';
1015 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1017 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1018 $select->addOptions( $opts );
1020 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1022 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1023 if( !empty( $this->mParams
['disabled'] ) ) {
1024 $select->setAttribute( 'disabled', 'disabled' );
1025 $tbAttribs['disabled'] = 'disabled';
1028 $select = $select->getHTML();
1030 if ( isset( $this->mParams
['maxlength'] ) ) {
1031 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1034 $textbox = Html
::input( $this->mName
. '-other',
1035 $valInSelect ?
'' : $value,
1039 return "$select<br/>\n$textbox";
1042 function loadDataFromRequest( $request ) {
1043 if( $request->getCheck( $this->mName
) ) {
1044 $val = $request->getText( $this->mName
);
1046 if( $val == 'other' ) {
1047 $val = $request->getText( $this->mName
. '-other' );
1052 return $this->getDefault();
1058 * Multi-select field
1060 class HTMLMultiSelectField
extends HTMLFormField
{
1062 function validate( $value, $alldata ) {
1063 $p = parent
::validate( $value, $alldata );
1064 if( $p !== true ) return $p;
1066 if( !is_array( $value ) ) return false;
1068 # If all options are valid, array_intersect of the valid options
1069 # and the provided options will return the provided options.
1070 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1072 $validValues = array_intersect( $value, $validOptions );
1073 if ( count( $validValues ) == count( $value ) )
1076 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1079 function getInputHTML( $value ) {
1080 $html = $this->formatOptions( $this->mParams
['options'], $value );
1085 function formatOptions( $options, $value ) {
1089 if ( !empty( $this->mParams
['disabled'] ) ) {
1090 $attribs['disabled'] = 'disabled';
1093 foreach( $options as $label => $info ) {
1094 if( is_array( $info ) ) {
1095 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1096 $html .= $this->formatOptions( $info, $value );
1098 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1100 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
1101 $attribs +
$thisAttribs );
1102 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1104 $html .= $checkbox . '<br />';
1111 function loadDataFromRequest( $request ) {
1112 # won't work with getCheck
1113 if( $request->getCheck( 'wpEditToken' ) ) {
1114 $arr = $request->getArray( $this->mName
);
1121 return $this->getDefault();
1125 function getDefault() {
1126 if ( isset( $this->mDefault
) ) {
1127 return $this->mDefault
;
1133 protected function needsLabel() {
1139 * Radio checkbox fields.
1141 class HTMLRadioField
extends HTMLFormField
{
1142 function validate( $value, $alldata ) {
1143 $p = parent
::validate( $value, $alldata );
1144 if( $p !== true ) return $p;
1146 if( !is_string( $value ) && !is_int( $value ) )
1149 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1151 if ( in_array( $value, $validOptions ) )
1154 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1158 * This returns a block of all the radio options, in one cell.
1159 * @see includes/HTMLFormField#getInputHTML()
1161 function getInputHTML( $value ) {
1162 $html = $this->formatOptions( $this->mParams
['options'], $value );
1167 function formatOptions( $options, $value ) {
1171 if ( !empty( $this->mParams
['disabled'] ) ) {
1172 $attribs['disabled'] = 'disabled';
1175 # TODO: should this produce an unordered list perhaps?
1176 foreach( $options as $label => $info ) {
1177 if( is_array( $info ) ) {
1178 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1179 $html .= $this->formatOptions( $info, $value );
1181 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1182 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1183 $attribs +
array( 'id' => $id ) );
1185 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1194 protected function needsLabel() {
1200 * An information field (text blob), not a proper input.
1202 class HTMLInfoField
extends HTMLFormField
{
1203 function __construct( $info ) {
1204 $info['nodata'] = true;
1206 parent
::__construct( $info );
1209 function getInputHTML( $value ) {
1210 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1213 function getTableRow( $value ) {
1214 if ( !empty( $this->mParams
['rawrow'] ) ) {
1218 return parent
::getTableRow( $value );
1221 protected function needsLabel() {
1226 class HTMLHiddenField
extends HTMLFormField
{
1228 public function getTableRow( $value ){
1229 $this->mParent
->addHiddenField(
1230 $this->mParams
['name'],
1231 $this->mParams
['default']
1236 public function getInputHTML( $value ){ return ''; }
1239 class HTMLSubmitField
extends HTMLFormField
{
1241 public function getTableRow( $value ){
1242 $this->mParent
->addButton(
1243 $this->mParams
['name'],
1244 $this->mParams
['default'],
1245 isset($this->mParams
['id']) ?
$this->mParams
['id'] : null
1249 public function getInputHTML( $value ){ return ''; }