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 * 'cssclass' -- CSS class
28 * 'options' -- varies according to the specific object.
29 * 'label-message' -- message key for a message to use as the label.
30 * can be an array of msg key and then parameters to
32 * 'label' -- alternatively, a raw text message. Overridden by
34 * 'help-message' -- message key for a message to use as a help text.
35 * can be an array of msg key and then parameters to
37 * 'required' -- passed through to the object, indicating that it
38 * is a required field.
39 * 'size' -- the length of text fields
40 * 'filter-callback -- a function name to give you the chance to
41 * massage the inputted value before it's processed.
42 * @see HTMLForm::filter()
43 * 'validation-callback' -- a function name to give you the chance
44 * to impose extra validation on the field input.
45 * @see HTMLForm::validate()
47 * TODO: Document 'section' / 'subsection' stuff
50 static $jsAdded = false;
52 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
53 static $typeMappings = array(
54 'text' => 'HTMLTextField',
55 'textarea' => 'HTMLTextAreaField',
56 'select' => 'HTMLSelectField',
57 'radio' => 'HTMLRadioField',
58 'multiselect' => 'HTMLMultiSelectField',
59 'check' => 'HTMLCheckField',
60 'toggle' => 'HTMLCheckField',
61 'int' => 'HTMLIntField',
62 'float' => 'HTMLFloatField',
63 'info' => 'HTMLInfoField',
64 'selectorother' => 'HTMLSelectOrOtherField',
65 'submit' => 'HTMLSubmitField',
66 'hidden' => 'HTMLHiddenField',
67 'edittools' => 'HTMLEditTools',
69 # HTMLTextField will output the correct type="" attribute automagically.
70 # There are about four zillion other HTML5 input types, like url, but
71 # we don't use those at the moment, so no point in adding all of them.
72 'email' => 'HTMLTextField',
73 'password' => 'HTMLTextField',
76 protected $mMessagePrefix;
77 protected $mFlatFields;
78 protected $mFieldTree;
79 protected $mShowReset = false;
82 protected $mSubmitCallback;
83 protected $mValidationErrorMessage;
86 protected $mHeader = '';
87 protected $mFooter = '';
88 protected $mPost = '';
92 protected $mSubmitName;
93 protected $mSubmitText;
94 protected $mSubmitTooltip;
97 protected $mUseMultipart = false;
98 protected $mHiddenFields = array();
99 protected $mButtons = array();
101 protected $mWrapperLegend = false;
104 * Build a new HTMLForm from an array of field attributes
105 * @param $descriptor Array of Field constructs, as described above
106 * @param $messagePrefix String a prefix to go in front of default messages
108 public function __construct( $descriptor, $messagePrefix='' ) {
109 $this->mMessagePrefix
= $messagePrefix;
111 // Expand out into a tree.
112 $loadedDescriptor = array();
113 $this->mFlatFields
= array();
115 foreach( $descriptor as $fieldname => $info ) {
116 $section = isset( $info['section'] )
120 $info['name'] = isset( $info['name'] )
124 if ( isset( $info['type'] ) && $info['type'] == 'file' ){
125 $this->mUseMultipart
= true;
128 $field = self
::loadInputFromParameters( $info );
129 $field->mParent
= $this;
131 $setSection =& $loadedDescriptor;
133 $sectionParts = explode( '/', $section );
135 while( count( $sectionParts ) ) {
136 $newName = array_shift( $sectionParts );
138 if ( !isset( $setSection[$newName] ) ) {
139 $setSection[$newName] = array();
142 $setSection =& $setSection[$newName];
146 $setSection[$fieldname] = $field;
147 $this->mFlatFields
[$fieldname] = $field;
150 $this->mFieldTree
= $loadedDescriptor;
154 * Add the HTMLForm-specific JavaScript, if it hasn't been
157 static function addJS() {
158 if( self
::$jsAdded ) return;
160 global $wgOut, $wgStylePath;
162 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
166 * Initialise a new Object for the field
167 * @param $descriptor input Descriptor, as described above
168 * @return HTMLFormField subclass
170 static function loadInputFromParameters( $descriptor ) {
171 if ( isset( $descriptor['class'] ) ) {
172 $class = $descriptor['class'];
173 } elseif ( isset( $descriptor['type'] ) ) {
174 $class = self
::$typeMappings[$descriptor['type']];
175 $descriptor['class'] = $class;
179 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
182 $obj = new $class( $descriptor );
188 * The here's-one-I-made-earlier option: do the submission if
189 * posted, or display the form with or without funky valiation
191 * @return Bool whether submission was successful.
198 # Load data from the request.
202 global $wgUser, $wgRequest;
203 $editToken = $wgRequest->getVal( 'wpEditToken' );
206 if ( $wgUser->matchEditToken( $editToken ) )
207 $result = $this->trySubmit();
209 if( $result === true )
213 $this->displayForm( $result );
218 * Validate all the fields, and call the submision callback
219 * function if everything is kosher.
220 * @return Mixed Bool true == Successful submission, Bool false
221 * == No submission attempted, anything else == Error to
224 function trySubmit() {
225 # Check for validation
226 foreach( $this->mFlatFields
as $fieldname => $field ) {
227 if ( !empty( $field->mParams
['nodata'] ) ){
230 if ( $field->validate(
231 $this->mFieldData
[$fieldname],
235 return isset( $this->mValidationErrorMessage
)
236 ?
$this->mValidationErrorMessage
237 : array( 'htmlform-invalid-input' );
241 $callback = $this->mSubmitCallback
;
243 $data = $this->filterDataForSubmit( $this->mFieldData
);
245 $res = call_user_func( $callback, $data );
251 * Set a callback to a function to do something with the form
252 * once it's been successfully validated.
253 * @param $cb String function name. The function will be passed
254 * the output from HTMLForm::filterDataForSubmit, and must
255 * return Bool true on success, Bool false if no submission
256 * was attempted, or String HTML output to display on error.
258 function setSubmitCallback( $cb ) {
259 $this->mSubmitCallback
= $cb;
263 * Set a message to display on a validation error.
264 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
265 * (so each entry can be either a String or Array)
267 function setValidationErrorMessage( $msg ) {
268 $this->mValidationErrorMessage
= $msg;
272 * Set the introductory message, overwriting any existing message.
273 * @param $msg String complete text of message to display
275 function setIntro( $msg ) { $this->mPre
= $msg; }
278 * Add introductory text.
279 * @param $msg String complete text of message to display
281 function addPreText( $msg ) { $this->mPre
.= $msg; }
284 * Add header text, inside the form.
285 * @param $msg String complete text of message to display
287 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
290 * Add footer text, inside the form.
291 * @param $msg String complete text of message to display
293 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
296 * Add text to the end of the display.
297 * @param $msg String complete text of message to display
299 function addPostText( $msg ) { $this->mPost
.= $msg; }
302 * Add a hidden field to the output
303 * @param $name String field name
304 * @param $value String field value
305 * @param $attribs Array
307 public function addHiddenField( $name, $value, $attribs=array() ){
308 $attribs +
= array( 'name' => $name );
309 $this->mHiddenFields
[] = array( $value, $attribs );
312 public function addButton( $name, $value, $id=null, $attribs=null ){
313 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
317 * Display the form (sending to wgOut), with an appropriate error
318 * message or stack of messages, and any validation errors, etc.
319 * @param $submitResult Mixed output from HTMLForm::trySubmit()
321 function displayForm( $submitResult ) {
325 . $this->getErrors( $submitResult )
328 . $this->getHiddenFields()
329 . $this->getButtons()
333 $html = $this->wrapForm( $html );
343 * Wrap the form innards in an actual <form> element
344 * @param $html String HTML contents to wrap.
345 * @return String wrapped HTML.
347 function wrapForm( $html ) {
349 # Include a <fieldset> wrapper for style, if requested.
350 if ( $this->mWrapperLegend
!== false ){
351 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
353 # Use multipart/form-data
354 $encType = $this->mUseMultipart
355 ?
'multipart/form-data'
356 : 'application/x-www-form-urlencoded';
359 'action' => $this->getTitle()->getFullURL(),
361 'class' => 'visualClear',
362 'enctype' => $encType,
364 if ( !empty( $this->mId
) )
365 $attribs['id'] = $this->mId
;
367 return Html
::rawElement( 'form', $attribs, $html );
371 * Get the hidden fields that should go inside the form.
372 * @return String HTML.
374 function getHiddenFields() {
378 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
379 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
381 foreach( $this->mHiddenFields
as $data ){
382 list( $value, $attribs ) = $data;
383 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
390 * Get the submit and (potentially) reset buttons.
391 * @return String HTML.
393 function getButtons() {
398 if ( isset( $this->mSubmitID
) )
399 $attribs['id'] = $this->mSubmitID
;
400 if ( isset( $this->mSubmitName
) )
401 $attribs['name'] = $this->mSubmitName
;
402 if ( isset( $this->mSubmitTooltip
) ) {
404 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
407 $attribs['class'] = 'mw-htmlform-submit';
409 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
411 if( $this->mShowReset
) {
412 $html .= Html
::element(
416 'value' => wfMsg( 'htmlform-reset' )
421 foreach( $this->mButtons
as $button ){
424 'name' => $button['name'],
425 'value' => $button['value']
427 if ( $button['attribs'] )
428 $attrs +
= $button['attribs'];
429 if( isset( $button['id'] ) )
430 $attrs['id'] = $button['id'];
431 $html .= Html
::element( 'input', $attrs );
438 * Get the whole body of the form.
441 return $this->displaySection( $this->mFieldTree
);
445 * Format and display an error message stack.
446 * @param $errors Mixed String or Array of message keys
449 function getErrors( $errors ) {
450 if ( is_array( $errors ) ) {
451 $errorstr = $this->formatErrors( $errors );
457 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
462 * Format a stack of error messages into a single HTML string
463 * @param $errors Array of message keys/values
464 * @return String HTML, a <ul> list of errors
466 static function formatErrors( $errors ) {
468 foreach ( $errors as $error ) {
469 if( is_array( $error ) ) {
470 $msg = array_shift( $error );
475 $errorstr .= Html
::rawElement(
478 wfMsgExt( $msg, array( 'parseinline' ), $error )
482 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
488 * Set the text for the submit button
489 * @param $t String plaintext.
491 function setSubmitText( $t ) {
492 $this->mSubmitText
= $t;
496 * Get the text for the submit button, either customised or a default.
497 * @return unknown_type
499 function getSubmitText() {
500 return $this->mSubmitText
502 : wfMsg( 'htmlform-submit' );
505 public function setSubmitName( $name ) {
506 $this->mSubmitName
= $name;
509 public function setSubmitTooltip( $name ) {
510 $this->mSubmitTooltip
= $name;
515 * Set the id for the submit button.
516 * @param $t String. FIXME: Integrity is *not* validated
518 function setSubmitID( $t ) {
519 $this->mSubmitID
= $t;
522 public function setId( $id ) {
526 * Prompt the whole form to be wrapped in a <fieldset>, with
527 * this text as its <legend> element.
528 * @param $legend String HTML to go inside the <legend> element.
531 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
534 * Set the prefix for various default messages
535 * TODO: currently only used for the <fieldset> legend on forms
536 * with multiple sections; should be used elsewhre?
539 function setMessagePrefix( $p ) {
540 $this->mMessagePrefix
= $p;
544 * Set the title for form submission
545 * @param $t Title of page the form is on/should be posted to
547 function setTitle( $t ) {
555 function getTitle() {
556 return $this->mTitle
;
563 function displaySection( $fields, $sectionName = '' ) {
565 $subsectionHtml = '';
566 $hasLeftColumn = false;
568 foreach( $fields as $key => $value ) {
569 if ( is_object( $value ) ) {
570 $v = empty( $value->mParams
['nodata'] )
571 ?
$this->mFieldData
[$key]
572 : $value->getDefault();
573 $tableHtml .= $value->getTableRow( $v );
575 if( $value->getLabel() != ' ' )
576 $hasLeftColumn = true;
577 } elseif ( is_array( $value ) ) {
578 $section = $this->displaySection( $value, $key );
579 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
580 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
585 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
586 $classes[] = 'mw-htmlform-nolabel';
588 'class' => implode( ' ', $classes ),
591 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
593 $tableHtml = Html
::rawElement( 'table', $attribs,
594 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
596 return $subsectionHtml . "\n" . $tableHtml;
600 * Construct the form fields from the Descriptor array
602 function loadData() {
605 $fieldData = array();
607 foreach( $this->mFlatFields
as $fieldname => $field ) {
608 if ( !empty( $field->mParams
['nodata'] ) ){
610 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
611 $fieldData[$fieldname] = $field->getDefault();
613 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
618 foreach( $fieldData as $name => &$value ) {
619 $field = $this->mFlatFields
[$name];
620 $value = $field->filter( $value, $this->mFlatFields
);
623 $this->mFieldData
= $fieldData;
627 * Stop a reset button being shown for this form
628 * @param $suppressReset Bool set to false to re-enable the
631 function suppressReset( $suppressReset = true ) {
632 $this->mShowReset
= !$suppressReset;
636 * Overload this if you want to apply special filtration routines
637 * to the form as a whole, after it's submitted but before it's
640 * @return unknown_type
642 function filterDataForSubmit( $data ) {
648 * The parent class to generate form fields. Any field type should
649 * be a subclass of this.
651 abstract class HTMLFormField
{
653 protected $mValidationCallback;
654 protected $mFilterCallback;
657 protected $mLabel; # String label. Set on construction
659 protected $mClass = '';
664 * This function must be implemented to return the HTML to generate
665 * the input object itself. It should not implement the surrounding
666 * table cells/rows, or labels/help messages.
667 * @param $value String the value to set the input to; eg a default
668 * text for a text input.
669 * @return String valid HTML.
671 abstract function getInputHTML( $value );
674 * Override this function to add specific validation checks on the
675 * field input. Don't forget to call parent::validate() to ensure
676 * that the user-defined callback mValidationCallback is still run
677 * @param $value String the value the field was submitted with
678 * @param $alldata Array the data collected from the form
679 * @return Mixed Bool true on success, or String error to display.
681 function validate( $value, $alldata ) {
682 if ( isset( $this->mValidationCallback
) ) {
683 return call_user_func( $this->mValidationCallback
, $value, $alldata );
689 function filter( $value, $alldata ) {
690 if( isset( $this->mFilterCallback
) ) {
691 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
698 * Should this field have a label, or is there no input element with the
699 * appropriate id for the label to point to?
701 * @return bool True to output a label, false to suppress
703 protected function needsLabel() {
708 * Get the value that this input has been set to from a posted form,
709 * or the input's default value if it has not been set.
710 * @param $request WebRequest
711 * @return String the value
713 function loadDataFromRequest( $request ) {
714 if( $request->getCheck( $this->mName
) ) {
715 return $request->getText( $this->mName
);
717 return $this->getDefault();
722 * Initialise the object
723 * @param $params Associative Array. See HTMLForm doc for syntax.
725 function __construct( $params ) {
726 $this->mParams
= $params;
728 # Generate the label from a message, if possible
729 if( isset( $params['label-message'] ) ) {
730 $msgInfo = $params['label-message'];
732 if ( is_array( $msgInfo ) ) {
733 $msg = array_shift( $msgInfo );
739 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
740 } elseif ( isset( $params['label'] ) ) {
741 $this->mLabel
= $params['label'];
744 if ( isset( $params['name'] ) ) {
745 $name = $params['name'];
746 $validName = Sanitizer
::escapeId( $name );
747 if( $name != $validName ) {
748 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
750 $this->mName
= 'wp'.$name;
751 $this->mID
= 'mw-input-'.$name;
754 if ( isset( $params['default'] ) ) {
755 $this->mDefault
= $params['default'];
758 if ( isset( $params['id'] ) ) {
760 $validId = Sanitizer
::escapeId( $id );
761 if( $id != $validId ) {
762 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
767 if ( isset( $params['cssclass'] ) ) {
768 $this->mClass
= $params['cssclass'];
771 if ( isset( $params['validation-callback'] ) ) {
772 $this->mValidationCallback
= $params['validation-callback'];
775 if ( isset( $params['filter-callback'] ) ) {
776 $this->mFilterCallback
= $params['filter-callback'];
781 * Get the complete table row for the input, including help text,
782 * labels, and whatever.
783 * @param $value String the value to set the input to.
784 * @return String complete HTML table row.
786 function getTableRow( $value ) {
787 # Check for invalid data.
790 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
791 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
794 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
797 $html = $this->getLabelHtml();
798 $html .= Html
::rawElement(
800 array( 'class' => 'mw-input' ),
801 $this->getInputHTML( $value ) ."\n$errors"
804 $fieldType = get_class( $this );
806 $html = Html
::rawElement(
808 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
813 if ( isset( $this->mParams
['help-message'] ) ) {
814 $msg = $this->mParams
['help-message'];
815 $helptext = wfMsgExt( $msg, 'parseinline' );
816 if ( wfEmptyMsg( $msg, $helptext ) ) {
820 } elseif ( isset( $this->mParams
['help'] ) ) {
821 $helptext = $this->mParams
['help'];
824 if ( !is_null( $helptext ) ) {
825 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
827 $row = Html
::rawElement( 'tr', array(), $row );
834 function getLabel() {
835 return $this->mLabel
;
837 function getLabelHtml() {
838 # Don't output a for= attribute for labels with no associated input.
839 # Kind of hacky here, possibly we don't want these to be <label>s at all.
841 if ( $this->needsLabel() ) {
842 $for['for'] = $this->mID
;
844 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
845 Html
::rawElement( 'label', $for, $this->getLabel() )
849 function getDefault() {
850 if ( isset( $this->mDefault
) ) {
851 return $this->mDefault
;
858 * Returns the attributes required for the tooltip and accesskey.
860 * @return array Attributes
862 public function getTooltipAndAccessKey() {
863 if ( empty( $this->mParams
['tooltip'] ) )
867 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
871 * flatten an array of options to a single array, for instance,
872 * a set of <options> inside <optgroups>.
873 * @param $options Associative Array with values either Strings
875 * @return Array flattened input
877 public static function flattenOptions( $options ) {
880 foreach( $options as $key => $value ) {
881 if ( is_array( $value ) ) {
882 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
884 $flatOpts[] = $value;
893 class HTMLTextField
extends HTMLFormField
{
896 return isset( $this->mParams
['size'] )
897 ?
$this->mParams
['size']
901 function getInputHTML( $value ) {
904 'name' => $this->mName
,
905 'size' => $this->getSize(),
907 ) +
$this->getTooltipAndAccessKey();
909 if ( isset( $this->mParams
['maxlength'] ) ) {
910 $attribs['maxlength'] = $this->mParams
['maxlength'];
913 if ( !empty( $this->mParams
['disabled'] ) ) {
914 $attribs['disabled'] = 'disabled';
917 # TODO: Enforce pattern, step, required, readonly on the server side as
919 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
920 'placeholder' ) as $param ) {
921 if ( isset( $this->mParams
[$param] ) ) {
922 $attribs[$param] = $this->mParams
[$param];
925 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
927 if ( isset( $this->mParams
[$param] ) ) {
928 $attribs[$param] = '';
932 # Implement tiny differences between some field variants
933 # here, rather than creating a new class for each one which
934 # is essentially just a clone of this one.
935 if ( isset( $this->mParams
['type'] ) ) {
936 switch ( $this->mParams
['type'] ) {
938 $attribs['type'] = 'email';
941 $attribs['type'] = 'number';
944 $attribs['type'] = 'number';
945 $attribs['step'] = 'any';
950 $attribs['type'] = $this->mParams
['type'];
955 return Html
::element( 'input', $attribs );
958 public function validate( $value, $alldata ){
959 $p = parent
::validate( $value, $alldata );
960 if( $p !== true ) return $p;
962 if( isset( $this->mParams
['required'] ) && $value === '' ){
963 return wfMsgExt( 'htmlform-required', 'parseinline' );
968 class HTMLTextAreaField
extends HTMLFormField
{
971 return isset( $this->mParams
['cols'] )
972 ?
$this->mParams
['cols']
976 return isset( $this->mParams
['rows'] )
977 ?
$this->mParams
['rows']
981 function getInputHTML( $value ) {
984 'name' => $this->mName
,
985 'cols' => $this->getCols(),
986 'rows' => $this->getRows(),
987 ) +
$this->getTooltipAndAccessKey();
990 if ( !empty( $this->mParams
['disabled'] ) ) {
991 $attribs['disabled'] = 'disabled';
993 if ( !empty( $this->mParams
['readonly'] ) ) {
994 $attribs['readonly'] = 'readonly';
997 foreach ( array( 'required', 'autofocus' ) as $param ) {
998 if ( isset( $this->mParams
[$param] ) ) {
999 $attribs[$param] = '';
1003 return Html
::element( 'textarea', $attribs, $value );
1006 public function validate( $value, $alldata ){
1007 $p = parent
::validate( $value, $alldata );
1008 if( $p !== true ) return $p;
1010 if( isset( $this->mParams
['required'] ) && $value === '' ){
1011 return wfMsgExt( 'htmlform-required', 'parseinline' );
1018 * A field that will contain a numeric value
1020 class HTMLFloatField
extends HTMLTextField
{
1022 function getSize() {
1023 return isset( $this->mParams
['size'] )
1024 ?
$this->mParams
['size']
1028 function validate( $value, $alldata ) {
1029 $p = parent
::validate( $value, $alldata );
1031 if ( $p !== true ) return $p;
1033 if ( floatval( $value ) != $value ) {
1034 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1039 # The "int" part of these message names is rather confusing.
1040 # They make equal sense for all numbers.
1041 if ( isset( $this->mParams
['min'] ) ) {
1042 $min = $this->mParams
['min'];
1043 if ( $min > $value )
1044 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1047 if ( isset( $this->mParams
['max'] ) ) {
1048 $max = $this->mParams
['max'];
1050 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1058 * A field that must contain a number
1060 class HTMLIntField
extends HTMLFloatField
{
1061 function validate( $value, $alldata ) {
1062 $p = parent
::validate( $value, $alldata );
1064 if ( $p !== true ) return $p;
1067 && ( !is_numeric( $value ) ||
round( $value ) != $value ) )
1069 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1079 class HTMLCheckField
extends HTMLFormField
{
1080 function getInputHTML( $value ) {
1081 if ( !empty( $this->mParams
['invert'] ) )
1084 $attr = $this->getTooltipAndAccessKey();
1085 $attr['id'] = $this->mID
;
1086 if( !empty( $this->mParams
['disabled'] ) ) {
1087 $attr['disabled'] = 'disabled';
1090 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1091 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1095 * For a checkbox, the label goes on the right hand side, and is
1096 * added in getInputHTML(), rather than HTMLFormField::getRow()
1098 function getLabel() {
1102 function loadDataFromRequest( $request ) {
1104 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1108 // GetCheck won't work like we want for checks.
1109 if( $request->getCheck( 'wpEditToken' ) ) {
1110 // XOR has the following truth table, which is what we want
1111 // INVERT VALUE | OUTPUT
1112 // true true | false
1113 // false true | true
1114 // false false | false
1115 // true false | true
1116 return $request->getBool( $this->mName
) xor $invert;
1118 return $this->getDefault();
1124 * A select dropdown field. Basically a wrapper for Xmlselect class
1126 class HTMLSelectField
extends HTMLFormField
{
1128 function validate( $value, $alldata ) {
1129 $p = parent
::validate( $value, $alldata );
1130 if( $p !== true ) return $p;
1132 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1133 if ( in_array( $value, $validOptions ) )
1136 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1139 function getInputHTML( $value ) {
1140 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1142 # If one of the options' 'name' is int(0), it is automatically selected.
1143 # because PHP sucks and things int(0) == 'some string'.
1144 # Working around this by forcing all of them to strings.
1145 $options = array_map( 'strval', $this->mParams
['options'] );
1147 if( !empty( $this->mParams
['disabled'] ) ) {
1148 $select->setAttribute( 'disabled', 'disabled' );
1151 $select->addOptions( $options );
1153 return $select->getHTML();
1158 * Select dropdown field, with an additional "other" textbox.
1160 class HTMLSelectOrOtherField
extends HTMLTextField
{
1161 static $jsAdded = false;
1163 function __construct( $params ) {
1164 if( !in_array( 'other', $params['options'], true ) ) {
1165 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1168 parent
::__construct( $params );
1171 static function forceToStringRecursive( $array ) {
1172 if ( is_array($array) ) {
1173 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1175 return strval($array);
1179 function getInputHTML( $value ) {
1180 $valInSelect = false;
1182 if( $value !== false )
1183 $valInSelect = in_array( $value,
1184 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1186 $selected = $valInSelect ?
$value : 'other';
1188 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1190 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1191 $select->addOptions( $opts );
1193 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1195 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1196 if( !empty( $this->mParams
['disabled'] ) ) {
1197 $select->setAttribute( 'disabled', 'disabled' );
1198 $tbAttribs['disabled'] = 'disabled';
1201 $select = $select->getHTML();
1203 if ( isset( $this->mParams
['maxlength'] ) ) {
1204 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1207 $textbox = Html
::input( $this->mName
. '-other',
1208 $valInSelect ?
'' : $value,
1212 return "$select<br />\n$textbox";
1215 function loadDataFromRequest( $request ) {
1216 if( $request->getCheck( $this->mName
) ) {
1217 $val = $request->getText( $this->mName
);
1219 if( $val == 'other' ) {
1220 $val = $request->getText( $this->mName
. '-other' );
1225 return $this->getDefault();
1231 * Multi-select field
1233 class HTMLMultiSelectField
extends HTMLFormField
{
1235 function validate( $value, $alldata ) {
1236 $p = parent
::validate( $value, $alldata );
1237 if( $p !== true ) return $p;
1239 if( !is_array( $value ) ) return false;
1241 # If all options are valid, array_intersect of the valid options
1242 # and the provided options will return the provided options.
1243 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1245 $validValues = array_intersect( $value, $validOptions );
1246 if ( count( $validValues ) == count( $value ) )
1249 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1252 function getInputHTML( $value ) {
1253 $html = $this->formatOptions( $this->mParams
['options'], $value );
1258 function formatOptions( $options, $value ) {
1262 if ( !empty( $this->mParams
['disabled'] ) ) {
1263 $attribs['disabled'] = 'disabled';
1266 foreach( $options as $label => $info ) {
1267 if( is_array( $info ) ) {
1268 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1269 $html .= $this->formatOptions( $info, $value );
1271 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1273 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value, true ),
1274 $attribs +
$thisAttribs );
1275 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1277 $html .= $checkbox . '<br />';
1284 function loadDataFromRequest( $request ) {
1285 # won't work with getCheck
1286 if( $request->getCheck( 'wpEditToken' ) ) {
1287 $arr = $request->getArray( $this->mName
);
1294 return $this->getDefault();
1298 function getDefault() {
1299 if ( isset( $this->mDefault
) ) {
1300 return $this->mDefault
;
1306 protected function needsLabel() {
1312 * Radio checkbox fields.
1314 class HTMLRadioField
extends HTMLFormField
{
1315 function validate( $value, $alldata ) {
1316 $p = parent
::validate( $value, $alldata );
1317 if( $p !== true ) return $p;
1319 if( !is_string( $value ) && !is_int( $value ) )
1322 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1324 if ( in_array( $value, $validOptions ) )
1327 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1331 * This returns a block of all the radio options, in one cell.
1332 * @see includes/HTMLFormField#getInputHTML()
1334 function getInputHTML( $value ) {
1335 $html = $this->formatOptions( $this->mParams
['options'], $value );
1340 function formatOptions( $options, $value ) {
1344 if ( !empty( $this->mParams
['disabled'] ) ) {
1345 $attribs['disabled'] = 'disabled';
1348 # TODO: should this produce an unordered list perhaps?
1349 foreach( $options as $label => $info ) {
1350 if( is_array( $info ) ) {
1351 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1352 $html .= $this->formatOptions( $info, $value );
1354 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1355 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1356 $attribs +
array( 'id' => $id ) );
1358 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1360 $html .= "<br />\n";
1367 protected function needsLabel() {
1373 * An information field (text blob), not a proper input.
1375 class HTMLInfoField
extends HTMLFormField
{
1376 function __construct( $info ) {
1377 $info['nodata'] = true;
1379 parent
::__construct( $info );
1382 function getInputHTML( $value ) {
1383 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1386 function getTableRow( $value ) {
1387 if ( !empty( $this->mParams
['rawrow'] ) ) {
1391 return parent
::getTableRow( $value );
1394 protected function needsLabel() {
1399 class HTMLHiddenField
extends HTMLFormField
{
1401 public function __construct( $params ){
1402 parent
::__construct( $params );
1403 # forcing the 'wp' prefix on hidden field names
1405 $this->mName
= substr( $this->mName
, 2 );
1408 public function getTableRow( $value ){
1411 $params['id'] = $this->mID
;
1413 $this->mParent
->addHiddenField(
1421 public function getInputHTML( $value ){ return ''; }
1425 * Add a submit button inline in the form (as opposed to
1426 * HTMLForm::addButton(), which will add it at the end).
1428 class HTMLSubmitField
extends HTMLFormField
{
1430 function __construct( $info ) {
1431 $info['nodata'] = true;
1432 parent
::__construct( $info );
1435 function getInputHTML( $value ) {
1436 return Xml
::submitButton(
1439 'class' => 'mw-htmlform-submit',
1440 'name' => $this->mName
,
1446 protected function needsLabel() {
1451 class HTMLEditTools
extends HTMLFormField
{
1452 public function getInputHTML( $value ) {
1455 public function getTableRow( $value ) {
1456 return "<tr><td></td><td class=\"mw-input\">"
1457 . '<div class="mw-editTools">'
1458 . wfMsgExt( empty( $this->mParams
['message'] )
1459 ?
'edittools' : $this->mParams
['message'],
1460 array( 'parse', 'content' ) )
1461 . "</div></td></tr>\n";