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 = false;
79 protected $mSubmitCallback;
80 protected $mValidationErrorMessage;
83 protected $mHeader = '';
84 protected $mPost = '';
87 protected $mSubmitText;
90 protected $mHiddenFields = array();
91 protected $mButtons = array();
93 protected $mWrapperLegend = false;
96 * Build a new HTMLForm from an array of field attributes
97 * @param $descriptor Array of Field constructs, as described above
98 * @param $messagePrefix String a prefix to go in front of default messages
100 public function __construct( $descriptor, $messagePrefix='' ) {
101 $this->mMessagePrefix
= $messagePrefix;
103 // Expand out into a tree.
104 $loadedDescriptor = array();
105 $this->mFlatFields
= array();
107 foreach( $descriptor as $fieldname => $info ) {
109 if ( isset( $info['section'] ) )
110 $section = $info['section'];
112 $info['name'] = $fieldname;
114 $field = self
::loadInputFromParameters( $info );
115 $field->mParent
= $this;
117 $setSection =& $loadedDescriptor;
119 $sectionParts = explode( '/', $section );
121 while( count( $sectionParts ) ) {
122 $newName = array_shift( $sectionParts );
124 if ( !isset( $setSection[$newName] ) ) {
125 $setSection[$newName] = array();
128 $setSection =& $setSection[$newName];
132 $setSection[$fieldname] = $field;
133 $this->mFlatFields
[$fieldname] = $field;
136 $this->mFieldTree
= $loadedDescriptor;
140 * Add the HTMLForm-specific JavaScript, if it hasn't been
143 static function addJS() {
144 if( self
::$jsAdded ) return;
148 $wgOut->addScriptClass( 'htmlform' );
152 * Initialise a new Object for the field
153 * @param $descriptor input Descriptor, as described above
154 * @return HTMLFormField subclass
156 static function loadInputFromParameters( $descriptor ) {
157 if ( isset( $descriptor['class'] ) ) {
158 $class = $descriptor['class'];
159 } elseif ( isset( $descriptor['type'] ) ) {
160 $class = self
::$typeMappings[$descriptor['type']];
161 $descriptor['class'] = $class;
165 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
168 $obj = new $class( $descriptor );
174 * The here's-one-I-made-earlier option: do the submission if
175 * posted, or display the form with or without funky valiation
177 * @return Bool whether submission was successful.
184 # Load data from the request.
188 global $wgUser, $wgRequest;
189 $editToken = $wgRequest->getVal( 'wpEditToken' );
192 if ( $wgUser->matchEditToken( $editToken ) )
193 $result = $this->trySubmit();
195 if( $result === true )
199 $this->displayForm( $result );
204 * Validate all the fields, and call the submision callback
205 * function if everything is kosher.
206 * @return Mixed Bool true == Successful submission, Bool false
207 * == No submission attempted, anything else == Error to
210 function trySubmit() {
211 # Check for validation
212 foreach( $this->mFlatFields
as $fieldname => $field ) {
213 if ( !empty( $field->mParams
['nodata'] ) )
215 if ( $field->validate(
216 $this->mFieldData
[$fieldname],
220 return isset( $this->mValidationErrorMessage
)
221 ?
$this->mValidationErrorMessage
222 : array( 'htmlform-invalid-input' );
226 $callback = $this->mSubmitCallback
;
228 $data = $this->filterDataForSubmit( $this->mFieldData
);
230 $res = call_user_func( $callback, $data );
236 * Set a callback to a function to do something with the form
237 * once it's been successfully validated.
238 * @param $cb String function name. The function will be passed
239 * the output from HTMLForm::filterDataForSubmit, and must
240 * return Bool true on success, Bool false if no submission
241 * was attempted, or String HTML output to display on error.
243 function setSubmitCallback( $cb ) {
244 $this->mSubmitCallback
= $cb;
248 * Set a message to display on a validation error.
249 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
250 * (so each entry can be either a String or Array)
252 function setValidationErrorMessage( $msg ) {
253 $this->mValidationErrorMessage
= $msg;
257 * Set the introductory message, overwriting any existing message.
258 * @param $msg String complete text of message to display
260 function setIntro( $msg ) { $this->mPre
= $msg; }
263 * Add introductory text.
264 * @param $msg String complete text of message to display
266 function addPreText( $msg ) { $this->mPre
.= $msg; }
269 * Add header text, inside the form.
270 * @param $msg String complete text of message to display
272 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
275 * Add text to the end of the display.
276 * @param $msg String complete text of message to display
278 function addPostText( $msg ) { $this->mPost
.= $msg; }
281 * Add a hidden field to the output
282 * @param $name String field name
283 * @param $value String field value
285 public function addHiddenField( $name, $value ){
286 $this->mHiddenFields
[ $name ] = $value;
289 public function addButton( $name, $value, $id=null ){
290 $this->mButtons
[] = compact( 'name', 'value', 'id' );
294 * Display the form (sending to wgOut), with an appropriate error
295 * message or stack of messages, and any validation errors, etc.
296 * @param $submitResult Mixed output from HTMLForm::trySubmit()
298 function displayForm( $submitResult ) {
301 if ( $submitResult !== false ) {
302 $this->displayErrors( $submitResult );
308 . $this->getHiddenFields()
309 . $this->getButtons()
312 $html = $this->wrapForm( $html );
322 * Wrap the form innards in an actual <form> element
323 * @param $html String HTML contents to wrap.
324 * @return String wrapped HTML.
326 function wrapForm( $html ) {
328 # Include a <fieldset> wrapper for style, if requested.
329 if( $this->mWrapperLegend
!== false ){
330 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
333 return Html
::rawElement(
336 'action' => $this->getTitle()->getFullURL(),
338 'class' => 'visualClear',
345 * Get the hidden fields that should go inside the form.
346 * @return String HTML.
348 function getHiddenFields() {
352 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
353 $html .= Html
::hidden( 'title', $this->getTitle() ) . "\n";
355 foreach( $this->mHiddenFields
as $name => $value ){
356 $html .= Html
::hidden( $name, $value ) . "\n";
363 * Get the submit and (potentially) reset buttons.
364 * @return String HTML.
366 function getButtons() {
371 if ( isset( $this->mSubmitID
) )
372 $attribs['id'] = $this->mSubmitID
;
374 $attribs['class'] = 'mw-htmlform-submit';
376 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
378 if( $this->mShowReset
) {
379 $html .= Html
::element(
383 'value' => wfMsg( 'htmlform-reset' )
388 foreach( $this->mButtons
as $button ){
391 'name' => $button['name'],
392 'value' => $button['value']
394 if( isset( $button['id'] ) )
395 $attrs['id'] = $button['id'];
396 $html .= Html
::element( 'input', $attrs );
403 * Get the whole body of the form.
406 return $this->displaySection( $this->mFieldTree
);
410 * Format and display an error message stack.
411 * @param $errors Mixed String or Array of message keys
413 function displayErrors( $errors ) {
414 if ( is_array( $errors ) ) {
415 $errorstr = $this->formatErrors( $errors );
420 $errorstr = Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
423 $wgOut->addHTML( $errorstr );
427 * Format a stack of error messages into a single HTML string
428 * @param $errors Array of message keys/values
429 * @return String HTML, a <ul> list of errors
431 static function formatErrors( $errors ) {
433 foreach ( $errors as $error ) {
434 if( is_array( $error ) ) {
435 $msg = array_shift( $error );
440 $errorstr .= Html
::rawElement(
443 wfMsgExt( $msg, array( 'parseinline' ), $error )
447 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
453 * Set the text for the submit button
454 * @param $t String plaintext.
456 function setSubmitText( $t ) {
457 $this->mSubmitText
= $t;
461 * Get the text for the submit button, either customised or a default.
462 * @return unknown_type
464 function getSubmitText() {
465 return $this->mSubmitText
467 : wfMsg( 'htmlform-submit' );
471 * Set the id for the submit button.
472 * @param $t String. FIXME: Integrity is *not* validated
474 function setSubmitID( $t ) {
475 $this->mSubmitID
= $t;
479 * Prompt the whole form to be wrapped in a <fieldset>, with
480 * this text as its <legend> element.
481 * @param $legend String HTML to go inside the <legend> element.
484 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
487 * Set the prefix for various default messages
488 * TODO: currently only used for the <fieldset> legend on forms
489 * with multiple sections; should be used elsewhre?
492 function setMessagePrefix( $p ) {
493 $this->mMessagePrefix
= $p;
497 * Set the title for form submission
498 * @param $t Title of page the form is on/should be posted to
500 function setTitle( $t ) {
508 function getTitle() {
509 return $this->mTitle
;
516 function displaySection( $fields ) {
518 $subsectionHtml = '';
519 $hasLeftColumn = false;
521 foreach( $fields as $key => $value ) {
522 if ( is_object( $value ) ) {
523 $v = empty( $value->mParams
['nodata'] )
524 ?
$this->mFieldData
[$key]
525 : $value->getDefault();
526 $tableHtml .= $value->getTableRow( $v );
528 if( $value->getLabel() != ' ' )
529 $hasLeftColumn = true;
530 } elseif ( is_array( $value ) ) {
531 $section = $this->displaySection( $value );
532 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
533 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
538 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
539 $classes[] = 'mw-htmlform-nolabel';
540 $classes = implode( ' ', $classes );
542 $tableHtml = Html
::rawElement( 'table', array( 'class' => $classes ),
543 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
545 return $subsectionHtml . "\n" . $tableHtml;
549 * Construct the form fields from the Descriptor array
551 function loadData() {
554 $fieldData = array();
556 foreach( $this->mFlatFields
as $fieldname => $field ) {
557 if ( !empty( $field->mParams
['nodata'] ) ) continue;
558 if ( !empty( $field->mParams
['disabled'] ) ) {
559 $fieldData[$fieldname] = $field->getDefault();
561 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
566 foreach( $fieldData as $name => &$value ) {
567 $field = $this->mFlatFields
[$name];
568 $value = $field->filter( $value, $this->mFlatFields
);
571 $this->mFieldData
= $fieldData;
575 * Stop a reset button being shown for this form
576 * @param $suppressReset Bool set to false to re-enable the
579 function suppressReset( $suppressReset = true ) {
580 $this->mShowReset
= !$suppressReset;
584 * Overload this if you want to apply special filtration routines
585 * to the form as a whole, after it's submitted but before it's
588 * @return unknown_type
590 function filterDataForSubmit( $data ) {
596 * The parent class to generate form fields. Any field type should
597 * be a subclass of this.
599 abstract class HTMLFormField
{
601 protected $mValidationCallback;
602 protected $mFilterCallback;
605 protected $mLabel; # String label. Set on construction
611 * This function must be implemented to return the HTML to generate
612 * the input object itself. It should not implement the surrounding
613 * table cells/rows, or labels/help messages.
614 * @param $value String the value to set the input to; eg a default
615 * text for a text input.
616 * @return String valid HTML.
618 abstract function getInputHTML( $value );
621 * Override this function to add specific validation checks on the
622 * field input. Don't forget to call parent::validate() to ensure
623 * that the user-defined callback mValidationCallback is still run
624 * @param $value String the value the field was submitted with
625 * @param $alldata $all the data collected from the form
626 * @return Mixed Bool true on success, or String error to display.
628 function validate( $value, $alldata ) {
629 if ( isset( $this->mValidationCallback
) ) {
630 return call_user_func( $this->mValidationCallback
, $value, $alldata );
636 function filter( $value, $alldata ) {
637 if( isset( $this->mFilterCallback
) ) {
638 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
645 * Should this field have a label, or is there no input element with the
646 * appropriate id for the label to point to?
648 * @return bool True to output a label, false to suppress
650 protected function needsLabel() {
655 * Get the value that this input has been set to from a posted form,
656 * or the input's default value if it has not been set.
657 * @param $request WebRequest
658 * @return String the value
660 function loadDataFromRequest( $request ) {
661 if( $request->getCheck( $this->mName
) ) {
662 return $request->getText( $this->mName
);
664 return $this->getDefault();
669 * Initialise the object
670 * @param $params Associative Array. See HTMLForm doc for syntax.
672 function __construct( $params ) {
673 $this->mParams
= $params;
675 # Generate the label from a message, if possible
676 if( isset( $params['label-message'] ) ) {
677 $msgInfo = $params['label-message'];
679 if ( is_array( $msgInfo ) ) {
680 $msg = array_shift( $msgInfo );
686 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
687 } elseif ( isset( $params['label'] ) ) {
688 $this->mLabel
= $params['label'];
691 if ( isset( $params['name'] ) ) {
692 $name = $params['name'];
693 $validName = Sanitizer
::escapeId( $name );
694 if( $name != $validName ) {
695 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
697 $this->mName
= 'wp'.$name;
698 $this->mID
= 'mw-input-'.$name;
701 if ( isset( $params['default'] ) ) {
702 $this->mDefault
= $params['default'];
705 if ( isset( $params['id'] ) ) {
707 $validId = Sanitizer
::escapeId( $id );
708 if( $id != $validId ) {
709 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
714 if ( isset( $params['validation-callback'] ) ) {
715 $this->mValidationCallback
= $params['validation-callback'];
718 if ( isset( $params['filter-callback'] ) ) {
719 $this->mFilterCallback
= $params['filter-callback'];
724 * Get the complete table row for the input, including help text,
725 * labels, and whatever.
726 * @param $value String the value to set the input to.
727 * @return String complete HTML table row.
729 function getTableRow( $value ) {
730 # Check for invalid data.
733 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
734 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
737 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
742 # Don't output a for= attribute for labels with no associated input.
743 # Kind of hacky here, possibly we don't want these to be <label>s at all.
745 if ( $this->needsLabel() ) {
746 $for['for'] = $this->mID
;
748 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
749 Html
::rawElement( 'label', $for, $this->getLabel() )
751 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-input' ),
752 $this->getInputHTML( $value ) ."\n$errors" );
754 $fieldType = get_class( $this );
756 $html = Html
::rawElement( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
760 if ( isset( $this->mParams
['help-message'] ) ) {
761 $msg = $this->mParams
['help-message'];
762 $helptext = wfMsgExt( $msg, 'parseinline' );
763 if ( wfEmptyMsg( $msg, $helptext ) ) {
767 } elseif ( isset( $this->mParams
['help'] ) ) {
768 $helptext = $this->mParams
['help'];
771 if ( !is_null( $helptext ) ) {
772 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
774 $row = Html
::rawElement( 'tr', array(), $row );
781 function getLabel() {
782 return $this->mLabel
;
785 function getDefault() {
786 if ( isset( $this->mDefault
) ) {
787 return $this->mDefault
;
794 * flatten an array of options to a single array, for instance,
795 * a set of <options> inside <optgroups>.
796 * @param $options Associative Array with values either Strings
798 * @return Array flattened input
800 public static function flattenOptions( $options ) {
803 foreach( $options as $key => $value ) {
804 if ( is_array( $value ) ) {
805 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
807 $flatOpts[] = $value;
815 class HTMLTextField
extends HTMLFormField
{
818 return isset( $this->mParams
['size'] )
819 ?
$this->mParams
['size']
823 function getInputHTML( $value ) {
827 'name' => $this->mName
,
828 'size' => $this->getSize(),
832 if ( isset( $this->mParams
['maxlength'] ) ) {
833 $attribs['maxlength'] = $this->mParams
['maxlength'];
836 if ( !empty( $this->mParams
['disabled'] ) ) {
837 $attribs['disabled'] = 'disabled';
841 # TODO: Enforce pattern, step, required, readonly on the server
843 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
844 'placeholder' ) as $param ) {
845 if ( isset( $this->mParams
[$param] ) ) {
846 $attribs[$param] = $this->mParams
[$param];
849 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
851 if ( isset( $this->mParams
[$param] ) ) {
852 $attribs[$param] = '';
857 # Implement tiny differences between some field variants
858 # here, rather than creating a new class for each one which
859 # is essentially just a clone of this one.
860 if ( isset( $this->mParams
['type'] ) ) {
861 # Options that apply only to HTML5
863 switch ( $this->mParams
['type'] ) {
865 $attribs['type'] = 'email';
868 $attribs['type'] = 'number';
871 $attribs['type'] = 'number';
872 $attribs['step'] = 'any';
876 # Options that apply to HTML4 as well
877 switch( $this->mParams
['type'] ){
879 $attribs['type'] = 'password';
884 return Html
::element( 'input', $attribs );
889 * A field that will contain a numeric value
891 class HTMLFloatField
extends HTMLTextField
{
894 return isset( $this->mParams
['size'] )
895 ?
$this->mParams
['size']
899 function validate( $value, $alldata ) {
900 $p = parent
::validate( $value, $alldata );
902 if ( $p !== true ) return $p;
904 if ( floatval( $value ) != $value ) {
905 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
910 # The "int" part of these message names is rather confusing.
911 # They make equal sense for all numbers.
912 if ( isset( $this->mParams
['min'] ) ) {
913 $min = $this->mParams
['min'];
915 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
918 if ( isset( $this->mParams
['max'] ) ) {
919 $max = $this->mParams
['max'];
921 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
929 * A field that must contain a number
931 class HTMLIntField
extends HTMLFloatField
{
932 function validate( $value, $alldata ) {
933 $p = parent
::validate( $value, $alldata );
935 if ( $p !== true ) return $p;
937 if ( intval( $value ) != $value ) {
938 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
948 class HTMLCheckField
extends HTMLFormField
{
949 function getInputHTML( $value ) {
950 if ( !empty( $this->mParams
['invert'] ) )
953 $attr = array( 'id' => $this->mID
);
954 if( !empty( $this->mParams
['disabled'] ) ) {
955 $attr['disabled'] = 'disabled';
958 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
959 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
963 * For a checkbox, the label goes on the right hand side, and is
964 * added in getInputHTML(), rather than HTMLFormField::getRow()
966 function getLabel() {
970 function loadDataFromRequest( $request ) {
972 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
976 // GetCheck won't work like we want for checks.
977 if( $request->getCheck( 'wpEditToken' ) ) {
978 // XOR has the following truth table, which is what we want
979 // INVERT VALUE | OUTPUT
982 // false false | false
984 return $request->getBool( $this->mName
) xor $invert;
986 return $this->getDefault();
992 * A select dropdown field. Basically a wrapper for Xmlselect class
994 class HTMLSelectField
extends HTMLFormField
{
996 function validate( $value, $alldata ) {
997 $p = parent
::validate( $value, $alldata );
998 if( $p !== true ) return $p;
1000 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1001 if ( in_array( $value, $validOptions ) )
1004 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1007 function getInputHTML( $value ) {
1008 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1010 # If one of the options' 'name' is int(0), it is automatically selected.
1011 # because PHP sucks and things int(0) == 'some string'.
1012 # Working around this by forcing all of them to strings.
1013 $options = array_map( 'strval', $this->mParams
['options'] );
1015 if( !empty( $this->mParams
['disabled'] ) ) {
1016 $select->setAttribute( 'disabled', 'disabled' );
1019 $select->addOptions( $options );
1021 return $select->getHTML();
1026 * Select dropdown field, with an additional "other" textbox.
1028 class HTMLSelectOrOtherField
extends HTMLTextField
{
1029 static $jsAdded = false;
1031 function __construct( $params ) {
1032 if( !in_array( 'other', $params['options'], true ) ) {
1033 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1036 parent
::__construct( $params );
1039 static function forceToStringRecursive( $array ) {
1040 if ( is_array($array) ) {
1041 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1043 return strval($array);
1047 function getInputHTML( $value ) {
1048 $valInSelect = false;
1050 if( $value !== false )
1051 $valInSelect = in_array( $value,
1052 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1054 $selected = $valInSelect ?
$value : 'other';
1056 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1058 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1059 $select->addOptions( $opts );
1061 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1063 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1064 if( !empty( $this->mParams
['disabled'] ) ) {
1065 $select->setAttribute( 'disabled', 'disabled' );
1066 $tbAttribs['disabled'] = 'disabled';
1069 $select = $select->getHTML();
1071 if ( isset( $this->mParams
['maxlength'] ) ) {
1072 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1075 $textbox = Html
::input( $this->mName
. '-other',
1076 $valInSelect ?
'' : $value,
1080 return "$select<br/>\n$textbox";
1083 function loadDataFromRequest( $request ) {
1084 if( $request->getCheck( $this->mName
) ) {
1085 $val = $request->getText( $this->mName
);
1087 if( $val == 'other' ) {
1088 $val = $request->getText( $this->mName
. '-other' );
1093 return $this->getDefault();
1099 * Multi-select field
1101 class HTMLMultiSelectField
extends HTMLFormField
{
1103 function validate( $value, $alldata ) {
1104 $p = parent
::validate( $value, $alldata );
1105 if( $p !== true ) return $p;
1107 if( !is_array( $value ) ) return false;
1109 # If all options are valid, array_intersect of the valid options
1110 # and the provided options will return the provided options.
1111 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1113 $validValues = array_intersect( $value, $validOptions );
1114 if ( count( $validValues ) == count( $value ) )
1117 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1120 function getInputHTML( $value ) {
1121 $html = $this->formatOptions( $this->mParams
['options'], $value );
1126 function formatOptions( $options, $value ) {
1130 if ( !empty( $this->mParams
['disabled'] ) ) {
1131 $attribs['disabled'] = 'disabled';
1134 foreach( $options as $label => $info ) {
1135 if( is_array( $info ) ) {
1136 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1137 $html .= $this->formatOptions( $info, $value );
1139 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1141 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
1142 $attribs +
$thisAttribs );
1143 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1145 $html .= $checkbox . '<br />';
1152 function loadDataFromRequest( $request ) {
1153 # won't work with getCheck
1154 if( $request->getCheck( 'wpEditToken' ) ) {
1155 $arr = $request->getArray( $this->mName
);
1162 return $this->getDefault();
1166 function getDefault() {
1167 if ( isset( $this->mDefault
) ) {
1168 return $this->mDefault
;
1174 protected function needsLabel() {
1180 * Radio checkbox fields.
1182 class HTMLRadioField
extends HTMLFormField
{
1183 function validate( $value, $alldata ) {
1184 $p = parent
::validate( $value, $alldata );
1185 if( $p !== true ) return $p;
1187 if( !is_string( $value ) && !is_int( $value ) )
1190 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1192 if ( in_array( $value, $validOptions ) )
1195 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1199 * This returns a block of all the radio options, in one cell.
1200 * @see includes/HTMLFormField#getInputHTML()
1202 function getInputHTML( $value ) {
1203 $html = $this->formatOptions( $this->mParams
['options'], $value );
1208 function formatOptions( $options, $value ) {
1212 if ( !empty( $this->mParams
['disabled'] ) ) {
1213 $attribs['disabled'] = 'disabled';
1216 # TODO: should this produce an unordered list perhaps?
1217 foreach( $options as $label => $info ) {
1218 if( is_array( $info ) ) {
1219 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1220 $html .= $this->formatOptions( $info, $value );
1222 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1223 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1224 $attribs +
array( 'id' => $id ) );
1226 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1235 protected function needsLabel() {
1241 * An information field (text blob), not a proper input.
1243 class HTMLInfoField
extends HTMLFormField
{
1244 function __construct( $info ) {
1245 $info['nodata'] = true;
1247 parent
::__construct( $info );
1250 function getInputHTML( $value ) {
1251 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1254 function getTableRow( $value ) {
1255 if ( !empty( $this->mParams
['rawrow'] ) ) {
1259 return parent
::getTableRow( $value );
1262 protected function needsLabel() {
1267 class HTMLHiddenField
extends HTMLFormField
{
1269 public function getTableRow( $value ){
1270 $this->mParent
->addHiddenField(
1271 $this->mParams
['name'],
1272 $this->mParams
['default']
1277 public function getInputHTML( $value ){ return ''; }
1280 class HTMLSubmitField
extends HTMLFormField
{
1282 public function getTableRow( $value ){
1283 $this->mParent
->addButton(
1284 $this->mParams
['name'],
1285 $this->mParams
['default'],
1286 isset($this->mParams
['id']) ?
$this->mParams
['id'] : null
1290 public function getInputHTML( $value ){ return ''; }