50683a4b196a6c6d9cf7d989a18ee868710955b6
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] = '';
856 # Implement tiny differences between some field variants
857 # here, rather than creating a new class for each one which
858 # is essentially just a clone of this one.
859 if ( isset( $this->mParams
['type'] ) ) {
860 switch ( $this->mParams
['type'] ) {
862 $attribs['type'] = 'email';
865 $attribs['type'] = 'number';
868 $attribs['type'] = 'number';
869 $attribs['step'] = 'any';
872 $attribs['type'] = 'password';
878 return Html
::element( 'input', $attribs );
883 * A field that will contain a numeric value
885 class HTMLFloatField
extends HTMLTextField
{
888 return isset( $this->mParams
['size'] )
889 ?
$this->mParams
['size']
893 function validate( $value, $alldata ) {
894 $p = parent
::validate( $value, $alldata );
896 if ( $p !== true ) return $p;
898 if ( floatval( $value ) != $value ) {
899 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
904 # The "int" part of these message names is rather confusing.
905 # They make equal sense for all numbers.
906 if ( isset( $this->mParams
['min'] ) ) {
907 $min = $this->mParams
['min'];
909 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
912 if ( isset( $this->mParams
['max'] ) ) {
913 $max = $this->mParams
['max'];
915 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
923 * A field that must contain a number
925 class HTMLIntField
extends HTMLFloatField
{
926 function validate( $value, $alldata ) {
927 $p = parent
::validate( $value, $alldata );
929 if ( $p !== true ) return $p;
931 if ( intval( $value ) != $value ) {
932 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
942 class HTMLCheckField
extends HTMLFormField
{
943 function getInputHTML( $value ) {
944 if ( !empty( $this->mParams
['invert'] ) )
947 $attr = array( 'id' => $this->mID
);
948 if( !empty( $this->mParams
['disabled'] ) ) {
949 $attr['disabled'] = 'disabled';
952 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
953 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
957 * For a checkbox, the label goes on the right hand side, and is
958 * added in getInputHTML(), rather than HTMLFormField::getRow()
960 function getLabel() {
964 function loadDataFromRequest( $request ) {
966 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
970 // GetCheck won't work like we want for checks.
971 if( $request->getCheck( 'wpEditToken' ) ) {
972 // XOR has the following truth table, which is what we want
973 // INVERT VALUE | OUTPUT
976 // false false | false
978 return $request->getBool( $this->mName
) xor $invert;
980 return $this->getDefault();
986 * A select dropdown field. Basically a wrapper for Xmlselect class
988 class HTMLSelectField
extends HTMLFormField
{
990 function validate( $value, $alldata ) {
991 $p = parent
::validate( $value, $alldata );
992 if( $p !== true ) return $p;
994 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
995 if ( in_array( $value, $validOptions ) )
998 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1001 function getInputHTML( $value ) {
1002 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1004 # If one of the options' 'name' is int(0), it is automatically selected.
1005 # because PHP sucks and things int(0) == 'some string'.
1006 # Working around this by forcing all of them to strings.
1007 $options = array_map( 'strval', $this->mParams
['options'] );
1009 if( !empty( $this->mParams
['disabled'] ) ) {
1010 $select->setAttribute( 'disabled', 'disabled' );
1013 $select->addOptions( $options );
1015 return $select->getHTML();
1020 * Select dropdown field, with an additional "other" textbox.
1022 class HTMLSelectOrOtherField
extends HTMLTextField
{
1023 static $jsAdded = false;
1025 function __construct( $params ) {
1026 if( !in_array( 'other', $params['options'], true ) ) {
1027 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1030 parent
::__construct( $params );
1033 static function forceToStringRecursive( $array ) {
1034 if ( is_array($array) ) {
1035 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1037 return strval($array);
1041 function getInputHTML( $value ) {
1042 $valInSelect = false;
1044 if( $value !== false )
1045 $valInSelect = in_array( $value,
1046 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1048 $selected = $valInSelect ?
$value : 'other';
1050 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1052 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1053 $select->addOptions( $opts );
1055 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1057 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1058 if( !empty( $this->mParams
['disabled'] ) ) {
1059 $select->setAttribute( 'disabled', 'disabled' );
1060 $tbAttribs['disabled'] = 'disabled';
1063 $select = $select->getHTML();
1065 if ( isset( $this->mParams
['maxlength'] ) ) {
1066 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1069 $textbox = Html
::input( $this->mName
. '-other',
1070 $valInSelect ?
'' : $value,
1074 return "$select<br/>\n$textbox";
1077 function loadDataFromRequest( $request ) {
1078 if( $request->getCheck( $this->mName
) ) {
1079 $val = $request->getText( $this->mName
);
1081 if( $val == 'other' ) {
1082 $val = $request->getText( $this->mName
. '-other' );
1087 return $this->getDefault();
1093 * Multi-select field
1095 class HTMLMultiSelectField
extends HTMLFormField
{
1097 function validate( $value, $alldata ) {
1098 $p = parent
::validate( $value, $alldata );
1099 if( $p !== true ) return $p;
1101 if( !is_array( $value ) ) return false;
1103 # If all options are valid, array_intersect of the valid options
1104 # and the provided options will return the provided options.
1105 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1107 $validValues = array_intersect( $value, $validOptions );
1108 if ( count( $validValues ) == count( $value ) )
1111 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1114 function getInputHTML( $value ) {
1115 $html = $this->formatOptions( $this->mParams
['options'], $value );
1120 function formatOptions( $options, $value ) {
1124 if ( !empty( $this->mParams
['disabled'] ) ) {
1125 $attribs['disabled'] = 'disabled';
1128 foreach( $options as $label => $info ) {
1129 if( is_array( $info ) ) {
1130 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1131 $html .= $this->formatOptions( $info, $value );
1133 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1135 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
1136 $attribs +
$thisAttribs );
1137 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1139 $html .= $checkbox . '<br />';
1146 function loadDataFromRequest( $request ) {
1147 # won't work with getCheck
1148 if( $request->getCheck( 'wpEditToken' ) ) {
1149 $arr = $request->getArray( $this->mName
);
1156 return $this->getDefault();
1160 function getDefault() {
1161 if ( isset( $this->mDefault
) ) {
1162 return $this->mDefault
;
1168 protected function needsLabel() {
1174 * Radio checkbox fields.
1176 class HTMLRadioField
extends HTMLFormField
{
1177 function validate( $value, $alldata ) {
1178 $p = parent
::validate( $value, $alldata );
1179 if( $p !== true ) return $p;
1181 if( !is_string( $value ) && !is_int( $value ) )
1184 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1186 if ( in_array( $value, $validOptions ) )
1189 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1193 * This returns a block of all the radio options, in one cell.
1194 * @see includes/HTMLFormField#getInputHTML()
1196 function getInputHTML( $value ) {
1197 $html = $this->formatOptions( $this->mParams
['options'], $value );
1202 function formatOptions( $options, $value ) {
1206 if ( !empty( $this->mParams
['disabled'] ) ) {
1207 $attribs['disabled'] = 'disabled';
1210 # TODO: should this produce an unordered list perhaps?
1211 foreach( $options as $label => $info ) {
1212 if( is_array( $info ) ) {
1213 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1214 $html .= $this->formatOptions( $info, $value );
1216 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1217 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1218 $attribs +
array( 'id' => $id ) );
1220 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1229 protected function needsLabel() {
1235 * An information field (text blob), not a proper input.
1237 class HTMLInfoField
extends HTMLFormField
{
1238 function __construct( $info ) {
1239 $info['nodata'] = true;
1241 parent
::__construct( $info );
1244 function getInputHTML( $value ) {
1245 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1248 function getTableRow( $value ) {
1249 if ( !empty( $this->mParams
['rawrow'] ) ) {
1253 return parent
::getTableRow( $value );
1256 protected function needsLabel() {
1261 class HTMLHiddenField
extends HTMLFormField
{
1263 public function getTableRow( $value ){
1264 $this->mParent
->addHiddenField(
1265 $this->mParams
['name'],
1266 $this->mParams
['default']
1271 public function getInputHTML( $value ){ return ''; }
1274 class HTMLSubmitField
extends HTMLFormField
{
1276 public function getTableRow( $value ){
1277 $this->mParent
->addButton(
1278 $this->mParams
['name'],
1279 $this->mParams
['default'],
1280 isset($this->mParams
['id']) ?
$this->mParams
['id'] : null
1284 public function getInputHTML( $value ){ return ''; }