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" );
203 # Load data from the request.
207 global $wgUser, $wgRequest;
208 $editToken = $wgRequest->getVal( 'wpEditToken' );
211 if ( $wgUser->matchEditToken( $editToken ) )
212 $result = $this->trySubmit();
214 if( $result === true )
218 $this->displayForm( $result );
223 * Validate all the fields, and call the submision callback
224 * function if everything is kosher.
225 * @return Mixed Bool true == Successful submission, Bool false
226 * == No submission attempted, anything else == Error to
229 function trySubmit() {
230 # Check for validation
231 foreach( $this->mFlatFields
as $fieldname => $field ) {
232 if ( !empty( $field->mParams
['nodata'] ) ){
235 if ( $field->validate(
236 $this->mFieldData
[$fieldname],
240 return isset( $this->mValidationErrorMessage
)
241 ?
$this->mValidationErrorMessage
242 : array( 'htmlform-invalid-input' );
246 $callback = $this->mSubmitCallback
;
248 $data = $this->filterDataForSubmit( $this->mFieldData
);
250 $res = call_user_func( $callback, $data );
256 * Set a callback to a function to do something with the form
257 * once it's been successfully validated.
258 * @param $cb String function name. The function will be passed
259 * the output from HTMLForm::filterDataForSubmit, and must
260 * return Bool true on success, Bool false if no submission
261 * was attempted, or String HTML output to display on error.
263 function setSubmitCallback( $cb ) {
264 $this->mSubmitCallback
= $cb;
268 * Set a message to display on a validation error.
269 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
270 * (so each entry can be either a String or Array)
272 function setValidationErrorMessage( $msg ) {
273 $this->mValidationErrorMessage
= $msg;
277 * Set the introductory message, overwriting any existing message.
278 * @param $msg String complete text of message to display
280 function setIntro( $msg ) { $this->mPre
= $msg; }
283 * Add introductory text.
284 * @param $msg String complete text of message to display
286 function addPreText( $msg ) { $this->mPre
.= $msg; }
289 * Add header text, inside the form.
290 * @param $msg String complete text of message to display
292 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
295 * Add footer text, inside the form.
296 * @param $msg String complete text of message to display
298 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
301 * Add text to the end of the display.
302 * @param $msg String complete text of message to display
304 function addPostText( $msg ) { $this->mPost
.= $msg; }
307 * Add a hidden field to the output
308 * @param $name String field name
309 * @param $value String field value
310 * @param $attribs Array
312 public function addHiddenField( $name, $value, $attribs=array() ){
313 $attribs +
= array( 'name' => $name );
314 $this->mHiddenFields
[] = array( $value, $attribs );
317 public function addButton( $name, $value, $id=null, $attribs=null ){
318 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
322 * Display the form (sending to wgOut), with an appropriate error
323 * message or stack of messages, and any validation errors, etc.
324 * @param $submitResult Mixed output from HTMLForm::trySubmit()
326 function displayForm( $submitResult ) {
330 . $this->getErrors( $submitResult )
333 . $this->getHiddenFields()
334 . $this->getButtons()
338 $html = $this->wrapForm( $html );
348 * Wrap the form innards in an actual <form> element
349 * @param $html String HTML contents to wrap.
350 * @return String wrapped HTML.
352 function wrapForm( $html ) {
354 # Include a <fieldset> wrapper for style, if requested.
355 if ( $this->mWrapperLegend
!== false ){
356 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
358 # Use multipart/form-data
359 $encType = $this->mUseMultipart
360 ?
'multipart/form-data'
361 : 'application/x-www-form-urlencoded';
364 'action' => $this->getTitle()->getFullURL(),
366 'class' => 'visualClear',
367 'enctype' => $encType,
369 if ( !empty( $this->mId
) )
370 $attribs['id'] = $this->mId
;
372 return Html
::rawElement( 'form', $attribs, $html );
376 * Get the hidden fields that should go inside the form.
377 * @return String HTML.
379 function getHiddenFields() {
383 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
384 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
386 foreach( $this->mHiddenFields
as $data ){
387 list( $value, $attribs ) = $data;
388 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
395 * Get the submit and (potentially) reset buttons.
396 * @return String HTML.
398 function getButtons() {
403 if ( isset( $this->mSubmitID
) )
404 $attribs['id'] = $this->mSubmitID
;
405 if ( isset( $this->mSubmitName
) )
406 $attribs['name'] = $this->mSubmitName
;
407 if ( isset( $this->mSubmitTooltip
) ) {
409 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
412 $attribs['class'] = 'mw-htmlform-submit';
414 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
416 if( $this->mShowReset
) {
417 $html .= Html
::element(
421 'value' => wfMsg( 'htmlform-reset' )
426 foreach( $this->mButtons
as $button ){
429 'name' => $button['name'],
430 'value' => $button['value']
432 if ( $button['attribs'] )
433 $attrs +
= $button['attribs'];
434 if( isset( $button['id'] ) )
435 $attrs['id'] = $button['id'];
436 $html .= Html
::element( 'input', $attrs );
443 * Get the whole body of the form.
446 return $this->displaySection( $this->mFieldTree
);
450 * Format and display an error message stack.
451 * @param $errors Mixed String or Array of message keys
454 function getErrors( $errors ) {
455 if ( is_array( $errors ) ) {
456 $errorstr = $this->formatErrors( $errors );
462 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
467 * Format a stack of error messages into a single HTML string
468 * @param $errors Array of message keys/values
469 * @return String HTML, a <ul> list of errors
471 static function formatErrors( $errors ) {
473 foreach ( $errors as $error ) {
474 if( is_array( $error ) ) {
475 $msg = array_shift( $error );
480 $errorstr .= Html
::rawElement(
483 wfMsgExt( $msg, array( 'parseinline' ), $error )
487 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
493 * Set the text for the submit button
494 * @param $t String plaintext.
496 function setSubmitText( $t ) {
497 $this->mSubmitText
= $t;
501 * Get the text for the submit button, either customised or a default.
502 * @return unknown_type
504 function getSubmitText() {
505 return $this->mSubmitText
507 : wfMsg( 'htmlform-submit' );
510 public function setSubmitName( $name ) {
511 $this->mSubmitName
= $name;
514 public function setSubmitTooltip( $name ) {
515 $this->mSubmitTooltip
= $name;
520 * Set the id for the submit button.
521 * @param $t String. FIXME: Integrity is *not* validated
523 function setSubmitID( $t ) {
524 $this->mSubmitID
= $t;
527 public function setId( $id ) {
531 * Prompt the whole form to be wrapped in a <fieldset>, with
532 * this text as its <legend> element.
533 * @param $legend String HTML to go inside the <legend> element.
536 public function setWrapperLegend( $legend ){ $this->mWrapperLegend
= $legend; }
539 * Set the prefix for various default messages
540 * TODO: currently only used for the <fieldset> legend on forms
541 * with multiple sections; should be used elsewhre?
544 function setMessagePrefix( $p ) {
545 $this->mMessagePrefix
= $p;
549 * Set the title for form submission
550 * @param $t Title of page the form is on/should be posted to
552 function setTitle( $t ) {
560 function getTitle() {
561 return $this->mTitle
;
568 function displaySection( $fields, $sectionName = '' ) {
570 $subsectionHtml = '';
571 $hasLeftColumn = false;
573 foreach( $fields as $key => $value ) {
574 if ( is_object( $value ) ) {
575 $v = empty( $value->mParams
['nodata'] )
576 ?
$this->mFieldData
[$key]
577 : $value->getDefault();
578 $tableHtml .= $value->getTableRow( $v );
580 if( $value->getLabel() != ' ' )
581 $hasLeftColumn = true;
582 } elseif ( is_array( $value ) ) {
583 $section = $this->displaySection( $value, $key );
584 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
585 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
590 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
591 $classes[] = 'mw-htmlform-nolabel';
593 'class' => implode( ' ', $classes ),
596 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
598 $tableHtml = Html
::rawElement( 'table', $attribs,
599 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
601 return $subsectionHtml . "\n" . $tableHtml;
605 * Construct the form fields from the Descriptor array
607 function loadData() {
610 $fieldData = array();
612 foreach( $this->mFlatFields
as $fieldname => $field ) {
613 if ( !empty( $field->mParams
['nodata'] ) ){
615 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
616 $fieldData[$fieldname] = $field->getDefault();
618 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
623 foreach( $fieldData as $name => &$value ) {
624 $field = $this->mFlatFields
[$name];
625 $value = $field->filter( $value, $this->mFlatFields
);
628 $this->mFieldData
= $fieldData;
632 * Stop a reset button being shown for this form
633 * @param $suppressReset Bool set to false to re-enable the
636 function suppressReset( $suppressReset = true ) {
637 $this->mShowReset
= !$suppressReset;
641 * Overload this if you want to apply special filtration routines
642 * to the form as a whole, after it's submitted but before it's
645 * @return unknown_type
647 function filterDataForSubmit( $data ) {
653 * The parent class to generate form fields. Any field type should
654 * be a subclass of this.
656 abstract class HTMLFormField
{
658 protected $mValidationCallback;
659 protected $mFilterCallback;
662 protected $mLabel; # String label. Set on construction
664 protected $mClass = '';
669 * This function must be implemented to return the HTML to generate
670 * the input object itself. It should not implement the surrounding
671 * table cells/rows, or labels/help messages.
672 * @param $value String the value to set the input to; eg a default
673 * text for a text input.
674 * @return String valid HTML.
676 abstract function getInputHTML( $value );
679 * Override this function to add specific validation checks on the
680 * field input. Don't forget to call parent::validate() to ensure
681 * that the user-defined callback mValidationCallback is still run
682 * @param $value String the value the field was submitted with
683 * @param $alldata Array the data collected from the form
684 * @return Mixed Bool true on success, or String error to display.
686 function validate( $value, $alldata ) {
687 if ( isset( $this->mValidationCallback
) ) {
688 return call_user_func( $this->mValidationCallback
, $value, $alldata );
694 function filter( $value, $alldata ) {
695 if( isset( $this->mFilterCallback
) ) {
696 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
703 * Should this field have a label, or is there no input element with the
704 * appropriate id for the label to point to?
706 * @return bool True to output a label, false to suppress
708 protected function needsLabel() {
713 * Get the value that this input has been set to from a posted form,
714 * or the input's default value if it has not been set.
715 * @param $request WebRequest
716 * @return String the value
718 function loadDataFromRequest( $request ) {
719 if( $request->getCheck( $this->mName
) ) {
720 return $request->getText( $this->mName
);
722 return $this->getDefault();
727 * Initialise the object
728 * @param $params Associative Array. See HTMLForm doc for syntax.
730 function __construct( $params ) {
731 $this->mParams
= $params;
733 # Generate the label from a message, if possible
734 if( isset( $params['label-message'] ) ) {
735 $msgInfo = $params['label-message'];
737 if ( is_array( $msgInfo ) ) {
738 $msg = array_shift( $msgInfo );
744 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
745 } elseif ( isset( $params['label'] ) ) {
746 $this->mLabel
= $params['label'];
749 if ( isset( $params['name'] ) ) {
750 $name = $params['name'];
751 $validName = Sanitizer
::escapeId( $name );
752 if( $name != $validName ) {
753 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
755 $this->mName
= 'wp'.$name;
756 $this->mID
= 'mw-input-'.$name;
759 if ( isset( $params['default'] ) ) {
760 $this->mDefault
= $params['default'];
763 if ( isset( $params['id'] ) ) {
765 $validId = Sanitizer
::escapeId( $id );
766 if( $id != $validId ) {
767 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
772 if ( isset( $params['cssclass'] ) ) {
773 $this->mClass
= $params['cssclass'];
776 if ( isset( $params['validation-callback'] ) ) {
777 $this->mValidationCallback
= $params['validation-callback'];
780 if ( isset( $params['filter-callback'] ) ) {
781 $this->mFilterCallback
= $params['filter-callback'];
786 * Get the complete table row for the input, including help text,
787 * labels, and whatever.
788 * @param $value String the value to set the input to.
789 * @return String complete HTML table row.
791 function getTableRow( $value ) {
792 # Check for invalid data.
795 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
796 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
799 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
802 $html = $this->getLabelHtml();
803 $html .= Html
::rawElement(
805 array( 'class' => 'mw-input' ),
806 $this->getInputHTML( $value ) ."\n$errors"
809 $fieldType = get_class( $this );
811 $html = Html
::rawElement(
813 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
818 if ( isset( $this->mParams
['help-message'] ) ) {
819 $msg = $this->mParams
['help-message'];
820 $helptext = wfMsgExt( $msg, 'parseinline' );
821 if ( wfEmptyMsg( $msg, $helptext ) ) {
825 } elseif ( isset( $this->mParams
['help'] ) ) {
826 $helptext = $this->mParams
['help'];
829 if ( !is_null( $helptext ) ) {
830 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
832 $row = Html
::rawElement( 'tr', array(), $row );
839 function getLabel() {
840 return $this->mLabel
;
842 function getLabelHtml() {
843 # Don't output a for= attribute for labels with no associated input.
844 # Kind of hacky here, possibly we don't want these to be <label>s at all.
846 if ( $this->needsLabel() ) {
847 $for['for'] = $this->mID
;
849 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
850 Html
::rawElement( 'label', $for, $this->getLabel() )
854 function getDefault() {
855 if ( isset( $this->mDefault
) ) {
856 return $this->mDefault
;
863 * Returns the attributes required for the tooltip and accesskey.
865 * @return array Attributes
867 public function getTooltipAndAccessKey() {
868 if ( empty( $this->mParams
['tooltip'] ) )
872 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
876 * flatten an array of options to a single array, for instance,
877 * a set of <options> inside <optgroups>.
878 * @param $options Associative Array with values either Strings
880 * @return Array flattened input
882 public static function flattenOptions( $options ) {
885 foreach( $options as $key => $value ) {
886 if ( is_array( $value ) ) {
887 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
889 $flatOpts[] = $value;
898 class HTMLTextField
extends HTMLFormField
{
901 return isset( $this->mParams
['size'] )
902 ?
$this->mParams
['size']
906 function getInputHTML( $value ) {
909 'name' => $this->mName
,
910 'size' => $this->getSize(),
912 ) +
$this->getTooltipAndAccessKey();
914 if ( isset( $this->mParams
['maxlength'] ) ) {
915 $attribs['maxlength'] = $this->mParams
['maxlength'];
918 if ( !empty( $this->mParams
['disabled'] ) ) {
919 $attribs['disabled'] = 'disabled';
922 # TODO: Enforce pattern, step, required, readonly on the server side as
924 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
925 'placeholder' ) as $param ) {
926 if ( isset( $this->mParams
[$param] ) ) {
927 $attribs[$param] = $this->mParams
[$param];
930 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
932 if ( isset( $this->mParams
[$param] ) ) {
933 $attribs[$param] = '';
937 # Implement tiny differences between some field variants
938 # here, rather than creating a new class for each one which
939 # is essentially just a clone of this one.
940 if ( isset( $this->mParams
['type'] ) ) {
941 switch ( $this->mParams
['type'] ) {
943 $attribs['type'] = 'email';
946 $attribs['type'] = 'number';
949 $attribs['type'] = 'number';
950 $attribs['step'] = 'any';
955 $attribs['type'] = $this->mParams
['type'];
960 return Html
::element( 'input', $attribs );
963 public function validate( $value, $alldata ){
964 $p = parent
::validate( $value, $alldata );
965 if( $p !== true ) return $p;
967 if( isset( $this->mParams
['required'] ) && $value === '' ){
968 return wfMsgExt( 'htmlform-required', 'parseinline' );
973 class HTMLTextAreaField
extends HTMLFormField
{
976 return isset( $this->mParams
['cols'] )
977 ?
$this->mParams
['cols']
981 return isset( $this->mParams
['rows'] )
982 ?
$this->mParams
['rows']
986 function getInputHTML( $value ) {
989 'name' => $this->mName
,
990 'cols' => $this->getCols(),
991 'rows' => $this->getRows(),
992 ) +
$this->getTooltipAndAccessKey();
995 if ( !empty( $this->mParams
['disabled'] ) ) {
996 $attribs['disabled'] = 'disabled';
998 if ( !empty( $this->mParams
['readonly'] ) ) {
999 $attribs['readonly'] = 'readonly';
1002 foreach ( array( 'required', 'autofocus' ) as $param ) {
1003 if ( isset( $this->mParams
[$param] ) ) {
1004 $attribs[$param] = '';
1008 return Html
::element( 'textarea', $attribs, $value );
1011 public function validate( $value, $alldata ){
1012 $p = parent
::validate( $value, $alldata );
1013 if( $p !== true ) return $p;
1015 if( isset( $this->mParams
['required'] ) && $value === '' ){
1016 return wfMsgExt( 'htmlform-required', 'parseinline' );
1023 * A field that will contain a numeric value
1025 class HTMLFloatField
extends HTMLTextField
{
1027 function getSize() {
1028 return isset( $this->mParams
['size'] )
1029 ?
$this->mParams
['size']
1033 function validate( $value, $alldata ) {
1034 $p = parent
::validate( $value, $alldata );
1036 if ( $p !== true ) return $p;
1038 if ( floatval( $value ) != $value ) {
1039 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1044 # The "int" part of these message names is rather confusing.
1045 # They make equal sense for all numbers.
1046 if ( isset( $this->mParams
['min'] ) ) {
1047 $min = $this->mParams
['min'];
1048 if ( $min > $value )
1049 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1052 if ( isset( $this->mParams
['max'] ) ) {
1053 $max = $this->mParams
['max'];
1055 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1063 * A field that must contain a number
1065 class HTMLIntField
extends HTMLFloatField
{
1066 function validate( $value, $alldata ) {
1067 $p = parent
::validate( $value, $alldata );
1069 if ( $p !== true ) return $p;
1072 && ( !is_numeric( $value ) ||
round( $value ) != $value ) )
1074 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1084 class HTMLCheckField
extends HTMLFormField
{
1085 function getInputHTML( $value ) {
1086 if ( !empty( $this->mParams
['invert'] ) )
1089 $attr = $this->getTooltipAndAccessKey();
1090 $attr['id'] = $this->mID
;
1091 if( !empty( $this->mParams
['disabled'] ) ) {
1092 $attr['disabled'] = 'disabled';
1095 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1096 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1100 * For a checkbox, the label goes on the right hand side, and is
1101 * added in getInputHTML(), rather than HTMLFormField::getRow()
1103 function getLabel() {
1107 function loadDataFromRequest( $request ) {
1109 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1113 // GetCheck won't work like we want for checks.
1114 if( $request->getCheck( 'wpEditToken' ) ) {
1115 // XOR has the following truth table, which is what we want
1116 // INVERT VALUE | OUTPUT
1117 // true true | false
1118 // false true | true
1119 // false false | false
1120 // true false | true
1121 return $request->getBool( $this->mName
) xor $invert;
1123 return $this->getDefault();
1129 * A select dropdown field. Basically a wrapper for Xmlselect class
1131 class HTMLSelectField
extends HTMLFormField
{
1133 function validate( $value, $alldata ) {
1134 $p = parent
::validate( $value, $alldata );
1135 if( $p !== true ) return $p;
1137 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1138 if ( in_array( $value, $validOptions ) )
1141 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1144 function getInputHTML( $value ) {
1145 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1147 # If one of the options' 'name' is int(0), it is automatically selected.
1148 # because PHP sucks and things int(0) == 'some string'.
1149 # Working around this by forcing all of them to strings.
1150 $options = array_map( 'strval', $this->mParams
['options'] );
1152 if( !empty( $this->mParams
['disabled'] ) ) {
1153 $select->setAttribute( 'disabled', 'disabled' );
1156 $select->addOptions( $options );
1158 return $select->getHTML();
1163 * Select dropdown field, with an additional "other" textbox.
1165 class HTMLSelectOrOtherField
extends HTMLTextField
{
1166 static $jsAdded = false;
1168 function __construct( $params ) {
1169 if( !in_array( 'other', $params['options'], true ) ) {
1170 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1173 parent
::__construct( $params );
1176 static function forceToStringRecursive( $array ) {
1177 if ( is_array($array) ) {
1178 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
1180 return strval($array);
1184 function getInputHTML( $value ) {
1185 $valInSelect = false;
1187 if( $value !== false )
1188 $valInSelect = in_array( $value,
1189 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
1191 $selected = $valInSelect ?
$value : 'other';
1193 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1195 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1196 $select->addOptions( $opts );
1198 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1200 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1201 if( !empty( $this->mParams
['disabled'] ) ) {
1202 $select->setAttribute( 'disabled', 'disabled' );
1203 $tbAttribs['disabled'] = 'disabled';
1206 $select = $select->getHTML();
1208 if ( isset( $this->mParams
['maxlength'] ) ) {
1209 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1212 $textbox = Html
::input( $this->mName
. '-other',
1213 $valInSelect ?
'' : $value,
1217 return "$select<br />\n$textbox";
1220 function loadDataFromRequest( $request ) {
1221 if( $request->getCheck( $this->mName
) ) {
1222 $val = $request->getText( $this->mName
);
1224 if( $val == 'other' ) {
1225 $val = $request->getText( $this->mName
. '-other' );
1230 return $this->getDefault();
1236 * Multi-select field
1238 class HTMLMultiSelectField
extends HTMLFormField
{
1240 function validate( $value, $alldata ) {
1241 $p = parent
::validate( $value, $alldata );
1242 if( $p !== true ) return $p;
1244 if( !is_array( $value ) ) return false;
1246 # If all options are valid, array_intersect of the valid options
1247 # and the provided options will return the provided options.
1248 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1250 $validValues = array_intersect( $value, $validOptions );
1251 if ( count( $validValues ) == count( $value ) )
1254 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1257 function getInputHTML( $value ) {
1258 $html = $this->formatOptions( $this->mParams
['options'], $value );
1263 function formatOptions( $options, $value ) {
1267 if ( !empty( $this->mParams
['disabled'] ) ) {
1268 $attribs['disabled'] = 'disabled';
1271 foreach( $options as $label => $info ) {
1272 if( is_array( $info ) ) {
1273 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1274 $html .= $this->formatOptions( $info, $value );
1276 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
1278 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value, true ),
1279 $attribs +
$thisAttribs );
1280 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
1282 $html .= $checkbox . '<br />';
1289 function loadDataFromRequest( $request ) {
1290 # won't work with getCheck
1291 if( $request->getCheck( 'wpEditToken' ) ) {
1292 $arr = $request->getArray( $this->mName
);
1299 return $this->getDefault();
1303 function getDefault() {
1304 if ( isset( $this->mDefault
) ) {
1305 return $this->mDefault
;
1311 protected function needsLabel() {
1317 * Radio checkbox fields.
1319 class HTMLRadioField
extends HTMLFormField
{
1320 function validate( $value, $alldata ) {
1321 $p = parent
::validate( $value, $alldata );
1322 if( $p !== true ) return $p;
1324 if( !is_string( $value ) && !is_int( $value ) )
1327 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1329 if ( in_array( $value, $validOptions ) )
1332 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1336 * This returns a block of all the radio options, in one cell.
1337 * @see includes/HTMLFormField#getInputHTML()
1339 function getInputHTML( $value ) {
1340 $html = $this->formatOptions( $this->mParams
['options'], $value );
1345 function formatOptions( $options, $value ) {
1349 if ( !empty( $this->mParams
['disabled'] ) ) {
1350 $attribs['disabled'] = 'disabled';
1353 # TODO: should this produce an unordered list perhaps?
1354 foreach( $options as $label => $info ) {
1355 if( is_array( $info ) ) {
1356 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1357 $html .= $this->formatOptions( $info, $value );
1359 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1360 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
1361 $attribs +
array( 'id' => $id ) );
1363 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1365 $html .= "<br />\n";
1372 protected function needsLabel() {
1378 * An information field (text blob), not a proper input.
1380 class HTMLInfoField
extends HTMLFormField
{
1381 function __construct( $info ) {
1382 $info['nodata'] = true;
1384 parent
::__construct( $info );
1387 function getInputHTML( $value ) {
1388 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1391 function getTableRow( $value ) {
1392 if ( !empty( $this->mParams
['rawrow'] ) ) {
1396 return parent
::getTableRow( $value );
1399 protected function needsLabel() {
1404 class HTMLHiddenField
extends HTMLFormField
{
1406 public function __construct( $params ){
1407 parent
::__construct( $params );
1408 # forcing the 'wp' prefix on hidden field names
1410 $this->mName
= substr( $this->mName
, 2 );
1413 public function getTableRow( $value ){
1416 $params['id'] = $this->mID
;
1418 $this->mParent
->addHiddenField(
1426 public function getInputHTML( $value ){ return ''; }
1430 * Add a submit button inline in the form (as opposed to
1431 * HTMLForm::addButton(), which will add it at the end).
1433 class HTMLSubmitField
extends HTMLFormField
{
1435 function __construct( $info ) {
1436 $info['nodata'] = true;
1437 parent
::__construct( $info );
1440 function getInputHTML( $value ) {
1441 return Xml
::submitButton(
1444 'class' => 'mw-htmlform-submit',
1445 'name' => $this->mName
,
1451 protected function needsLabel() {
1456 class HTMLEditTools
extends HTMLFormField
{
1457 public function getInputHTML( $value ) {
1460 public function getTableRow( $value ) {
1461 return "<tr><td></td><td class=\"mw-input\">"
1462 . '<div class="mw-editTools">'
1463 . wfMsgExt( empty( $this->mParams
['message'] )
1464 ?
'edittools' : $this->mParams
['message'],
1465 array( 'parse', 'content' ) )
1466 . "</div></td></tr>\n";