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 HTML 5 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;
157 $wgOut->addScriptClass( 'htmlform' );
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() ) . "\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 ) {
880 'name' => $this->mName
,
881 'size' => $this->getSize(),
883 ) +
$this->getTooltipAndAccessKey();
885 if ( isset( $this->mParams
['maxlength'] ) ) {
886 $attribs['maxlength'] = $this->mParams
['maxlength'];
889 if ( !empty( $this->mParams
['disabled'] ) ) {
890 $attribs['disabled'] = 'disabled';
894 # TODO: Enforce pattern, step, required, readonly on the server
896 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
897 'placeholder' ) as $param ) {
898 if ( isset( $this->mParams
[$param] ) ) {
899 $attribs[$param] = $this->mParams
[$param];
902 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
904 if ( isset( $this->mParams
[$param] ) ) {
905 $attribs[$param] = '';
910 # Implement tiny differences between some field variants
911 # here, rather than creating a new class for each one which
912 # is essentially just a clone of this one.
913 if ( isset( $this->mParams
['type'] ) ) {
914 # Options that apply only to HTML5
916 switch ( $this->mParams
['type'] ) {
918 $attribs['type'] = 'email';
921 $attribs['type'] = 'number';
924 $attribs['type'] = 'number';
925 $attribs['step'] = 'any';
929 # Options that apply to HTML4 as well
930 switch( $this->mParams
['type'] ) {
934 $attribs['type'] = $this->mParams
['type'];
939 return Html
::element( 'input', $attribs );
942 class HTMLTextAreaField
extends HTMLFormField
{
945 return isset( $this->mParams
['cols'] )
946 ?
$this->mParams
['cols']
950 return isset( $this->mParams
['rows'] )
951 ?
$this->mParams
['rows']
955 function getInputHTML( $value ) {
959 'name' => $this->mName
,
960 'cols' => $this->getCols(),
961 'rows' => $this->getRows(),
962 ) +
$this->getTooltipAndAccessKey();
965 if ( !empty( $this->mParams
['disabled'] ) ) {
966 $attribs['disabled'] = 'disabled';
968 if ( !empty( $this->mParams
['readonly'] ) ) {
969 $attribs['readonly'] = 'readonly';
973 foreach ( array( 'required', 'autofocus' ) as $param ) {
974 if ( isset( $this->mParams
[$param] ) ) {
975 $attribs[$param] = '';
981 return Html
::element( 'textarea', $attribs, $value );
986 * A field that will contain a numeric value
988 class HTMLFloatField
extends HTMLTextField
{
991 return isset( $this->mParams
['size'] )
992 ?
$this->mParams
['size']
996 function validate( $value, $alldata ) {
997 $p = parent
::validate( $value, $alldata );
999 if ( $p !== true ) return $p;
1001 if ( floatval( $value ) != $value ) {
1002 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1007 # The "int" part of these message names is rather confusing.
1008 # They make equal sense for all numbers.
1009 if ( isset( $this->mParams
['min'] ) ) {
1010 $min = $this->mParams
['min'];
1011 if ( $min > $value )
1012 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1015 if ( isset( $this->mParams
['max'] ) ) {
1016 $max = $this->mParams
['max'];
1018 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1026 * A field that must contain a number
1028 class HTMLIntField
extends HTMLFloatField
{
1029 function validate( $value, $alldata ) {
1030 $p = parent
::validate( $value, $alldata );
1032 if ( $p !== true ) return $p;
1034 if ( intval( $value ) != $value ) {
1035 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1045 class HTMLCheckField
extends HTMLFormField
{
1046 function getInputHTML( $value ) {
1047 if ( !empty( $this->mParams
['invert'] ) )
1050 $attr = $this->getTooltipAndAccessKey();
1051 $attr['id'] = $this->mID
;
1052 if( !empty( $this->mParams
['disabled'] ) ) {
1053 $attr['disabled'] = 'disabled';
1056 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1057 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1061 * For a checkbox, the label goes on the right hand side, and is
1062 * added in getInputHTML(), rather than HTMLFormField::getRow()
1064 function getLabel() {
1068 function loadDataFromRequest( $request ) {
1070 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1074 // GetCheck won't work like we want for checks.
1075 if( $request->getCheck( 'wpEditToken' ) ) {
1076 // XOR has the following truth table, which is what we want
1077 // INVERT VALUE | OUTPUT
1078 // true true | false
1079 // false true | true
1080 // false false | false
1081 // true false | true
1082 return $request->getBool( $this->mName
) xor $invert;
1084 return $this->getDefault();
1090 * A select dropdown field. Basically a wrapper for Xmlselect class
1092 class HTMLSelectField
extends HTMLFormField
{
1094 function validate( $value, $alldata ) {
1095 $p = parent
::validate( $value, $alldata );
1096 if( $p !== true ) return $p;
1098 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1099 if ( in_array( $value, $validOptions ) )
1102 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1105 function getInputHTML( $value ) {
1106 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1108 # If one of the options' 'name' is int(0), it is automatically selected.
1109 # because PHP sucks and things int(0) == 'some string'.
1110 # Working around this by forcing all of them to strings.
1111 $options = array_map( 'strval', $this->mParams
['options'] );
1113 if( !empty( $this->mParams
['disabled'] ) ) {
1114 $select->setAttribute( 'disabled', 'disabled' );
1117 $select->addOptions( $options );
1119 return $select->getHTML();
1124 * Select dropdown field, with an additional "other" textbox.
1126 class HTMLSelectOrOtherField
extends HTMLTextField
{
1127 static $jsAdded = false;
1129 function __construct( $params ) {
1130 if( !in_array( 'other', $params['options'], true ) ) {
1131 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1134 parent
::__construct( $params );
1137 static function forceToStringRecursive( $array ) {
1138 if ( is_array($array) ) {
1139 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1141 return strval($array);
1145 function getInputHTML( $value ) {
1146 $valInSelect = false;
1148 if( $value !== false )
1149 $valInSelect = in_array( $value,
1150 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1152 $selected = $valInSelect ?
$value : 'other';
1154 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1156 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1157 $select->addOptions( $opts );
1159 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1161 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1162 if( !empty( $this->mParams
['disabled'] ) ) {
1163 $select->setAttribute( 'disabled', 'disabled' );
1164 $tbAttribs['disabled'] = 'disabled';
1167 $select = $select->getHTML();
1169 if ( isset( $this->mParams
['maxlength'] ) ) {
1170 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1173 $textbox = Html
::input( $this->mName
. '-other',
1174 $valInSelect ?
'' : $value,
1178 return "$select<br/>\n$textbox";
1181 function loadDataFromRequest( $request ) {
1182 if( $request->getCheck( $this->mName
) ) {
1183 $val = $request->getText( $this->mName
);
1185 if( $val == 'other' ) {
1186 $val = $request->getText( $this->mName
. '-other' );
1191 return $this->getDefault();
1197 * Multi-select field
1199 class HTMLMultiSelectField
extends HTMLFormField
{
1201 function validate( $value, $alldata ) {
1202 $p = parent
::validate( $value, $alldata );
1203 if( $p !== true ) return $p;
1205 if( !is_array( $value ) ) return false;
1207 # If all options are valid, array_intersect of the valid options
1208 # and the provided options will return the provided options.
1209 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1211 $validValues = array_intersect( $value, $validOptions );
1212 if ( count( $validValues ) == count( $value ) )
1215 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1218 function getInputHTML( $value ) {
1219 $html = $this->formatOptions( $this->mParams
['options'], $value );
1224 function formatOptions( $options, $value ) {
1228 if ( !empty( $this->mParams
['disabled'] ) ) {
1229 $attribs['disabled'] = 'disabled';
1232 foreach( $options as $label => $info ) {
1233 if( is_array( $info ) ) {
1234 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1235 $html .= $this->formatOptions( $info, $value );
1237 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1239 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
1240 $attribs +
$thisAttribs );
1241 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1243 $html .= $checkbox . '<br />';
1250 function loadDataFromRequest( $request ) {
1251 # won't work with getCheck
1252 if( $request->getCheck( 'wpEditToken' ) ) {
1253 $arr = $request->getArray( $this->mName
);
1260 return $this->getDefault();
1264 function getDefault() {
1265 if ( isset( $this->mDefault
) ) {
1266 return $this->mDefault
;
1272 protected function needsLabel() {
1278 * Radio checkbox fields.
1280 class HTMLRadioField
extends HTMLFormField
{
1281 function validate( $value, $alldata ) {
1282 $p = parent
::validate( $value, $alldata );
1283 if( $p !== true ) return $p;
1285 if( !is_string( $value ) && !is_int( $value ) )
1288 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1290 if ( in_array( $value, $validOptions ) )
1293 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1297 * This returns a block of all the radio options, in one cell.
1298 * @see includes/HTMLFormField#getInputHTML()
1300 function getInputHTML( $value ) {
1301 $html = $this->formatOptions( $this->mParams
['options'], $value );
1306 function formatOptions( $options, $value ) {
1310 if ( !empty( $this->mParams
['disabled'] ) ) {
1311 $attribs['disabled'] = 'disabled';
1314 # TODO: should this produce an unordered list perhaps?
1315 foreach( $options as $label => $info ) {
1316 if( is_array( $info ) ) {
1317 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1318 $html .= $this->formatOptions( $info, $value );
1320 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1321 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1322 $attribs +
array( 'id' => $id ) );
1324 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1333 protected function needsLabel() {
1339 * An information field (text blob), not a proper input.
1341 class HTMLInfoField
extends HTMLFormField
{
1342 function __construct( $info ) {
1343 $info['nodata'] = true;
1345 parent
::__construct( $info );
1348 function getInputHTML( $value ) {
1349 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1352 function getTableRow( $value ) {
1353 if ( !empty( $this->mParams
['rawrow'] ) ) {
1357 return parent
::getTableRow( $value );
1360 protected function needsLabel() {
1365 class HTMLHiddenField
extends HTMLFormField
{
1367 public function getTableRow( $value ){
1368 $this->mParent
->addHiddenField(
1369 $this->mParams
['name'],
1370 $this->mParams
['default']
1375 public function getInputHTML( $value ){ return ''; }
1378 class HTMLSubmitField
extends HTMLFormField
{
1380 public function getTableRow( $value ){
1381 $this->mParent
->addButton(
1382 $this->mParams
['name'],
1383 $this->mParams
['default'],
1384 isset($this->mParams
['id']) ?
$this->mParams
['id'] : null,
1385 $this->getTooltipAndAccessKey()
1389 public function getInputHTML( $value ){ return ''; }
1392 class HTMLEditTools
extends HTMLFormField
{
1393 public function getInputHTML( $value ) {
1396 public function getTableRow( $value ) {
1397 return "<tr><td></td><td class=\"mw-input\">"
1398 . '<div class="mw-editTools">'
1399 . wfMsgExt( empty( $this->mParams
['message'] )
1400 ?
'edittools' : $this->mParams
['message'],
1401 array( 'parse', 'content' ) )
1402 . "</div></td></tr>\n";