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.
194 // Check if we have the info we need
195 if ( ! $this->mTitle
) {
196 throw new MWException( "You must call setTitle() on an HTMLForm" );
201 # Load data from the request.
205 global $wgUser, $wgRequest;
206 $editToken = $wgRequest->getVal( 'wpEditToken' );
209 if ( $wgUser->matchEditToken( $editToken ) )
210 $result = $this->trySubmit();
212 if( $result === true )
216 $this->displayForm( $result );
221 * Validate all the fields, and call the submision callback
222 * function if everything is kosher.
223 * @return Mixed Bool true == Successful submission, Bool false
224 * == No submission attempted, anything else == Error to
227 function trySubmit() {
228 # Check for validation
229 foreach( $this->mFlatFields
as $fieldname => $field ) {
230 if ( !empty( $field->mParams
['nodata'] ) ){
233 if ( $field->validate(
234 $this->mFieldData
[$fieldname],
238 return isset( $this->mValidationErrorMessage
)
239 ?
$this->mValidationErrorMessage
240 : array( 'htmlform-invalid-input' );
244 $callback = $this->mSubmitCallback
;
246 $data = $this->filterDataForSubmit( $this->mFieldData
);
248 $res = call_user_func( $callback, $data );
254 * Set a callback to a function to do something with the form
255 * once it's been successfully validated.
256 * @param $cb String function name. The function will be passed
257 * the output from HTMLForm::filterDataForSubmit, and must
258 * return Bool true on success, Bool false if no submission
259 * was attempted, or String HTML output to display on error.
261 function setSubmitCallback( $cb ) {
262 $this->mSubmitCallback
= $cb;
266 * Set a message to display on a validation error.
267 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
268 * (so each entry can be either a String or Array)
270 function setValidationErrorMessage( $msg ) {
271 $this->mValidationErrorMessage
= $msg;
275 * Set the introductory message, overwriting any existing message.
276 * @param $msg String complete text of message to display
278 function setIntro( $msg ) { $this->mPre
= $msg; }
281 * Add introductory text.
282 * @param $msg String complete text of message to display
284 function addPreText( $msg ) { $this->mPre
.= $msg; }
287 * Add header text, inside the form.
288 * @param $msg String complete text of message to display
290 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
293 * Add footer text, inside the form.
294 * @param $msg String complete text of message to display
296 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
299 * Add text to the end of the display.
300 * @param $msg String complete text of message to display
302 function addPostText( $msg ) { $this->mPost
.= $msg; }
305 * Add a hidden field to the output
306 * @param $name String field name
307 * @param $value String field value
308 * @param $attribs Array
310 public function addHiddenField( $name, $value, $attribs=array() ){
311 $attribs +
= array( 'name' => $name );
312 $this->mHiddenFields
[] = array( $value, $attribs );
315 public function addButton( $name, $value, $id=null, $attribs=null ){
316 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
320 * Display the form (sending to wgOut), with an appropriate error
321 * message or stack of messages, and any validation errors, etc.
322 * @param $submitResult Mixed output from HTMLForm::trySubmit()
324 function displayForm( $submitResult ) {
328 . $this->getErrors( $submitResult )
331 . $this->getHiddenFields()
332 . $this->getButtons()
336 $html = $this->wrapForm( $html );
346 * Wrap the form innards in an actual <form> element
347 * @param $html String HTML contents to wrap.
348 * @return String wrapped HTML.
350 function wrapForm( $html ) {
352 # Include a <fieldset> wrapper for style, if requested.
353 if ( $this->mWrapperLegend
!== false ){
354 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
356 # Use multipart/form-data
357 $encType = $this->mUseMultipart
358 ?
'multipart/form-data'
359 : 'application/x-www-form-urlencoded';
362 'action' => $this->getTitle()->getFullURL(),
364 'class' => 'visualClear',
365 'enctype' => $encType,
367 if ( !empty( $this->mId
) )
368 $attribs['id'] = $this->mId
;
370 return Html
::rawElement( 'form', $attribs, $html );
374 * Get the hidden fields that should go inside the form.
375 * @return String HTML.
377 function getHiddenFields() {
381 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
382 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
384 foreach( $this->mHiddenFields
as $data ){
385 list( $value, $attribs ) = $data;
386 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
393 * Get the submit and (potentially) reset buttons.
394 * @return String HTML.
396 function getButtons() {
401 if ( isset( $this->mSubmitID
) )
402 $attribs['id'] = $this->mSubmitID
;
403 if ( isset( $this->mSubmitName
) )
404 $attribs['name'] = $this->mSubmitName
;
405 if ( isset( $this->mSubmitTooltip
) ) {
407 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
410 $attribs['class'] = 'mw-htmlform-submit';
412 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
414 if( $this->mShowReset
) {
415 $html .= Html
::element(
419 'value' => wfMsg( 'htmlform-reset' )
424 foreach( $this->mButtons
as $button ){
427 'name' => $button['name'],
428 'value' => $button['value']
430 if ( $button['attribs'] )
431 $attrs +
= $button['attribs'];
432 if( isset( $button['id'] ) )
433 $attrs['id'] = $button['id'];
434 $html .= Html
::element( 'input', $attrs );
441 * Get the whole body of the form.
444 return $this->displaySection( $this->mFieldTree
);
448 * Format and display an error message stack.
449 * @param $errors Mixed String or Array of message keys
452 function getErrors( $errors ) {
453 if ( is_array( $errors ) ) {
454 $errorstr = $this->formatErrors( $errors );
460 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
465 * Format a stack of error messages into a single HTML string
466 * @param $errors Array of message keys/values
467 * @return String HTML, a <ul> list of errors
469 static function formatErrors( $errors ) {
471 foreach ( $errors as $error ) {
472 if( is_array( $error ) ) {
473 $msg = array_shift( $error );
478 $errorstr .= Html
::rawElement(
481 wfMsgExt( $msg, array( 'parseinline' ), $error )
485 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
491 * Set the text for the submit button
492 * @param $t String plaintext.
494 function setSubmitText( $t ) {
495 $this->mSubmitText
= $t;
499 * Get the text for the submit button, either customised or a default.
500 * @return unknown_type
502 function getSubmitText() {
503 return $this->mSubmitText
505 : wfMsg( 'htmlform-submit' );
508 public function setSubmitName( $name ) {
509 $this->mSubmitName
= $name;
512 public function setSubmitTooltip( $name ) {
513 $this->mSubmitTooltip
= $name;
518 * Set the id for the submit button.
519 * @param $t String. FIXME: Integrity is *not* validated
521 function setSubmitID( $t ) {
522 $this->mSubmitID
= $t;
525 public function setId( $id ) {
529 * Prompt the whole form to be wrapped in a <fieldset>, with
530 * this text as its <legend> element.
531 * @param $legend String HTML to go inside the <legend> element.
534 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
537 * Set the prefix for various default messages
538 * TODO: currently only used for the <fieldset> legend on forms
539 * with multiple sections; should be used elsewhre?
542 function setMessagePrefix( $p ) {
543 $this->mMessagePrefix
= $p;
547 * Set the title for form submission
548 * @param $t Title of page the form is on/should be posted to
550 function setTitle( $t ) {
558 function getTitle() {
559 return $this->mTitle
;
566 function displaySection( $fields, $sectionName = '' ) {
568 $subsectionHtml = '';
569 $hasLeftColumn = false;
571 foreach( $fields as $key => $value ) {
572 if ( is_object( $value ) ) {
573 $v = empty( $value->mParams
['nodata'] )
574 ?
$this->mFieldData
[$key]
575 : $value->getDefault();
576 $tableHtml .= $value->getTableRow( $v );
578 if( $value->getLabel() != ' ' )
579 $hasLeftColumn = true;
580 } elseif ( is_array( $value ) ) {
581 $section = $this->displaySection( $value, $key );
582 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
583 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
588 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
589 $classes[] = 'mw-htmlform-nolabel';
591 'class' => implode( ' ', $classes ),
594 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
596 $tableHtml = Html
::rawElement( 'table', $attribs,
597 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
599 return $subsectionHtml . "\n" . $tableHtml;
603 * Construct the form fields from the Descriptor array
605 function loadData() {
608 $fieldData = array();
610 foreach( $this->mFlatFields
as $fieldname => $field ) {
611 if ( !empty( $field->mParams
['nodata'] ) ){
613 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
614 $fieldData[$fieldname] = $field->getDefault();
616 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
621 foreach( $fieldData as $name => &$value ) {
622 $field = $this->mFlatFields
[$name];
623 $value = $field->filter( $value, $this->mFlatFields
);
626 $this->mFieldData
= $fieldData;
630 * Stop a reset button being shown for this form
631 * @param $suppressReset Bool set to false to re-enable the
634 function suppressReset( $suppressReset = true ) {
635 $this->mShowReset
= !$suppressReset;
639 * Overload this if you want to apply special filtration routines
640 * to the form as a whole, after it's submitted but before it's
643 * @return unknown_type
645 function filterDataForSubmit( $data ) {
651 * The parent class to generate form fields. Any field type should
652 * be a subclass of this.
654 abstract class HTMLFormField
{
656 protected $mValidationCallback;
657 protected $mFilterCallback;
660 protected $mLabel; # String label. Set on construction
662 protected $mClass = '';
667 * This function must be implemented to return the HTML to generate
668 * the input object itself. It should not implement the surrounding
669 * table cells/rows, or labels/help messages.
670 * @param $value String the value to set the input to; eg a default
671 * text for a text input.
672 * @return String valid HTML.
674 abstract function getInputHTML( $value );
677 * Override this function to add specific validation checks on the
678 * field input. Don't forget to call parent::validate() to ensure
679 * that the user-defined callback mValidationCallback is still run
680 * @param $value String the value the field was submitted with
681 * @param $alldata Array the data collected from the form
682 * @return Mixed Bool true on success, or String error to display.
684 function validate( $value, $alldata ) {
685 if ( isset( $this->mValidationCallback
) ) {
686 return call_user_func( $this->mValidationCallback
, $value, $alldata );
692 function filter( $value, $alldata ) {
693 if( isset( $this->mFilterCallback
) ) {
694 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
701 * Should this field have a label, or is there no input element with the
702 * appropriate id for the label to point to?
704 * @return bool True to output a label, false to suppress
706 protected function needsLabel() {
711 * Get the value that this input has been set to from a posted form,
712 * or the input's default value if it has not been set.
713 * @param $request WebRequest
714 * @return String the value
716 function loadDataFromRequest( $request ) {
717 if( $request->getCheck( $this->mName
) ) {
718 return $request->getText( $this->mName
);
720 return $this->getDefault();
725 * Initialise the object
726 * @param $params Associative Array. See HTMLForm doc for syntax.
728 function __construct( $params ) {
729 $this->mParams
= $params;
731 # Generate the label from a message, if possible
732 if( isset( $params['label-message'] ) ) {
733 $msgInfo = $params['label-message'];
735 if ( is_array( $msgInfo ) ) {
736 $msg = array_shift( $msgInfo );
742 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
743 } elseif ( isset( $params['label'] ) ) {
744 $this->mLabel
= $params['label'];
747 if ( isset( $params['name'] ) ) {
748 $name = $params['name'];
749 $validName = Sanitizer
::escapeId( $name );
750 if( $name != $validName ) {
751 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
753 $this->mName
= 'wp'.$name;
754 $this->mID
= 'mw-input-'.$name;
757 if ( isset( $params['default'] ) ) {
758 $this->mDefault
= $params['default'];
761 if ( isset( $params['id'] ) ) {
763 $validId = Sanitizer
::escapeId( $id );
764 if( $id != $validId ) {
765 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
770 if ( isset( $params['cssclass'] ) ) {
771 $this->mClass
= $params['cssclass'];
774 if ( isset( $params['validation-callback'] ) ) {
775 $this->mValidationCallback
= $params['validation-callback'];
778 if ( isset( $params['filter-callback'] ) ) {
779 $this->mFilterCallback
= $params['filter-callback'];
784 * Get the complete table row for the input, including help text,
785 * labels, and whatever.
786 * @param $value String the value to set the input to.
787 * @return String complete HTML table row.
789 function getTableRow( $value ) {
790 # Check for invalid data.
793 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
794 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
797 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
800 $html = $this->getLabelHtml();
801 $html .= Html
::rawElement(
803 array( 'class' => 'mw-input' ),
804 $this->getInputHTML( $value ) ."\n$errors"
807 $fieldType = get_class( $this );
809 $html = Html
::rawElement(
811 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
816 if ( isset( $this->mParams
['help-message'] ) ) {
817 $msg = $this->mParams
['help-message'];
818 $helptext = wfMsgExt( $msg, 'parseinline' );
819 if ( wfEmptyMsg( $msg, $helptext ) ) {
823 } elseif ( isset( $this->mParams
['help'] ) ) {
824 $helptext = $this->mParams
['help'];
827 if ( !is_null( $helptext ) ) {
828 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
830 $row = Html
::rawElement( 'tr', array(), $row );
837 function getLabel() {
838 return $this->mLabel
;
840 function getLabelHtml() {
841 # Don't output a for= attribute for labels with no associated input.
842 # Kind of hacky here, possibly we don't want these to be <label>s at all.
844 if ( $this->needsLabel() ) {
845 $for['for'] = $this->mID
;
847 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
848 Html
::rawElement( 'label', $for, $this->getLabel() )
852 function getDefault() {
853 if ( isset( $this->mDefault
) ) {
854 return $this->mDefault
;
861 * Returns the attributes required for the tooltip and accesskey.
863 * @return array Attributes
865 public function getTooltipAndAccessKey() {
866 if ( empty( $this->mParams
['tooltip'] ) )
870 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
874 * flatten an array of options to a single array, for instance,
875 * a set of <options> inside <optgroups>.
876 * @param $options Associative Array with values either Strings
878 * @return Array flattened input
880 public static function flattenOptions( $options ) {
883 foreach( $options as $key => $value ) {
884 if ( is_array( $value ) ) {
885 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
887 $flatOpts[] = $value;
896 class HTMLTextField
extends HTMLFormField
{
899 return isset( $this->mParams
['size'] )
900 ?
$this->mParams
['size']
904 function getInputHTML( $value ) {
907 'name' => $this->mName
,
908 'size' => $this->getSize(),
910 ) +
$this->getTooltipAndAccessKey();
912 if ( isset( $this->mParams
['maxlength'] ) ) {
913 $attribs['maxlength'] = $this->mParams
['maxlength'];
916 if ( !empty( $this->mParams
['disabled'] ) ) {
917 $attribs['disabled'] = 'disabled';
920 # TODO: Enforce pattern, step, required, readonly on the server side as
922 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
923 'placeholder' ) as $param ) {
924 if ( isset( $this->mParams
[$param] ) ) {
925 $attribs[$param] = $this->mParams
[$param];
928 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
930 if ( isset( $this->mParams
[$param] ) ) {
931 $attribs[$param] = '';
935 # Implement tiny differences between some field variants
936 # here, rather than creating a new class for each one which
937 # is essentially just a clone of this one.
938 if ( isset( $this->mParams
['type'] ) ) {
939 switch ( $this->mParams
['type'] ) {
941 $attribs['type'] = 'email';
944 $attribs['type'] = 'number';
947 $attribs['type'] = 'number';
948 $attribs['step'] = 'any';
953 $attribs['type'] = $this->mParams
['type'];
958 return Html
::element( 'input', $attribs );
961 public function validate( $value, $alldata ){
962 $p = parent
::validate( $value, $alldata );
963 if( $p !== true ) return $p;
965 if( isset( $this->mParams
['required'] ) && $value === '' ){
966 return wfMsgExt( 'htmlform-required', 'parseinline' );
971 class HTMLTextAreaField
extends HTMLFormField
{
974 return isset( $this->mParams
['cols'] )
975 ?
$this->mParams
['cols']
979 return isset( $this->mParams
['rows'] )
980 ?
$this->mParams
['rows']
984 function getInputHTML( $value ) {
987 'name' => $this->mName
,
988 'cols' => $this->getCols(),
989 'rows' => $this->getRows(),
990 ) +
$this->getTooltipAndAccessKey();
993 if ( !empty( $this->mParams
['disabled'] ) ) {
994 $attribs['disabled'] = 'disabled';
996 if ( !empty( $this->mParams
['readonly'] ) ) {
997 $attribs['readonly'] = 'readonly';
1000 foreach ( array( 'required', 'autofocus' ) as $param ) {
1001 if ( isset( $this->mParams
[$param] ) ) {
1002 $attribs[$param] = '';
1006 return Html
::element( 'textarea', $attribs, $value );
1009 public function validate( $value, $alldata ){
1010 $p = parent
::validate( $value, $alldata );
1011 if( $p !== true ) return $p;
1013 if( isset( $this->mParams
['required'] ) && $value === '' ){
1014 return wfMsgExt( 'htmlform-required', 'parseinline' );
1021 * A field that will contain a numeric value
1023 class HTMLFloatField
extends HTMLTextField
{
1025 function getSize() {
1026 return isset( $this->mParams
['size'] )
1027 ?
$this->mParams
['size']
1031 function validate( $value, $alldata ) {
1032 $p = parent
::validate( $value, $alldata );
1034 if ( $p !== true ) return $p;
1036 if ( floatval( $value ) != $value ) {
1037 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1042 # The "int" part of these message names is rather confusing.
1043 # They make equal sense for all numbers.
1044 if ( isset( $this->mParams
['min'] ) ) {
1045 $min = $this->mParams
['min'];
1046 if ( $min > $value )
1047 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1050 if ( isset( $this->mParams
['max'] ) ) {
1051 $max = $this->mParams
['max'];
1053 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1061 * A field that must contain a number
1063 class HTMLIntField
extends HTMLFloatField
{
1064 function validate( $value, $alldata ) {
1065 $p = parent
::validate( $value, $alldata );
1067 if ( $p !== true ) return $p;
1070 && ( !is_numeric( $value ) ||
round( $value ) != $value ) )
1072 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1082 class HTMLCheckField
extends HTMLFormField
{
1083 function getInputHTML( $value ) {
1084 if ( !empty( $this->mParams
['invert'] ) )
1087 $attr = $this->getTooltipAndAccessKey();
1088 $attr['id'] = $this->mID
;
1089 if( !empty( $this->mParams
['disabled'] ) ) {
1090 $attr['disabled'] = 'disabled';
1093 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1094 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1098 * For a checkbox, the label goes on the right hand side, and is
1099 * added in getInputHTML(), rather than HTMLFormField::getRow()
1101 function getLabel() {
1105 function loadDataFromRequest( $request ) {
1107 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1111 // GetCheck won't work like we want for checks.
1112 if( $request->getCheck( 'wpEditToken' ) ) {
1113 // XOR has the following truth table, which is what we want
1114 // INVERT VALUE | OUTPUT
1115 // true true | false
1116 // false true | true
1117 // false false | false
1118 // true false | true
1119 return $request->getBool( $this->mName
) xor $invert;
1121 return $this->getDefault();
1127 * A select dropdown field. Basically a wrapper for Xmlselect class
1129 class HTMLSelectField
extends HTMLFormField
{
1131 function validate( $value, $alldata ) {
1132 $p = parent
::validate( $value, $alldata );
1133 if( $p !== true ) return $p;
1135 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1136 if ( in_array( $value, $validOptions ) )
1139 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1142 function getInputHTML( $value ) {
1143 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1145 # If one of the options' 'name' is int(0), it is automatically selected.
1146 # because PHP sucks and things int(0) == 'some string'.
1147 # Working around this by forcing all of them to strings.
1148 $options = array_map( 'strval', $this->mParams
['options'] );
1150 if( !empty( $this->mParams
['disabled'] ) ) {
1151 $select->setAttribute( 'disabled', 'disabled' );
1154 $select->addOptions( $options );
1156 return $select->getHTML();
1161 * Select dropdown field, with an additional "other" textbox.
1163 class HTMLSelectOrOtherField
extends HTMLTextField
{
1164 static $jsAdded = false;
1166 function __construct( $params ) {
1167 if( !in_array( 'other', $params['options'], true ) ) {
1168 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1171 parent
::__construct( $params );
1174 static function forceToStringRecursive( $array ) {
1175 if ( is_array($array) ) {
1176 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1178 return strval($array);
1182 function getInputHTML( $value ) {
1183 $valInSelect = false;
1185 if( $value !== false )
1186 $valInSelect = in_array( $value,
1187 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1189 $selected = $valInSelect ?
$value : 'other';
1191 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1193 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1194 $select->addOptions( $opts );
1196 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1198 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1199 if( !empty( $this->mParams
['disabled'] ) ) {
1200 $select->setAttribute( 'disabled', 'disabled' );
1201 $tbAttribs['disabled'] = 'disabled';
1204 $select = $select->getHTML();
1206 if ( isset( $this->mParams
['maxlength'] ) ) {
1207 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1210 $textbox = Html
::input( $this->mName
. '-other',
1211 $valInSelect ?
'' : $value,
1215 return "$select<br />\n$textbox";
1218 function loadDataFromRequest( $request ) {
1219 if( $request->getCheck( $this->mName
) ) {
1220 $val = $request->getText( $this->mName
);
1222 if( $val == 'other' ) {
1223 $val = $request->getText( $this->mName
. '-other' );
1228 return $this->getDefault();
1234 * Multi-select field
1236 class HTMLMultiSelectField
extends HTMLFormField
{
1238 function validate( $value, $alldata ) {
1239 $p = parent
::validate( $value, $alldata );
1240 if( $p !== true ) return $p;
1242 if( !is_array( $value ) ) return false;
1244 # If all options are valid, array_intersect of the valid options
1245 # and the provided options will return the provided options.
1246 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1248 $validValues = array_intersect( $value, $validOptions );
1249 if ( count( $validValues ) == count( $value ) )
1252 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1255 function getInputHTML( $value ) {
1256 $html = $this->formatOptions( $this->mParams
['options'], $value );
1261 function formatOptions( $options, $value ) {
1265 if ( !empty( $this->mParams
['disabled'] ) ) {
1266 $attribs['disabled'] = 'disabled';
1269 foreach( $options as $label => $info ) {
1270 if( is_array( $info ) ) {
1271 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1272 $html .= $this->formatOptions( $info, $value );
1274 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1276 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value, true ),
1277 $attribs +
$thisAttribs );
1278 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1280 $html .= $checkbox . '<br />';
1287 function loadDataFromRequest( $request ) {
1288 # won't work with getCheck
1289 if( $request->getCheck( 'wpEditToken' ) ) {
1290 $arr = $request->getArray( $this->mName
);
1297 return $this->getDefault();
1301 function getDefault() {
1302 if ( isset( $this->mDefault
) ) {
1303 return $this->mDefault
;
1309 protected function needsLabel() {
1315 * Radio checkbox fields.
1317 class HTMLRadioField
extends HTMLFormField
{
1318 function validate( $value, $alldata ) {
1319 $p = parent
::validate( $value, $alldata );
1320 if( $p !== true ) return $p;
1322 if( !is_string( $value ) && !is_int( $value ) )
1325 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1327 if ( in_array( $value, $validOptions ) )
1330 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1334 * This returns a block of all the radio options, in one cell.
1335 * @see includes/HTMLFormField#getInputHTML()
1337 function getInputHTML( $value ) {
1338 $html = $this->formatOptions( $this->mParams
['options'], $value );
1343 function formatOptions( $options, $value ) {
1347 if ( !empty( $this->mParams
['disabled'] ) ) {
1348 $attribs['disabled'] = 'disabled';
1351 # TODO: should this produce an unordered list perhaps?
1352 foreach( $options as $label => $info ) {
1353 if( is_array( $info ) ) {
1354 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1355 $html .= $this->formatOptions( $info, $value );
1357 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1358 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1359 $attribs +
array( 'id' => $id ) );
1361 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1363 $html .= "<br />\n";
1370 protected function needsLabel() {
1376 * An information field (text blob), not a proper input.
1378 class HTMLInfoField
extends HTMLFormField
{
1379 function __construct( $info ) {
1380 $info['nodata'] = true;
1382 parent
::__construct( $info );
1385 function getInputHTML( $value ) {
1386 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1389 function getTableRow( $value ) {
1390 if ( !empty( $this->mParams
['rawrow'] ) ) {
1394 return parent
::getTableRow( $value );
1397 protected function needsLabel() {
1402 class HTMLHiddenField
extends HTMLFormField
{
1404 public function __construct( $params ){
1405 parent
::__construct( $params );
1406 # forcing the 'wp' prefix on hidden field names
1408 $this->mName
= substr( $this->mName
, 2 );
1411 public function getTableRow( $value ){
1414 $params['id'] = $this->mID
;
1416 $this->mParent
->addHiddenField(
1424 public function getInputHTML( $value ){ return ''; }
1428 * Add a submit button inline in the form (as opposed to
1429 * HTMLForm::addButton(), which will add it at the end).
1431 class HTMLSubmitField
extends HTMLFormField
{
1433 function __construct( $info ) {
1434 $info['nodata'] = true;
1435 parent
::__construct( $info );
1438 function getInputHTML( $value ) {
1439 return Xml
::submitButton(
1442 'class' => 'mw-htmlform-submit',
1443 'name' => $this->mName
,
1449 protected function needsLabel() {
1454 class HTMLEditTools
extends HTMLFormField
{
1455 public function getInputHTML( $value ) {
1458 public function getTableRow( $value ) {
1459 return "<tr><td></td><td class=\"mw-input\">"
1460 . '<div class="mw-editTools">'
1461 . wfMsgExt( empty( $this->mParams
['message'] )
1462 ?
'edittools' : $this->mParams
['message'],
1463 array( 'parse', 'content' ) )
1464 . "</div></td></tr>\n";