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 'textarea' => 'HTMLTextAreaField',
55 'select' => 'HTMLSelectField',
56 'radio' => 'HTMLRadioField',
57 'multiselect' => 'HTMLMultiSelectField',
58 'check' => 'HTMLCheckField',
59 'toggle' => 'HTMLCheckField',
60 'int' => 'HTMLIntField',
61 'float' => 'HTMLFloatField',
62 'info' => 'HTMLInfoField',
63 'selectorother' => 'HTMLSelectOrOtherField',
64 'submit' => 'HTMLSubmitField',
65 'hidden' => 'HTMLHiddenField',
67 # HTMLTextField will output the correct type="" attribute automagically.
68 # There are about four zillion other HTML 5 input types, like url, but
69 # we don't use those at the moment, so no point in adding all of them.
70 'email' => 'HTMLTextField',
71 'password' => 'HTMLTextField',
74 protected $mMessagePrefix;
75 protected $mFlatFields;
76 protected $mFieldTree;
77 protected $mShowReset = false;
80 protected $mSubmitCallback;
81 protected $mValidationErrorMessage;
84 protected $mHeader = '';
85 protected $mPost = '';
88 protected $mSubmitText;
91 protected $mHiddenFields = array();
92 protected $mButtons = array();
94 protected $mWrapperLegend = false;
97 * Build a new HTMLForm from an array of field attributes
98 * @param $descriptor Array of Field constructs, as described above
99 * @param $messagePrefix String a prefix to go in front of default messages
101 public function __construct( $descriptor, $messagePrefix='' ) {
102 $this->mMessagePrefix
= $messagePrefix;
104 // Expand out into a tree.
105 $loadedDescriptor = array();
106 $this->mFlatFields
= array();
108 foreach( $descriptor as $fieldname => $info ) {
110 if ( isset( $info['section'] ) )
111 $section = $info['section'];
113 $info['name'] = $fieldname;
115 $field = self
::loadInputFromParameters( $info );
116 $field->mParent
= $this;
118 $setSection =& $loadedDescriptor;
120 $sectionParts = explode( '/', $section );
122 while( count( $sectionParts ) ) {
123 $newName = array_shift( $sectionParts );
125 if ( !isset( $setSection[$newName] ) ) {
126 $setSection[$newName] = array();
129 $setSection =& $setSection[$newName];
133 $setSection[$fieldname] = $field;
134 $this->mFlatFields
[$fieldname] = $field;
137 $this->mFieldTree
= $loadedDescriptor;
141 * Add the HTMLForm-specific JavaScript, if it hasn't been
144 static function addJS() {
145 if( self
::$jsAdded ) return;
149 $wgOut->addScriptClass( 'htmlform' );
153 * Initialise a new Object for the field
154 * @param $descriptor input Descriptor, as described above
155 * @return HTMLFormField subclass
157 static function loadInputFromParameters( $descriptor ) {
158 if ( isset( $descriptor['class'] ) ) {
159 $class = $descriptor['class'];
160 } elseif ( isset( $descriptor['type'] ) ) {
161 $class = self
::$typeMappings[$descriptor['type']];
162 $descriptor['class'] = $class;
166 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
169 $obj = new $class( $descriptor );
175 * The here's-one-I-made-earlier option: do the submission if
176 * posted, or display the form with or without funky valiation
178 * @return Bool whether submission was successful.
185 # Load data from the request.
189 global $wgUser, $wgRequest;
190 $editToken = $wgRequest->getVal( 'wpEditToken' );
193 if ( $wgUser->matchEditToken( $editToken ) )
194 $result = $this->trySubmit();
196 if( $result === true )
200 $this->displayForm( $result );
205 * Validate all the fields, and call the submision callback
206 * function if everything is kosher.
207 * @return Mixed Bool true == Successful submission, Bool false
208 * == No submission attempted, anything else == Error to
211 function trySubmit() {
212 # Check for validation
213 foreach( $this->mFlatFields
as $fieldname => $field ) {
214 if ( !empty( $field->mParams
['nodata'] ) )
216 if ( $field->validate(
217 $this->mFieldData
[$fieldname],
221 return isset( $this->mValidationErrorMessage
)
222 ?
$this->mValidationErrorMessage
223 : array( 'htmlform-invalid-input' );
227 $callback = $this->mSubmitCallback
;
229 $data = $this->filterDataForSubmit( $this->mFieldData
);
231 $res = call_user_func( $callback, $data );
237 * Set a callback to a function to do something with the form
238 * once it's been successfully validated.
239 * @param $cb String function name. The function will be passed
240 * the output from HTMLForm::filterDataForSubmit, and must
241 * return Bool true on success, Bool false if no submission
242 * was attempted, or String HTML output to display on error.
244 function setSubmitCallback( $cb ) {
245 $this->mSubmitCallback
= $cb;
249 * Set a message to display on a validation error.
250 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
251 * (so each entry can be either a String or Array)
253 function setValidationErrorMessage( $msg ) {
254 $this->mValidationErrorMessage
= $msg;
258 * Set the introductory message, overwriting any existing message.
259 * @param $msg String complete text of message to display
261 function setIntro( $msg ) { $this->mPre
= $msg; }
264 * Add introductory text.
265 * @param $msg String complete text of message to display
267 function addPreText( $msg ) { $this->mPre
.= $msg; }
270 * Add header text, inside the form.
271 * @param $msg String complete text of message to display
273 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
276 * Add text to the end of the display.
277 * @param $msg String complete text of message to display
279 function addPostText( $msg ) { $this->mPost
.= $msg; }
282 * Add a hidden field to the output
283 * @param $name String field name
284 * @param $value String field value
286 public function addHiddenField( $name, $value ){
287 $this->mHiddenFields
[ $name ] = $value;
290 public function addButton( $name, $value, $id=null ){
291 $this->mButtons
[] = compact( 'name', 'value', 'id' );
295 * Display the form (sending to wgOut), with an appropriate error
296 * message or stack of messages, and any validation errors, etc.
297 * @param $submitResult Mixed output from HTMLForm::trySubmit()
299 function displayForm( $submitResult ) {
302 if ( $submitResult !== false ) {
303 $this->displayErrors( $submitResult );
309 . $this->getHiddenFields()
310 . $this->getButtons()
313 $html = $this->wrapForm( $html );
323 * Wrap the form innards in an actual <form> element
324 * @param $html String HTML contents to wrap.
325 * @return String wrapped HTML.
327 function wrapForm( $html ) {
329 # Include a <fieldset> wrapper for style, if requested.
330 if( $this->mWrapperLegend
!== false ){
331 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
334 return Html
::rawElement(
337 'action' => $this->getTitle()->getFullURL(),
339 'class' => 'visualClear',
346 * Get the hidden fields that should go inside the form.
347 * @return String HTML.
349 function getHiddenFields() {
353 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
354 $html .= Html
::hidden( 'title', $this->getTitle() ) . "\n";
356 foreach( $this->mHiddenFields
as $name => $value ){
357 $html .= Html
::hidden( $name, $value ) . "\n";
364 * Get the submit and (potentially) reset buttons.
365 * @return String HTML.
367 function getButtons() {
372 if ( isset( $this->mSubmitID
) )
373 $attribs['id'] = $this->mSubmitID
;
375 $attribs['class'] = 'mw-htmlform-submit';
377 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
379 if( $this->mShowReset
) {
380 $html .= Html
::element(
384 'value' => wfMsg( 'htmlform-reset' )
389 foreach( $this->mButtons
as $button ){
392 'name' => $button['name'],
393 'value' => $button['value']
395 if( isset( $button['id'] ) )
396 $attrs['id'] = $button['id'];
397 $html .= Html
::element( 'input', $attrs );
404 * Get the whole body of the form.
407 return $this->displaySection( $this->mFieldTree
);
411 * Format and display an error message stack.
412 * @param $errors Mixed String or Array of message keys
414 function displayErrors( $errors ) {
415 if ( is_array( $errors ) ) {
416 $errorstr = $this->formatErrors( $errors );
421 $errorstr = Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
424 $wgOut->addHTML( $errorstr );
428 * Format a stack of error messages into a single HTML string
429 * @param $errors Array of message keys/values
430 * @return String HTML, a <ul> list of errors
432 static function formatErrors( $errors ) {
434 foreach ( $errors as $error ) {
435 if( is_array( $error ) ) {
436 $msg = array_shift( $error );
441 $errorstr .= Html
::rawElement(
444 wfMsgExt( $msg, array( 'parseinline' ), $error )
448 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
454 * Set the text for the submit button
455 * @param $t String plaintext.
457 function setSubmitText( $t ) {
458 $this->mSubmitText
= $t;
462 * Get the text for the submit button, either customised or a default.
463 * @return unknown_type
465 function getSubmitText() {
466 return $this->mSubmitText
468 : wfMsg( 'htmlform-submit' );
472 * Set the id for the submit button.
473 * @param $t String. FIXME: Integrity is *not* validated
475 function setSubmitID( $t ) {
476 $this->mSubmitID
= $t;
480 * Prompt the whole form to be wrapped in a <fieldset>, with
481 * this text as its <legend> element.
482 * @param $legend String HTML to go inside the <legend> element.
485 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
488 * Set the prefix for various default messages
489 * TODO: currently only used for the <fieldset> legend on forms
490 * with multiple sections; should be used elsewhre?
493 function setMessagePrefix( $p ) {
494 $this->mMessagePrefix
= $p;
498 * Set the title for form submission
499 * @param $t Title of page the form is on/should be posted to
501 function setTitle( $t ) {
509 function getTitle() {
510 return $this->mTitle
;
517 function displaySection( $fields ) {
519 $subsectionHtml = '';
520 $hasLeftColumn = false;
522 foreach( $fields as $key => $value ) {
523 if ( is_object( $value ) ) {
524 $v = empty( $value->mParams
['nodata'] )
525 ?
$this->mFieldData
[$key]
526 : $value->getDefault();
527 $tableHtml .= $value->getTableRow( $v );
529 if( $value->getLabel() != ' ' )
530 $hasLeftColumn = true;
531 } elseif ( is_array( $value ) ) {
532 $section = $this->displaySection( $value );
533 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
534 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
539 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
540 $classes[] = 'mw-htmlform-nolabel';
541 $classes = implode( ' ', $classes );
543 $tableHtml = Html
::rawElement( 'table', array( 'class' => $classes ),
544 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
546 return $subsectionHtml . "\n" . $tableHtml;
550 * Construct the form fields from the Descriptor array
552 function loadData() {
555 $fieldData = array();
557 foreach( $this->mFlatFields
as $fieldname => $field ) {
558 if ( !empty( $field->mParams
['nodata'] ) ) continue;
559 if ( !empty( $field->mParams
['disabled'] ) ) {
560 $fieldData[$fieldname] = $field->getDefault();
562 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
567 foreach( $fieldData as $name => &$value ) {
568 $field = $this->mFlatFields
[$name];
569 $value = $field->filter( $value, $this->mFlatFields
);
572 $this->mFieldData
= $fieldData;
576 * Stop a reset button being shown for this form
577 * @param $suppressReset Bool set to false to re-enable the
580 function suppressReset( $suppressReset = true ) {
581 $this->mShowReset
= !$suppressReset;
585 * Overload this if you want to apply special filtration routines
586 * to the form as a whole, after it's submitted but before it's
589 * @return unknown_type
591 function filterDataForSubmit( $data ) {
597 * The parent class to generate form fields. Any field type should
598 * be a subclass of this.
600 abstract class HTMLFormField
{
602 protected $mValidationCallback;
603 protected $mFilterCallback;
606 protected $mLabel; # String label. Set on construction
612 * This function must be implemented to return the HTML to generate
613 * the input object itself. It should not implement the surrounding
614 * table cells/rows, or labels/help messages.
615 * @param $value String the value to set the input to; eg a default
616 * text for a text input.
617 * @return String valid HTML.
619 abstract function getInputHTML( $value );
622 * Override this function to add specific validation checks on the
623 * field input. Don't forget to call parent::validate() to ensure
624 * that the user-defined callback mValidationCallback is still run
625 * @param $value String the value the field was submitted with
626 * @param $alldata $all the data collected from the form
627 * @return Mixed Bool true on success, or String error to display.
629 function validate( $value, $alldata ) {
630 if ( isset( $this->mValidationCallback
) ) {
631 return call_user_func( $this->mValidationCallback
, $value, $alldata );
637 function filter( $value, $alldata ) {
638 if( isset( $this->mFilterCallback
) ) {
639 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
646 * Should this field have a label, or is there no input element with the
647 * appropriate id for the label to point to?
649 * @return bool True to output a label, false to suppress
651 protected function needsLabel() {
656 * Get the value that this input has been set to from a posted form,
657 * or the input's default value if it has not been set.
658 * @param $request WebRequest
659 * @return String the value
661 function loadDataFromRequest( $request ) {
662 if( $request->getCheck( $this->mName
) ) {
663 return $request->getText( $this->mName
);
665 return $this->getDefault();
670 * Initialise the object
671 * @param $params Associative Array. See HTMLForm doc for syntax.
673 function __construct( $params ) {
674 $this->mParams
= $params;
676 # Generate the label from a message, if possible
677 if( isset( $params['label-message'] ) ) {
678 $msgInfo = $params['label-message'];
680 if ( is_array( $msgInfo ) ) {
681 $msg = array_shift( $msgInfo );
687 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
688 } elseif ( isset( $params['label'] ) ) {
689 $this->mLabel
= $params['label'];
692 if ( isset( $params['name'] ) ) {
693 $name = $params['name'];
694 $validName = Sanitizer
::escapeId( $name );
695 if( $name != $validName ) {
696 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
698 $this->mName
= 'wp'.$name;
699 $this->mID
= 'mw-input-'.$name;
702 if ( isset( $params['default'] ) ) {
703 $this->mDefault
= $params['default'];
706 if ( isset( $params['id'] ) ) {
708 $validId = Sanitizer
::escapeId( $id );
709 if( $id != $validId ) {
710 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
715 if ( isset( $params['validation-callback'] ) ) {
716 $this->mValidationCallback
= $params['validation-callback'];
719 if ( isset( $params['filter-callback'] ) ) {
720 $this->mFilterCallback
= $params['filter-callback'];
725 * Get the complete table row for the input, including help text,
726 * labels, and whatever.
727 * @param $value String the value to set the input to.
728 * @return String complete HTML table row.
730 function getTableRow( $value ) {
731 # Check for invalid data.
734 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
735 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
738 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
741 $html = $this->getLabelHtml();
742 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-input' ),
743 $this->getInputHTML( $value ) ."\n$errors" );
745 $fieldType = get_class( $this );
747 $html = Html
::rawElement( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
751 if ( isset( $this->mParams
['help-message'] ) ) {
752 $msg = $this->mParams
['help-message'];
753 $helptext = wfMsgExt( $msg, 'parseinline' );
754 if ( wfEmptyMsg( $msg, $helptext ) ) {
758 } elseif ( isset( $this->mParams
['help'] ) ) {
759 $helptext = $this->mParams
['help'];
762 if ( !is_null( $helptext ) ) {
763 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
765 $row = Html
::rawElement( 'tr', array(), $row );
772 function getLabel() {
773 return $this->mLabel
;
775 function getLabelHtml() {
776 # Don't output a for= attribute for labels with no associated input.
777 # Kind of hacky here, possibly we don't want these to be <label>s at all.
779 if ( $this->needsLabel() ) {
780 $for['for'] = $this->mID
;
782 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
783 Html
::rawElement( 'label', $for, $this->getLabel() )
787 function getDefault() {
788 if ( isset( $this->mDefault
) ) {
789 return $this->mDefault
;
796 * flatten an array of options to a single array, for instance,
797 * a set of <options> inside <optgroups>.
798 * @param $options Associative Array with values either Strings
800 * @return Array flattened input
802 public static function flattenOptions( $options ) {
805 foreach( $options as $key => $value ) {
806 if ( is_array( $value ) ) {
807 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
809 $flatOpts[] = $value;
817 class HTMLTextField
extends HTMLFormField
{
820 return isset( $this->mParams
['size'] )
821 ?
$this->mParams
['size']
825 function getInputHTML( $value ) {
829 'name' => $this->mName
,
830 'size' => $this->getSize(),
834 if ( isset( $this->mParams
['maxlength'] ) ) {
835 $attribs['maxlength'] = $this->mParams
['maxlength'];
838 if ( !empty( $this->mParams
['disabled'] ) ) {
839 $attribs['disabled'] = 'disabled';
843 # TODO: Enforce pattern, step, required, readonly on the server
845 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
846 'placeholder' ) as $param ) {
847 if ( isset( $this->mParams
[$param] ) ) {
848 $attribs[$param] = $this->mParams
[$param];
851 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
853 if ( isset( $this->mParams
[$param] ) ) {
854 $attribs[$param] = '';
859 # Implement tiny differences between some field variants
860 # here, rather than creating a new class for each one which
861 # is essentially just a clone of this one.
862 if ( isset( $this->mParams
['type'] ) ) {
863 # Options that apply only to HTML5
865 switch ( $this->mParams
['type'] ) {
867 $attribs['type'] = 'email';
870 $attribs['type'] = 'number';
873 $attribs['type'] = 'number';
874 $attribs['step'] = 'any';
878 # Options that apply to HTML4 as well
879 switch( $this->mParams
['type'] ) {
883 $attribs['type'] = $this->mParams
['type'];
888 return Html
::element( 'input', $attribs );
891 class HTMLTextAreaField
extends HTMLFormField
{
894 return isset( $this->mParams
['cols'] )
895 ?
$this->mParams
['cols']
899 return isset( $this->mParams
['rows'] )
900 ?
$this->mParams
['rows']
904 function getInputHTML( $value ) {
908 'name' => $this->mName
,
909 'cols' => $this->getCols(),
910 'rows' => $this->getRows(),
914 if ( !empty( $this->mParams
['disabled'] ) ) {
915 $attribs['disabled'] = 'disabled';
917 if ( !empty( $this->mParams
['readonly'] ) ) {
918 $attribs['readonly'] = 'readonly';
922 foreach ( array( 'required', 'autofocus' ) as $param ) {
923 if ( isset( $this->mParams
[$param] ) ) {
924 $attribs[$param] = '';
930 return Html
::element( 'textarea', $attribs, $value );
935 * A field that will contain a numeric value
937 class HTMLFloatField
extends HTMLTextField
{
940 return isset( $this->mParams
['size'] )
941 ?
$this->mParams
['size']
945 function validate( $value, $alldata ) {
946 $p = parent
::validate( $value, $alldata );
948 if ( $p !== true ) return $p;
950 if ( floatval( $value ) != $value ) {
951 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
956 # The "int" part of these message names is rather confusing.
957 # They make equal sense for all numbers.
958 if ( isset( $this->mParams
['min'] ) ) {
959 $min = $this->mParams
['min'];
961 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
964 if ( isset( $this->mParams
['max'] ) ) {
965 $max = $this->mParams
['max'];
967 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
975 * A field that must contain a number
977 class HTMLIntField
extends HTMLFloatField
{
978 function validate( $value, $alldata ) {
979 $p = parent
::validate( $value, $alldata );
981 if ( $p !== true ) return $p;
983 if ( intval( $value ) != $value ) {
984 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
994 class HTMLCheckField
extends HTMLFormField
{
995 function getInputHTML( $value ) {
996 if ( !empty( $this->mParams
['invert'] ) )
999 $attr = array( 'id' => $this->mID
);
1000 if( !empty( $this->mParams
['disabled'] ) ) {
1001 $attr['disabled'] = 'disabled';
1004 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1005 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1009 * For a checkbox, the label goes on the right hand side, and is
1010 * added in getInputHTML(), rather than HTMLFormField::getRow()
1012 function getLabel() {
1016 function loadDataFromRequest( $request ) {
1018 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1022 // GetCheck won't work like we want for checks.
1023 if( $request->getCheck( 'wpEditToken' ) ) {
1024 // XOR has the following truth table, which is what we want
1025 // INVERT VALUE | OUTPUT
1026 // true true | false
1027 // false true | true
1028 // false false | false
1029 // true false | true
1030 return $request->getBool( $this->mName
) xor $invert;
1032 return $this->getDefault();
1038 * A select dropdown field. Basically a wrapper for Xmlselect class
1040 class HTMLSelectField
extends HTMLFormField
{
1042 function validate( $value, $alldata ) {
1043 $p = parent
::validate( $value, $alldata );
1044 if( $p !== true ) return $p;
1046 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1047 if ( in_array( $value, $validOptions ) )
1050 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1053 function getInputHTML( $value ) {
1054 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1056 # If one of the options' 'name' is int(0), it is automatically selected.
1057 # because PHP sucks and things int(0) == 'some string'.
1058 # Working around this by forcing all of them to strings.
1059 $options = array_map( 'strval', $this->mParams
['options'] );
1061 if( !empty( $this->mParams
['disabled'] ) ) {
1062 $select->setAttribute( 'disabled', 'disabled' );
1065 $select->addOptions( $options );
1067 return $select->getHTML();
1072 * Select dropdown field, with an additional "other" textbox.
1074 class HTMLSelectOrOtherField
extends HTMLTextField
{
1075 static $jsAdded = false;
1077 function __construct( $params ) {
1078 if( !in_array( 'other', $params['options'], true ) ) {
1079 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1082 parent
::__construct( $params );
1085 static function forceToStringRecursive( $array ) {
1086 if ( is_array($array) ) {
1087 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1089 return strval($array);
1093 function getInputHTML( $value ) {
1094 $valInSelect = false;
1096 if( $value !== false )
1097 $valInSelect = in_array( $value,
1098 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1100 $selected = $valInSelect ?
$value : 'other';
1102 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1104 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1105 $select->addOptions( $opts );
1107 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1109 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1110 if( !empty( $this->mParams
['disabled'] ) ) {
1111 $select->setAttribute( 'disabled', 'disabled' );
1112 $tbAttribs['disabled'] = 'disabled';
1115 $select = $select->getHTML();
1117 if ( isset( $this->mParams
['maxlength'] ) ) {
1118 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1121 $textbox = Html
::input( $this->mName
. '-other',
1122 $valInSelect ?
'' : $value,
1126 return "$select<br/>\n$textbox";
1129 function loadDataFromRequest( $request ) {
1130 if( $request->getCheck( $this->mName
) ) {
1131 $val = $request->getText( $this->mName
);
1133 if( $val == 'other' ) {
1134 $val = $request->getText( $this->mName
. '-other' );
1139 return $this->getDefault();
1145 * Multi-select field
1147 class HTMLMultiSelectField
extends HTMLFormField
{
1149 function validate( $value, $alldata ) {
1150 $p = parent
::validate( $value, $alldata );
1151 if( $p !== true ) return $p;
1153 if( !is_array( $value ) ) return false;
1155 # If all options are valid, array_intersect of the valid options
1156 # and the provided options will return the provided options.
1157 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1159 $validValues = array_intersect( $value, $validOptions );
1160 if ( count( $validValues ) == count( $value ) )
1163 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1166 function getInputHTML( $value ) {
1167 $html = $this->formatOptions( $this->mParams
['options'], $value );
1172 function formatOptions( $options, $value ) {
1176 if ( !empty( $this->mParams
['disabled'] ) ) {
1177 $attribs['disabled'] = 'disabled';
1180 foreach( $options as $label => $info ) {
1181 if( is_array( $info ) ) {
1182 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1183 $html .= $this->formatOptions( $info, $value );
1185 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1187 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
1188 $attribs +
$thisAttribs );
1189 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1191 $html .= $checkbox . '<br />';
1198 function loadDataFromRequest( $request ) {
1199 # won't work with getCheck
1200 if( $request->getCheck( 'wpEditToken' ) ) {
1201 $arr = $request->getArray( $this->mName
);
1208 return $this->getDefault();
1212 function getDefault() {
1213 if ( isset( $this->mDefault
) ) {
1214 return $this->mDefault
;
1220 protected function needsLabel() {
1226 * Radio checkbox fields.
1228 class HTMLRadioField
extends HTMLFormField
{
1229 function validate( $value, $alldata ) {
1230 $p = parent
::validate( $value, $alldata );
1231 if( $p !== true ) return $p;
1233 if( !is_string( $value ) && !is_int( $value ) )
1236 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1238 if ( in_array( $value, $validOptions ) )
1241 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1245 * This returns a block of all the radio options, in one cell.
1246 * @see includes/HTMLFormField#getInputHTML()
1248 function getInputHTML( $value ) {
1249 $html = $this->formatOptions( $this->mParams
['options'], $value );
1254 function formatOptions( $options, $value ) {
1258 if ( !empty( $this->mParams
['disabled'] ) ) {
1259 $attribs['disabled'] = 'disabled';
1262 # TODO: should this produce an unordered list perhaps?
1263 foreach( $options as $label => $info ) {
1264 if( is_array( $info ) ) {
1265 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1266 $html .= $this->formatOptions( $info, $value );
1268 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1269 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1270 $attribs +
array( 'id' => $id ) );
1272 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1281 protected function needsLabel() {
1287 * An information field (text blob), not a proper input.
1289 class HTMLInfoField
extends HTMLFormField
{
1290 function __construct( $info ) {
1291 $info['nodata'] = true;
1293 parent
::__construct( $info );
1296 function getInputHTML( $value ) {
1297 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1300 function getTableRow( $value ) {
1301 if ( !empty( $this->mParams
['rawrow'] ) ) {
1305 return parent
::getTableRow( $value );
1308 protected function needsLabel() {
1313 class HTMLHiddenField
extends HTMLFormField
{
1315 public function getTableRow( $value ){
1316 $this->mParent
->addHiddenField(
1317 $this->mParams
['name'],
1318 $this->mParams
['default']
1323 public function getInputHTML( $value ){ return ''; }
1326 class HTMLSubmitField
extends HTMLFormField
{
1328 public function getTableRow( $value ){
1329 $this->mParent
->addButton(
1330 $this->mParams
['name'],
1331 $this->mParams
['default'],
1332 isset($this->mParams
['id']) ?
$this->mParams
['id'] : null
1336 public function getInputHTML( $value ){ return ''; }