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',
66 'edittools' => 'HTMLEditTools',
68 # HTMLTextField will output the correct type="" attribute automagically.
69 # There are about four zillion other HTML5 input types, like url, but
70 # we don't use those at the moment, so no point in adding all of them.
71 'email' => 'HTMLTextField',
72 'password' => 'HTMLTextField',
75 protected $mMessagePrefix;
76 protected $mFlatFields;
77 protected $mFieldTree;
78 protected $mShowReset = false;
81 protected $mSubmitCallback;
82 protected $mValidationErrorMessage;
85 protected $mHeader = '';
86 protected $mPost = '';
90 protected $mSubmitName;
91 protected $mSubmitText;
92 protected $mSubmitTooltip;
95 protected $mUseMultipart = false;
96 protected $mHiddenFields = array();
97 protected $mButtons = array();
99 protected $mWrapperLegend = false;
102 * Build a new HTMLForm from an array of field attributes
103 * @param $descriptor Array of Field constructs, as described above
104 * @param $messagePrefix String a prefix to go in front of default messages
106 public function __construct( $descriptor, $messagePrefix='' ) {
107 $this->mMessagePrefix
= $messagePrefix;
109 // Expand out into a tree.
110 $loadedDescriptor = array();
111 $this->mFlatFields
= array();
113 foreach( $descriptor as $fieldname => $info ) {
115 if ( isset( $info['section'] ) )
116 $section = $info['section'];
118 $info['name'] = $fieldname;
120 if ( isset( $info['type'] ) && $info['type'] == 'file' )
121 $this->mUseMultipart
= true;
123 $field = self
::loadInputFromParameters( $info );
124 $field->mParent
= $this;
126 $setSection =& $loadedDescriptor;
128 $sectionParts = explode( '/', $section );
130 while( count( $sectionParts ) ) {
131 $newName = array_shift( $sectionParts );
133 if ( !isset( $setSection[$newName] ) ) {
134 $setSection[$newName] = array();
137 $setSection =& $setSection[$newName];
141 $setSection[$fieldname] = $field;
142 $this->mFlatFields
[$fieldname] = $field;
145 $this->mFieldTree
= $loadedDescriptor;
149 * Add the HTMLForm-specific JavaScript, if it hasn't been
152 static function addJS() {
153 if( self
::$jsAdded ) return;
155 global $wgOut, $wgStylePath;
157 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
161 * Initialise a new Object for the field
162 * @param $descriptor input Descriptor, as described above
163 * @return HTMLFormField subclass
165 static function loadInputFromParameters( $descriptor ) {
166 if ( isset( $descriptor['class'] ) ) {
167 $class = $descriptor['class'];
168 } elseif ( isset( $descriptor['type'] ) ) {
169 $class = self
::$typeMappings[$descriptor['type']];
170 $descriptor['class'] = $class;
174 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
177 $obj = new $class( $descriptor );
183 * The here's-one-I-made-earlier option: do the submission if
184 * posted, or display the form with or without funky valiation
186 * @return Bool whether submission was successful.
193 # Load data from the request.
197 global $wgUser, $wgRequest;
198 $editToken = $wgRequest->getVal( 'wpEditToken' );
201 if ( $wgUser->matchEditToken( $editToken ) )
202 $result = $this->trySubmit();
204 if( $result === true )
208 $this->displayForm( $result );
213 * Validate all the fields, and call the submision callback
214 * function if everything is kosher.
215 * @return Mixed Bool true == Successful submission, Bool false
216 * == No submission attempted, anything else == Error to
219 function trySubmit() {
220 # Check for validation
221 foreach( $this->mFlatFields
as $fieldname => $field ) {
222 if ( !empty( $field->mParams
['nodata'] ) )
224 if ( $field->validate(
225 $this->mFieldData
[$fieldname],
229 return isset( $this->mValidationErrorMessage
)
230 ?
$this->mValidationErrorMessage
231 : array( 'htmlform-invalid-input' );
235 $callback = $this->mSubmitCallback
;
237 $data = $this->filterDataForSubmit( $this->mFieldData
);
239 $res = call_user_func( $callback, $data );
245 * Set a callback to a function to do something with the form
246 * once it's been successfully validated.
247 * @param $cb String function name. The function will be passed
248 * the output from HTMLForm::filterDataForSubmit, and must
249 * return Bool true on success, Bool false if no submission
250 * was attempted, or String HTML output to display on error.
252 function setSubmitCallback( $cb ) {
253 $this->mSubmitCallback
= $cb;
257 * Set a message to display on a validation error.
258 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
259 * (so each entry can be either a String or Array)
261 function setValidationErrorMessage( $msg ) {
262 $this->mValidationErrorMessage
= $msg;
266 * Set the introductory message, overwriting any existing message.
267 * @param $msg String complete text of message to display
269 function setIntro( $msg ) { $this->mPre
= $msg; }
272 * Add introductory text.
273 * @param $msg String complete text of message to display
275 function addPreText( $msg ) { $this->mPre
.= $msg; }
278 * Add header text, inside the form.
279 * @param $msg String complete text of message to display
281 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
284 * Add text to the end of the display.
285 * @param $msg String complete text of message to display
287 function addPostText( $msg ) { $this->mPost
.= $msg; }
290 * Add a hidden field to the output
291 * @param $name String field name
292 * @param $value String field value
294 public function addHiddenField( $name, $value ){
295 $this->mHiddenFields
[ $name ] = $value;
298 public function addButton( $name, $value, $id=null, $attribs=null ){
299 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
303 * Display the form (sending to wgOut), with an appropriate error
304 * message or stack of messages, and any validation errors, etc.
305 * @param $submitResult Mixed output from HTMLForm::trySubmit()
307 function displayForm( $submitResult ) {
310 if ( $submitResult !== false ) {
311 $this->displayErrors( $submitResult );
317 . $this->getHiddenFields()
318 . $this->getButtons()
321 $html = $this->wrapForm( $html );
331 * Wrap the form innards in an actual <form> element
332 * @param $html String HTML contents to wrap.
333 * @return String wrapped HTML.
335 function wrapForm( $html ) {
337 # Include a <fieldset> wrapper for style, if requested.
338 if ( $this->mWrapperLegend
!== false ){
339 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
341 # Use multipart/form-data
342 $encType = $this->mUseMultipart
343 ?
'multipart/form-data'
344 : 'application/x-www-form-urlencoded';
347 'action' => $this->getTitle()->getFullURL(),
349 'class' => 'visualClear',
350 'enctype' => $encType,
352 if ( !empty( $this->mId
) )
353 $attribs['id'] = $this->mId
;
355 return Html
::rawElement( 'form', $attribs, $html );
359 * Get the hidden fields that should go inside the form.
360 * @return String HTML.
362 function getHiddenFields() {
366 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
367 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
369 foreach( $this->mHiddenFields
as $name => $value ){
370 $html .= Html
::hidden( $name, $value ) . "\n";
377 * Get the submit and (potentially) reset buttons.
378 * @return String HTML.
380 function getButtons() {
385 if ( isset( $this->mSubmitID
) )
386 $attribs['id'] = $this->mSubmitID
;
387 if ( isset( $this->mSubmitName
) )
388 $attribs['name'] = $this->mSubmitName
;
389 if ( isset( $this->mSubmitTooltip
) ) {
391 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
394 $attribs['class'] = 'mw-htmlform-submit';
396 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
398 if( $this->mShowReset
) {
399 $html .= Html
::element(
403 'value' => wfMsg( 'htmlform-reset' )
408 foreach( $this->mButtons
as $button ){
411 'name' => $button['name'],
412 'value' => $button['value']
414 if ( $button['attribs'] )
415 $attrs +
= $button['attribs'];
416 if( isset( $button['id'] ) )
417 $attrs['id'] = $button['id'];
418 $html .= Html
::element( 'input', $attrs );
425 * Get the whole body of the form.
428 return $this->displaySection( $this->mFieldTree
);
432 * Format and display an error message stack.
433 * @param $errors Mixed String or Array of message keys
435 function displayErrors( $errors ) {
436 if ( is_array( $errors ) ) {
437 $errorstr = $this->formatErrors( $errors );
442 $errorstr = Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
445 $wgOut->addHTML( $errorstr );
449 * Format a stack of error messages into a single HTML string
450 * @param $errors Array of message keys/values
451 * @return String HTML, a <ul> list of errors
453 static function formatErrors( $errors ) {
455 foreach ( $errors as $error ) {
456 if( is_array( $error ) ) {
457 $msg = array_shift( $error );
462 $errorstr .= Html
::rawElement(
465 wfMsgExt( $msg, array( 'parseinline' ), $error )
469 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
475 * Set the text for the submit button
476 * @param $t String plaintext.
478 function setSubmitText( $t ) {
479 $this->mSubmitText
= $t;
483 * Get the text for the submit button, either customised or a default.
484 * @return unknown_type
486 function getSubmitText() {
487 return $this->mSubmitText
489 : wfMsg( 'htmlform-submit' );
492 public function setSubmitName( $name ) {
493 $this->mSubmitName
= $name;
496 public function setSubmitTooltip( $name ) {
497 $this->mSubmitTooltip
= $name;
502 * Set the id for the submit button.
503 * @param $t String. FIXME: Integrity is *not* validated
505 function setSubmitID( $t ) {
506 $this->mSubmitID
= $t;
509 public function setId( $id ) {
513 * Prompt the whole form to be wrapped in a <fieldset>, with
514 * this text as its <legend> element.
515 * @param $legend String HTML to go inside the <legend> element.
518 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
521 * Set the prefix for various default messages
522 * TODO: currently only used for the <fieldset> legend on forms
523 * with multiple sections; should be used elsewhre?
526 function setMessagePrefix( $p ) {
527 $this->mMessagePrefix
= $p;
531 * Set the title for form submission
532 * @param $t Title of page the form is on/should be posted to
534 function setTitle( $t ) {
542 function getTitle() {
543 return $this->mTitle
;
550 function displaySection( $fields, $sectionName = '' ) {
552 $subsectionHtml = '';
553 $hasLeftColumn = false;
555 foreach( $fields as $key => $value ) {
556 if ( is_object( $value ) ) {
557 $v = empty( $value->mParams
['nodata'] )
558 ?
$this->mFieldData
[$key]
559 : $value->getDefault();
560 $tableHtml .= $value->getTableRow( $v );
562 if( $value->getLabel() != ' ' )
563 $hasLeftColumn = true;
564 } elseif ( is_array( $value ) ) {
565 $section = $this->displaySection( $value, $key );
566 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
567 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
572 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
573 $classes[] = 'mw-htmlform-nolabel';
575 'classes' => implode( ' ', $classes ),
578 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
580 $tableHtml = Html
::rawElement( 'table', $attribs,
581 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
583 return $subsectionHtml . "\n" . $tableHtml;
587 * Construct the form fields from the Descriptor array
589 function loadData() {
592 $fieldData = array();
594 foreach( $this->mFlatFields
as $fieldname => $field ) {
595 if ( !empty( $field->mParams
['nodata'] ) ) continue;
596 if ( !empty( $field->mParams
['disabled'] ) ) {
597 $fieldData[$fieldname] = $field->getDefault();
599 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
604 foreach( $fieldData as $name => &$value ) {
605 $field = $this->mFlatFields
[$name];
606 $value = $field->filter( $value, $this->mFlatFields
);
609 $this->mFieldData
= $fieldData;
613 * Stop a reset button being shown for this form
614 * @param $suppressReset Bool set to false to re-enable the
617 function suppressReset( $suppressReset = true ) {
618 $this->mShowReset
= !$suppressReset;
622 * Overload this if you want to apply special filtration routines
623 * to the form as a whole, after it's submitted but before it's
626 * @return unknown_type
628 function filterDataForSubmit( $data ) {
634 * The parent class to generate form fields. Any field type should
635 * be a subclass of this.
637 abstract class HTMLFormField
{
639 protected $mValidationCallback;
640 protected $mFilterCallback;
643 protected $mLabel; # String label. Set on construction
649 * This function must be implemented to return the HTML to generate
650 * the input object itself. It should not implement the surrounding
651 * table cells/rows, or labels/help messages.
652 * @param $value String the value to set the input to; eg a default
653 * text for a text input.
654 * @return String valid HTML.
656 abstract function getInputHTML( $value );
659 * Override this function to add specific validation checks on the
660 * field input. Don't forget to call parent::validate() to ensure
661 * that the user-defined callback mValidationCallback is still run
662 * @param $value String the value the field was submitted with
663 * @param $alldata $all the data collected from the form
664 * @return Mixed Bool true on success, or String error to display.
666 function validate( $value, $alldata ) {
667 if ( isset( $this->mValidationCallback
) ) {
668 return call_user_func( $this->mValidationCallback
, $value, $alldata );
674 function filter( $value, $alldata ) {
675 if( isset( $this->mFilterCallback
) ) {
676 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
683 * Should this field have a label, or is there no input element with the
684 * appropriate id for the label to point to?
686 * @return bool True to output a label, false to suppress
688 protected function needsLabel() {
693 * Get the value that this input has been set to from a posted form,
694 * or the input's default value if it has not been set.
695 * @param $request WebRequest
696 * @return String the value
698 function loadDataFromRequest( $request ) {
699 if( $request->getCheck( $this->mName
) ) {
700 return $request->getText( $this->mName
);
702 return $this->getDefault();
707 * Initialise the object
708 * @param $params Associative Array. See HTMLForm doc for syntax.
710 function __construct( $params ) {
711 $this->mParams
= $params;
713 # Generate the label from a message, if possible
714 if( isset( $params['label-message'] ) ) {
715 $msgInfo = $params['label-message'];
717 if ( is_array( $msgInfo ) ) {
718 $msg = array_shift( $msgInfo );
724 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
725 } elseif ( isset( $params['label'] ) ) {
726 $this->mLabel
= $params['label'];
729 if ( isset( $params['name'] ) ) {
730 $name = $params['name'];
731 $validName = Sanitizer
::escapeId( $name );
732 if( $name != $validName ) {
733 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
735 $this->mName
= 'wp'.$name;
736 $this->mID
= 'mw-input-'.$name;
739 if ( isset( $params['default'] ) ) {
740 $this->mDefault
= $params['default'];
743 if ( isset( $params['id'] ) ) {
745 $validId = Sanitizer
::escapeId( $id );
746 if( $id != $validId ) {
747 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
752 if ( isset( $params['validation-callback'] ) ) {
753 $this->mValidationCallback
= $params['validation-callback'];
756 if ( isset( $params['filter-callback'] ) ) {
757 $this->mFilterCallback
= $params['filter-callback'];
762 * Get the complete table row for the input, including help text,
763 * labels, and whatever.
764 * @param $value String the value to set the input to.
765 * @return String complete HTML table row.
767 function getTableRow( $value ) {
768 # Check for invalid data.
771 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
772 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
775 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
778 $html = $this->getLabelHtml();
779 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-input' ),
780 $this->getInputHTML( $value ) ."\n$errors" );
782 $fieldType = get_class( $this );
784 $html = Html
::rawElement( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
788 if ( isset( $this->mParams
['help-message'] ) ) {
789 $msg = $this->mParams
['help-message'];
790 $helptext = wfMsgExt( $msg, 'parseinline' );
791 if ( wfEmptyMsg( $msg, $helptext ) ) {
795 } elseif ( isset( $this->mParams
['help'] ) ) {
796 $helptext = $this->mParams
['help'];
799 if ( !is_null( $helptext ) ) {
800 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
802 $row = Html
::rawElement( 'tr', array(), $row );
809 function getLabel() {
810 return $this->mLabel
;
812 function getLabelHtml() {
813 # Don't output a for= attribute for labels with no associated input.
814 # Kind of hacky here, possibly we don't want these to be <label>s at all.
816 if ( $this->needsLabel() ) {
817 $for['for'] = $this->mID
;
819 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
820 Html
::rawElement( 'label', $for, $this->getLabel() )
824 function getDefault() {
825 if ( isset( $this->mDefault
) ) {
826 return $this->mDefault
;
833 * Returns the attributes required for the tooltip and accesskey.
835 * @return array Attributes
837 public function getTooltipAndAccessKey() {
838 if ( empty( $this->mParams
['tooltip'] ) )
842 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
846 * flatten an array of options to a single array, for instance,
847 * a set of <options> inside <optgroups>.
848 * @param $options Associative Array with values either Strings
850 * @return Array flattened input
852 public static function flattenOptions( $options ) {
855 foreach( $options as $key => $value ) {
856 if ( is_array( $value ) ) {
857 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
859 $flatOpts[] = $value;
868 class HTMLTextField
extends HTMLFormField
{
871 return isset( $this->mParams
['size'] )
872 ?
$this->mParams
['size']
876 function getInputHTML( $value ) {
879 'name' => $this->mName
,
880 'size' => $this->getSize(),
882 ) +
$this->getTooltipAndAccessKey();
884 if ( isset( $this->mParams
['maxlength'] ) ) {
885 $attribs['maxlength'] = $this->mParams
['maxlength'];
888 if ( !empty( $this->mParams
['disabled'] ) ) {
889 $attribs['disabled'] = 'disabled';
892 # TODO: Enforce pattern, step, required, readonly on the server side as
894 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
895 'placeholder' ) as $param ) {
896 if ( isset( $this->mParams
[$param] ) ) {
897 $attribs[$param] = $this->mParams
[$param];
900 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
902 if ( isset( $this->mParams
[$param] ) ) {
903 $attribs[$param] = '';
907 # Implement tiny differences between some field variants
908 # here, rather than creating a new class for each one which
909 # is essentially just a clone of this one.
910 if ( isset( $this->mParams
['type'] ) ) {
911 switch ( $this->mParams
['type'] ) {
913 $attribs['type'] = 'email';
916 $attribs['type'] = 'number';
919 $attribs['type'] = 'number';
920 $attribs['step'] = 'any';
925 $attribs['type'] = $this->mParams
['type'];
930 return Html
::element( 'input', $attribs );
933 class HTMLTextAreaField
extends HTMLFormField
{
936 return isset( $this->mParams
['cols'] )
937 ?
$this->mParams
['cols']
941 return isset( $this->mParams
['rows'] )
942 ?
$this->mParams
['rows']
946 function getInputHTML( $value ) {
949 'name' => $this->mName
,
950 'cols' => $this->getCols(),
951 'rows' => $this->getRows(),
952 ) +
$this->getTooltipAndAccessKey();
955 if ( !empty( $this->mParams
['disabled'] ) ) {
956 $attribs['disabled'] = 'disabled';
958 if ( !empty( $this->mParams
['readonly'] ) ) {
959 $attribs['readonly'] = 'readonly';
962 foreach ( array( 'required', 'autofocus' ) as $param ) {
963 if ( isset( $this->mParams
[$param] ) ) {
964 $attribs[$param] = '';
968 return Html
::element( 'textarea', $attribs, $value );
973 * A field that will contain a numeric value
975 class HTMLFloatField
extends HTMLTextField
{
978 return isset( $this->mParams
['size'] )
979 ?
$this->mParams
['size']
983 function validate( $value, $alldata ) {
984 $p = parent
::validate( $value, $alldata );
986 if ( $p !== true ) return $p;
988 if ( floatval( $value ) != $value ) {
989 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
994 # The "int" part of these message names is rather confusing.
995 # They make equal sense for all numbers.
996 if ( isset( $this->mParams
['min'] ) ) {
997 $min = $this->mParams
['min'];
999 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1002 if ( isset( $this->mParams
['max'] ) ) {
1003 $max = $this->mParams
['max'];
1005 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1013 * A field that must contain a number
1015 class HTMLIntField
extends HTMLFloatField
{
1016 function validate( $value, $alldata ) {
1017 $p = parent
::validate( $value, $alldata );
1019 if ( $p !== true ) return $p;
1021 if ( intval( $value ) != $value ) {
1022 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1032 class HTMLCheckField
extends HTMLFormField
{
1033 function getInputHTML( $value ) {
1034 if ( !empty( $this->mParams
['invert'] ) )
1037 $attr = $this->getTooltipAndAccessKey();
1038 $attr['id'] = $this->mID
;
1039 if( !empty( $this->mParams
['disabled'] ) ) {
1040 $attr['disabled'] = 'disabled';
1043 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1044 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1048 * For a checkbox, the label goes on the right hand side, and is
1049 * added in getInputHTML(), rather than HTMLFormField::getRow()
1051 function getLabel() {
1055 function loadDataFromRequest( $request ) {
1057 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1061 // GetCheck won't work like we want for checks.
1062 if( $request->getCheck( 'wpEditToken' ) ) {
1063 // XOR has the following truth table, which is what we want
1064 // INVERT VALUE | OUTPUT
1065 // true true | false
1066 // false true | true
1067 // false false | false
1068 // true false | true
1069 return $request->getBool( $this->mName
) xor $invert;
1071 return $this->getDefault();
1077 * A select dropdown field. Basically a wrapper for Xmlselect class
1079 class HTMLSelectField
extends HTMLFormField
{
1081 function validate( $value, $alldata ) {
1082 $p = parent
::validate( $value, $alldata );
1083 if( $p !== true ) return $p;
1085 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1086 if ( in_array( $value, $validOptions ) )
1089 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1092 function getInputHTML( $value ) {
1093 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1095 # If one of the options' 'name' is int(0), it is automatically selected.
1096 # because PHP sucks and things int(0) == 'some string'.
1097 # Working around this by forcing all of them to strings.
1098 $options = array_map( 'strval', $this->mParams
['options'] );
1100 if( !empty( $this->mParams
['disabled'] ) ) {
1101 $select->setAttribute( 'disabled', 'disabled' );
1104 $select->addOptions( $options );
1106 return $select->getHTML();
1111 * Select dropdown field, with an additional "other" textbox.
1113 class HTMLSelectOrOtherField
extends HTMLTextField
{
1114 static $jsAdded = false;
1116 function __construct( $params ) {
1117 if( !in_array( 'other', $params['options'], true ) ) {
1118 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1121 parent
::__construct( $params );
1124 static function forceToStringRecursive( $array ) {
1125 if ( is_array($array) ) {
1126 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1128 return strval($array);
1132 function getInputHTML( $value ) {
1133 $valInSelect = false;
1135 if( $value !== false )
1136 $valInSelect = in_array( $value,
1137 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1139 $selected = $valInSelect ?
$value : 'other';
1141 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1143 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1144 $select->addOptions( $opts );
1146 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1148 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1149 if( !empty( $this->mParams
['disabled'] ) ) {
1150 $select->setAttribute( 'disabled', 'disabled' );
1151 $tbAttribs['disabled'] = 'disabled';
1154 $select = $select->getHTML();
1156 if ( isset( $this->mParams
['maxlength'] ) ) {
1157 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1160 $textbox = Html
::input( $this->mName
. '-other',
1161 $valInSelect ?
'' : $value,
1165 return "$select<br />\n$textbox";
1168 function loadDataFromRequest( $request ) {
1169 if( $request->getCheck( $this->mName
) ) {
1170 $val = $request->getText( $this->mName
);
1172 if( $val == 'other' ) {
1173 $val = $request->getText( $this->mName
. '-other' );
1178 return $this->getDefault();
1184 * Multi-select field
1186 class HTMLMultiSelectField
extends HTMLFormField
{
1188 function validate( $value, $alldata ) {
1189 $p = parent
::validate( $value, $alldata );
1190 if( $p !== true ) return $p;
1192 if( !is_array( $value ) ) return false;
1194 # If all options are valid, array_intersect of the valid options
1195 # and the provided options will return the provided options.
1196 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1198 $validValues = array_intersect( $value, $validOptions );
1199 if ( count( $validValues ) == count( $value ) )
1202 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1205 function getInputHTML( $value ) {
1206 $html = $this->formatOptions( $this->mParams
['options'], $value );
1211 function formatOptions( $options, $value ) {
1215 if ( !empty( $this->mParams
['disabled'] ) ) {
1216 $attribs['disabled'] = 'disabled';
1219 foreach( $options as $label => $info ) {
1220 if( is_array( $info ) ) {
1221 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1222 $html .= $this->formatOptions( $info, $value );
1224 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1226 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
1227 $attribs +
$thisAttribs );
1228 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1230 $html .= $checkbox . '<br />';
1237 function loadDataFromRequest( $request ) {
1238 # won't work with getCheck
1239 if( $request->getCheck( 'wpEditToken' ) ) {
1240 $arr = $request->getArray( $this->mName
);
1247 return $this->getDefault();
1251 function getDefault() {
1252 if ( isset( $this->mDefault
) ) {
1253 return $this->mDefault
;
1259 protected function needsLabel() {
1265 * Radio checkbox fields.
1267 class HTMLRadioField
extends HTMLFormField
{
1268 function validate( $value, $alldata ) {
1269 $p = parent
::validate( $value, $alldata );
1270 if( $p !== true ) return $p;
1272 if( !is_string( $value ) && !is_int( $value ) )
1275 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1277 if ( in_array( $value, $validOptions ) )
1280 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1284 * This returns a block of all the radio options, in one cell.
1285 * @see includes/HTMLFormField#getInputHTML()
1287 function getInputHTML( $value ) {
1288 $html = $this->formatOptions( $this->mParams
['options'], $value );
1293 function formatOptions( $options, $value ) {
1297 if ( !empty( $this->mParams
['disabled'] ) ) {
1298 $attribs['disabled'] = 'disabled';
1301 # TODO: should this produce an unordered list perhaps?
1302 foreach( $options as $label => $info ) {
1303 if( is_array( $info ) ) {
1304 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1305 $html .= $this->formatOptions( $info, $value );
1307 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1308 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1309 $attribs +
array( 'id' => $id ) );
1311 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1313 $html .= "<br />\n";
1320 protected function needsLabel() {
1326 * An information field (text blob), not a proper input.
1328 class HTMLInfoField
extends HTMLFormField
{
1329 function __construct( $info ) {
1330 $info['nodata'] = true;
1332 parent
::__construct( $info );
1335 function getInputHTML( $value ) {
1336 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1339 function getTableRow( $value ) {
1340 if ( !empty( $this->mParams
['rawrow'] ) ) {
1344 return parent
::getTableRow( $value );
1347 protected function needsLabel() {
1352 class HTMLHiddenField
extends HTMLFormField
{
1354 public function getTableRow( $value ){
1355 $this->mParent
->addHiddenField(
1356 $this->mParams
['name'],
1357 $this->mParams
['default']
1362 public function getInputHTML( $value ){ return ''; }
1365 class HTMLSubmitField
extends HTMLFormField
{
1367 public function getTableRow( $value ){
1368 $this->mParent
->addButton(
1369 $this->mParams
['name'],
1370 $this->mParams
['default'],
1371 isset($this->mParams
['id']) ?
$this->mParams
['id'] : null,
1372 $this->getTooltipAndAccessKey()
1376 public function getInputHTML( $value ){ return ''; }
1379 class HTMLEditTools
extends HTMLFormField
{
1380 public function getInputHTML( $value ) {
1383 public function getTableRow( $value ) {
1384 return "<tr><td></td><td class=\"mw-input\">"
1385 . '<div class="mw-editTools">'
1386 . wfMsgExt( empty( $this->mParams
['message'] )
1387 ?
'edittools' : $this->mParams
['message'],
1388 array( 'parse', 'content' ) )
1389 . "</div></td></tr>\n";