3 * Object handling generic submission, CSRF protection, layout and
4 * other logic for UI forms. in a reusable manner.
6 * In order to generate the form, the HTMLForm object takes an array
7 * structure detailing the form fields available. Each element of the
8 * array is a basic property-list, including the type of field, the
9 * label it is to be given in the form, callbacks for validation and
10 * 'filtering', and other pertinent information.
12 * Field types are implemented as subclasses of the generic HTMLFormField
13 * object, and typically implement at least getInputHTML, which generates
14 * the HTML for the input field to be placed in the table.
16 * The constructor input is an associative array of $fieldname => $info,
17 * where $info is an Associative Array with any of the following:
19 * 'class' -- the subclass of HTMLFormField that will be used
20 * to create the object. *NOT* the CSS class!
21 * 'type' -- roughly translates into the <select> type attribute.
22 * if 'class' is not specified, this is used as a map
23 * through HTMLForm::$typeMappings to get the class name.
24 * 'default' -- default value when the form is displayed
25 * 'id' -- HTML id attribute
26 * 'cssclass' -- CSS class
27 * 'options' -- varies according to the specific object.
28 * 'label-message' -- message key for a message to use as the label.
29 * can be an array of msg key and then parameters to
31 * 'label' -- alternatively, a raw text message. Overridden by
33 * 'help-message' -- message key for a message to use as a help text.
34 * can be an array of msg key and then parameters to
36 * 'required' -- passed through to the object, indicating that it
37 * is a required field.
38 * 'size' -- the length of text fields
39 * 'filter-callback -- a function name to give you the chance to
40 * massage the inputted value before it's processed.
41 * @see HTMLForm::filter()
42 * 'validation-callback' -- a function name to give you the chance
43 * to impose extra validation on the field input.
44 * @see HTMLForm::validate()
46 * TODO: Document 'section' / 'subsection' stuff
49 static $jsAdded = false;
51 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
52 static $typeMappings = array(
53 'text' => 'HTMLTextField',
54 'textarea' => 'HTMLTextAreaField',
55 'select' => 'HTMLSelectField',
56 'radio' => 'HTMLRadioField',
57 'multiselect' => 'HTMLMultiSelectField',
58 'check' => 'HTMLCheckField',
59 'toggle' => 'HTMLCheckField',
60 'int' => 'HTMLIntField',
61 'float' => 'HTMLFloatField',
62 'info' => 'HTMLInfoField',
63 'selectorother' => 'HTMLSelectOrOtherField',
64 'submit' => 'HTMLSubmitField',
65 'hidden' => 'HTMLHiddenField',
66 'edittools' => 'HTMLEditTools',
68 # HTMLTextField will output the correct type="" attribute automagically.
69 # There are about four zillion other HTML5 input types, like url, but
70 # we don't use those at the moment, so no point in adding all of them.
71 'email' => 'HTMLTextField',
72 'password' => 'HTMLTextField',
75 protected $mMessagePrefix;
76 protected $mFlatFields;
77 protected $mFieldTree;
78 protected $mShowReset = false;
81 protected $mSubmitCallback;
82 protected $mValidationErrorMessage;
85 protected $mHeader = '';
86 protected $mFooter = '';
87 protected $mPost = '';
91 protected $mSubmitName;
92 protected $mSubmitText;
93 protected $mSubmitTooltip;
95 protected $mMethod = 'post';
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;
162 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
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 * Prepare form for submission
190 function prepareForm() {
191 # Check if we have the info we need
192 if ( ! $this->mTitle
) {
193 throw new MWException( "You must call setTitle() on an HTMLForm" );
196 // FIXME shouldn't this be closer to displayForm() ?
199 # Load data from the request.
204 * Try submitting, with edit token check first
205 * @return Status|boolean
207 function tryAuthorizedSubmit() {
208 global $wgUser, $wgRequest;
209 $editToken = $wgRequest->getVal( 'wpEditToken' );
212 if ( $wgUser->matchEditToken( $editToken ) ) {
213 $result = $this->trySubmit();
219 * The here's-one-I-made-earlier option: do the submission if
220 * posted, or display the form with or without funky valiation
222 * @return Bool or Status whether submission was successful.
225 $this->prepareForm();
227 $result = $this->tryAuthorizedSubmit();
228 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
232 $this->displayForm( $result );
237 * Validate all the fields, and call the submision callback
238 * function if everything is kosher.
239 * @return Mixed Bool true == Successful submission, Bool false
240 * == No submission attempted, anything else == Error to
243 function trySubmit() {
244 # Check for validation
245 foreach ( $this->mFlatFields
as $fieldname => $field ) {
246 if ( !empty( $field->mParams
['nodata'] ) ) {
249 if ( $field->validate(
250 $this->mFieldData
[$fieldname],
254 return isset( $this->mValidationErrorMessage
)
255 ?
$this->mValidationErrorMessage
256 : array( 'htmlform-invalid-input' );
260 $callback = $this->mSubmitCallback
;
262 $data = $this->filterDataForSubmit( $this->mFieldData
);
264 $res = call_user_func( $callback, $data );
270 * Set a callback to a function to do something with the form
271 * once it's been successfully validated.
272 * @param $cb String function name. The function will be passed
273 * the output from HTMLForm::filterDataForSubmit, and must
274 * return Bool true on success, Bool false if no submission
275 * was attempted, or String HTML output to display on error.
277 function setSubmitCallback( $cb ) {
278 $this->mSubmitCallback
= $cb;
282 * Set a message to display on a validation error.
283 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
284 * (so each entry can be either a String or Array)
286 function setValidationErrorMessage( $msg ) {
287 $this->mValidationErrorMessage
= $msg;
291 * Set the introductory message, overwriting any existing message.
292 * @param $msg String complete text of message to display
294 function setIntro( $msg ) { $this->mPre
= $msg; }
297 * Add introductory text.
298 * @param $msg String complete text of message to display
300 function addPreText( $msg ) { $this->mPre
.= $msg; }
303 * Add header text, inside the form.
304 * @param $msg String complete text of message to display
306 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
309 * Add footer text, inside the form.
310 * @param $msg String complete text of message to display
312 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
315 * Add text to the end of the display.
316 * @param $msg String complete text of message to display
318 function addPostText( $msg ) { $this->mPost
.= $msg; }
321 * Add a hidden field to the output
322 * @param $name String field name
323 * @param $value String field value
324 * @param $attribs Array
326 public function addHiddenField( $name, $value, $attribs = array() ) {
327 $attribs +
= array( 'name' => $name );
328 $this->mHiddenFields
[] = array( $value, $attribs );
331 public function addButton( $name, $value, $id = null, $attribs = null ) {
332 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
336 * Display the form (sending to wgOut), with an appropriate error
337 * message or stack of messages, and any validation errors, etc.
338 * @param $submitResult Mixed output from HTMLForm::trySubmit()
340 function displayForm( $submitResult ) {
344 . $this->getErrors( $submitResult )
347 . $this->getHiddenFields()
348 . $this->getButtons()
352 $html = $this->wrapForm( $html );
362 * Wrap the form innards in an actual <form> element
363 * @param $html String HTML contents to wrap.
364 * @return String wrapped HTML.
366 function wrapForm( $html ) {
368 # Include a <fieldset> wrapper for style, if requested.
369 if ( $this->mWrapperLegend
!== false ) {
370 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
372 # Use multipart/form-data
373 $encType = $this->mUseMultipart
374 ?
'multipart/form-data'
375 : 'application/x-www-form-urlencoded';
378 'action' => $this->getTitle()->getFullURL(),
379 'method' => $this->mMethod
,
380 'class' => 'visualClear',
381 'enctype' => $encType,
383 if ( !empty( $this->mId
) ) {
384 $attribs['id'] = $this->mId
;
387 return Html
::rawElement( 'form', $attribs, $html );
391 * Get the hidden fields that should go inside the form.
392 * @return String HTML.
394 function getHiddenFields() {
398 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
399 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
401 foreach ( $this->mHiddenFields
as $data ) {
402 list( $value, $attribs ) = $data;
403 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
410 * Get the submit and (potentially) reset buttons.
411 * @return String HTML.
413 function getButtons() {
417 if ( isset( $this->mSubmitID
) ) {
418 $attribs['id'] = $this->mSubmitID
;
421 if ( isset( $this->mSubmitName
) ) {
422 $attribs['name'] = $this->mSubmitName
;
425 if ( isset( $this->mSubmitTooltip
) ) {
427 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
430 $attribs['class'] = 'mw-htmlform-submit';
432 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
434 if ( $this->mShowReset
) {
435 $html .= Html
::element(
439 'value' => wfMsg( 'htmlform-reset' )
444 foreach ( $this->mButtons
as $button ) {
447 'name' => $button['name'],
448 'value' => $button['value']
451 if ( $button['attribs'] ) {
452 $attrs +
= $button['attribs'];
455 if ( isset( $button['id'] ) ) {
456 $attrs['id'] = $button['id'];
459 $html .= Html
::element( 'input', $attrs );
466 * Get the whole body of the form.
469 return $this->displaySection( $this->mFieldTree
);
473 * Format and display an error message stack.
474 * @param $errors Mixed String or Array of message keys
477 function getErrors( $errors ) {
478 if ( $errors instanceof Status
) {
480 $errorstr = $wgOut->parse( $errors->getWikiText() );
481 } elseif ( is_array( $errors ) ) {
482 $errorstr = $this->formatErrors( $errors );
488 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
493 * Format a stack of error messages into a single HTML string
494 * @param $errors Array of message keys/values
495 * @return String HTML, a <ul> list of errors
497 static function formatErrors( $errors ) {
500 foreach ( $errors as $error ) {
501 if ( is_array( $error ) ) {
502 $msg = array_shift( $error );
508 $errorstr .= Html
::rawElement(
511 wfMsgExt( $msg, array( 'parseinline' ), $error )
515 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
521 * Set the text for the submit button
522 * @param $t String plaintext.
524 function setSubmitText( $t ) {
525 $this->mSubmitText
= $t;
529 * Get the text for the submit button, either customised or a default.
530 * @return unknown_type
532 function getSubmitText() {
533 return $this->mSubmitText
535 : wfMsg( 'htmlform-submit' );
538 public function setSubmitName( $name ) {
539 $this->mSubmitName
= $name;
542 public function setSubmitTooltip( $name ) {
543 $this->mSubmitTooltip
= $name;
547 * Set the id for the submit button.
548 * @param $t String. FIXME: Integrity is *not* validated
550 function setSubmitID( $t ) {
551 $this->mSubmitID
= $t;
554 public function setId( $id ) {
558 * Prompt the whole form to be wrapped in a <fieldset>, with
559 * this text as its <legend> element.
560 * @param $legend String HTML to go inside the <legend> element.
563 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
566 * Set the prefix for various default messages
567 * TODO: currently only used for the <fieldset> legend on forms
568 * with multiple sections; should be used elsewhre?
571 function setMessagePrefix( $p ) {
572 $this->mMessagePrefix
= $p;
576 * Set the title for form submission
577 * @param $t Title of page the form is on/should be posted to
579 function setTitle( $t ) {
587 function getTitle() {
588 return $this->mTitle
;
592 * Set the method used to submit the form
593 * @param $method String
595 public function setMethod( $method='post' ){
596 $this->mMethod
= $method;
599 public function getMethod(){
600 return $this->mMethod
;
607 function displaySection( $fields, $sectionName = '' ) {
609 $subsectionHtml = '';
610 $hasLeftColumn = false;
612 foreach ( $fields as $key => $value ) {
613 if ( is_object( $value ) ) {
614 $v = empty( $value->mParams
['nodata'] )
615 ?
$this->mFieldData
[$key]
616 : $value->getDefault();
617 $tableHtml .= $value->getTableRow( $v );
619 if ( $value->getLabel() != ' ' )
620 $hasLeftColumn = true;
621 } elseif ( is_array( $value ) ) {
622 $section = $this->displaySection( $value, $key );
623 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
624 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
630 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
631 $classes[] = 'mw-htmlform-nolabel';
635 'class' => implode( ' ', $classes ),
638 if ( $sectionName ) {
639 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
642 $tableHtml = Html
::rawElement( 'table', $attribs,
643 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
645 return $subsectionHtml . "\n" . $tableHtml;
649 * Construct the form fields from the Descriptor array
651 function loadData() {
654 $fieldData = array();
656 foreach ( $this->mFlatFields
as $fieldname => $field ) {
657 if ( !empty( $field->mParams
['nodata'] ) ) {
659 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
660 $fieldData[$fieldname] = $field->getDefault();
662 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
667 foreach ( $fieldData as $name => &$value ) {
668 $field = $this->mFlatFields
[$name];
669 $value = $field->filter( $value, $this->mFlatFields
);
672 $this->mFieldData
= $fieldData;
676 * Stop a reset button being shown for this form
677 * @param $suppressReset Bool set to false to re-enable the
680 function suppressReset( $suppressReset = true ) {
681 $this->mShowReset
= !$suppressReset;
685 * Overload this if you want to apply special filtration routines
686 * to the form as a whole, after it's submitted but before it's
689 * @return unknown_type
691 function filterDataForSubmit( $data ) {
697 * The parent class to generate form fields. Any field type should
698 * be a subclass of this.
700 abstract class HTMLFormField
{
702 protected $mValidationCallback;
703 protected $mFilterCallback;
706 protected $mLabel; # String label. Set on construction
708 protected $mClass = '';
713 * This function must be implemented to return the HTML to generate
714 * the input object itself. It should not implement the surrounding
715 * table cells/rows, or labels/help messages.
716 * @param $value String the value to set the input to; eg a default
717 * text for a text input.
718 * @return String valid HTML.
720 abstract function getInputHTML( $value );
723 * Override this function to add specific validation checks on the
724 * field input. Don't forget to call parent::validate() to ensure
725 * that the user-defined callback mValidationCallback is still run
726 * @param $value String the value the field was submitted with
727 * @param $alldata Array the data collected from the form
728 * @return Mixed Bool true on success, or String error to display.
730 function validate( $value, $alldata ) {
731 if ( isset( $this->mValidationCallback
) ) {
732 return call_user_func( $this->mValidationCallback
, $value, $alldata );
735 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
736 return wfMsgExt( 'htmlform-required', 'parseinline' );
742 function filter( $value, $alldata ) {
743 if ( isset( $this->mFilterCallback
) ) {
744 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
751 * Should this field have a label, or is there no input element with the
752 * appropriate id for the label to point to?
754 * @return bool True to output a label, false to suppress
756 protected function needsLabel() {
761 * Get the value that this input has been set to from a posted form,
762 * or the input's default value if it has not been set.
763 * @param $request WebRequest
764 * @return String the value
766 function loadDataFromRequest( $request ) {
767 if ( $request->getCheck( $this->mName
) ) {
768 return $request->getText( $this->mName
);
770 return $this->getDefault();
775 * Initialise the object
776 * @param $params Associative Array. See HTMLForm doc for syntax.
778 function __construct( $params ) {
779 $this->mParams
= $params;
781 # Generate the label from a message, if possible
782 if ( isset( $params['label-message'] ) ) {
783 $msgInfo = $params['label-message'];
785 if ( is_array( $msgInfo ) ) {
786 $msg = array_shift( $msgInfo );
792 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
793 } elseif ( isset( $params['label'] ) ) {
794 $this->mLabel
= $params['label'];
797 if ( isset( $params['name'] ) ) {
798 $name = $params['name'];
799 $validName = Sanitizer
::escapeId( $name );
801 if ( $name != $validName ) {
802 throw new MWException( "Invalid name '$name' passed to " . __METHOD__
);
805 $this->mName
= 'wp' . $name;
806 $this->mID
= 'mw-input-' . $name;
809 if ( isset( $params['default'] ) ) {
810 $this->mDefault
= $params['default'];
813 if ( isset( $params['id'] ) ) {
815 $validId = Sanitizer
::escapeId( $id );
817 if ( $id != $validId ) {
818 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
824 if ( isset( $params['cssclass'] ) ) {
825 $this->mClass
= $params['cssclass'];
828 if ( isset( $params['validation-callback'] ) ) {
829 $this->mValidationCallback
= $params['validation-callback'];
832 if ( isset( $params['filter-callback'] ) ) {
833 $this->mFilterCallback
= $params['filter-callback'];
838 * Get the complete table row for the input, including help text,
839 * labels, and whatever.
840 * @param $value String the value to set the input to.
841 * @return String complete HTML table row.
843 function getTableRow( $value ) {
844 # Check for invalid data.
847 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
849 $cellAttributes = array();
850 $verticalLabel = false;
852 if ( !empty($this->mParams
['vertical-label']) ) {
853 $cellAttributes['colspan'] = 2;
854 $verticalLabel = true;
857 if ( $errors === true ||
( !$wgRequest->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
860 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
863 $label = $this->getLabelHtml( $cellAttributes );
864 $field = Html
::rawElement(
866 array( 'class' => 'mw-input' ) +
$cellAttributes,
867 $this->getInputHTML( $value ) . "\n$errors"
870 $fieldType = get_class( $this );
872 if ($verticalLabel) {
873 $html = Html
::rawElement( 'tr',
874 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
875 $html .= Html
::rawElement( 'tr',
876 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
879 $html = Html
::rawElement( 'tr',
880 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
886 if ( isset( $this->mParams
['help-message'] ) ) {
887 $msg = $this->mParams
['help-message'];
888 $helptext = wfMsgExt( $msg, 'parseinline' );
889 if ( wfEmptyMsg( $msg, $helptext ) ) {
893 } elseif ( isset( $this->mParams
['help'] ) ) {
894 $helptext = $this->mParams
['help'];
897 if ( !is_null( $helptext ) ) {
898 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
900 $row = Html
::rawElement( 'tr', array(), $row );
907 function getLabel() {
908 return $this->mLabel
;
910 function getLabelHtml( $cellAttributes = array() ) {
911 # Don't output a for= attribute for labels with no associated input.
912 # Kind of hacky here, possibly we don't want these to be <label>s at all.
915 if ( $this->needsLabel() ) {
916 $for['for'] = $this->mID
;
919 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
920 Html
::rawElement( 'label', $for, $this->getLabel() )
924 function getDefault() {
925 if ( isset( $this->mDefault
) ) {
926 return $this->mDefault
;
933 * Returns the attributes required for the tooltip and accesskey.
935 * @return array Attributes
937 public function getTooltipAndAccessKey() {
938 if ( empty( $this->mParams
['tooltip'] ) ) {
944 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
948 * flatten an array of options to a single array, for instance,
949 * a set of <options> inside <optgroups>.
950 * @param $options Associative Array with values either Strings
952 * @return Array flattened input
954 public static function flattenOptions( $options ) {
957 foreach ( $options as $value ) {
958 if ( is_array( $value ) ) {
959 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
961 $flatOpts[] = $value;
969 class HTMLTextField
extends HTMLFormField
{
971 return isset( $this->mParams
['size'] )
972 ?
$this->mParams
['size']
976 function getInputHTML( $value ) {
979 'name' => $this->mName
,
980 'size' => $this->getSize(),
982 ) +
$this->getTooltipAndAccessKey();
984 if ( isset( $this->mParams
['maxlength'] ) ) {
985 $attribs['maxlength'] = $this->mParams
['maxlength'];
988 if ( !empty( $this->mParams
['disabled'] ) ) {
989 $attribs['disabled'] = 'disabled';
992 # TODO: Enforce pattern, step, required, readonly on the server side as
994 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
995 'placeholder' ) as $param ) {
996 if ( isset( $this->mParams
[$param] ) ) {
997 $attribs[$param] = $this->mParams
[$param];
1001 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1002 if ( isset( $this->mParams
[$param] ) ) {
1003 $attribs[$param] = '';
1007 # Implement tiny differences between some field variants
1008 # here, rather than creating a new class for each one which
1009 # is essentially just a clone of this one.
1010 if ( isset( $this->mParams
['type'] ) ) {
1011 switch ( $this->mParams
['type'] ) {
1013 $attribs['type'] = 'email';
1016 $attribs['type'] = 'number';
1019 $attribs['type'] = 'number';
1020 $attribs['step'] = 'any';
1025 $attribs['type'] = $this->mParams
['type'];
1030 return Html
::element( 'input', $attribs );
1033 class HTMLTextAreaField
extends HTMLFormField
{
1034 function getCols() {
1035 return isset( $this->mParams
['cols'] )
1036 ?
$this->mParams
['cols']
1040 function getRows() {
1041 return isset( $this->mParams
['rows'] )
1042 ?
$this->mParams
['rows']
1046 function getInputHTML( $value ) {
1049 'name' => $this->mName
,
1050 'cols' => $this->getCols(),
1051 'rows' => $this->getRows(),
1052 ) +
$this->getTooltipAndAccessKey();
1055 if ( !empty( $this->mParams
['disabled'] ) ) {
1056 $attribs['disabled'] = 'disabled';
1059 if ( !empty( $this->mParams
['readonly'] ) ) {
1060 $attribs['readonly'] = 'readonly';
1063 foreach ( array( 'required', 'autofocus' ) as $param ) {
1064 if ( isset( $this->mParams
[$param] ) ) {
1065 $attribs[$param] = '';
1069 return Html
::element( 'textarea', $attribs, $value );
1074 * A field that will contain a numeric value
1076 class HTMLFloatField
extends HTMLTextField
{
1077 function getSize() {
1078 return isset( $this->mParams
['size'] )
1079 ?
$this->mParams
['size']
1083 function validate( $value, $alldata ) {
1084 $p = parent
::validate( $value, $alldata );
1086 if ( $p !== true ) {
1090 $value = trim( $value );
1092 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1093 # with the addition that a leading '+' sign is ok.
1094 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1095 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1098 # The "int" part of these message names is rather confusing.
1099 # They make equal sense for all numbers.
1100 if ( isset( $this->mParams
['min'] ) ) {
1101 $min = $this->mParams
['min'];
1103 if ( $min > $value ) {
1104 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1108 if ( isset( $this->mParams
['max'] ) ) {
1109 $max = $this->mParams
['max'];
1111 if ( $max < $value ) {
1112 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1121 * A field that must contain a number
1123 class HTMLIntField
extends HTMLFloatField
{
1124 function validate( $value, $alldata ) {
1125 $p = parent
::validate( $value, $alldata );
1127 if ( $p !== true ) {
1131 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1132 # with the addition that a leading '+' sign is ok. Note that leading zeros
1133 # are fine, and will be left in the input, which is useful for things like
1134 # phone numbers when you know that they are integers (the HTML5 type=tel
1135 # input does not require its value to be numeric). If you want a tidier
1136 # value to, eg, save in the DB, clean it up with intval().
1137 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1139 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1149 class HTMLCheckField
extends HTMLFormField
{
1150 function getInputHTML( $value ) {
1151 if ( !empty( $this->mParams
['invert'] ) ) {
1155 $attr = $this->getTooltipAndAccessKey();
1156 $attr['id'] = $this->mID
;
1158 if ( !empty( $this->mParams
['disabled'] ) ) {
1159 $attr['disabled'] = 'disabled';
1162 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1163 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1167 * For a checkbox, the label goes on the right hand side, and is
1168 * added in getInputHTML(), rather than HTMLFormField::getRow()
1170 function getLabel() {
1174 function loadDataFromRequest( $request ) {
1176 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1180 // GetCheck won't work like we want for checks.
1181 if ( $request->getCheck( 'wpEditToken' ) ) {
1182 // XOR has the following truth table, which is what we want
1183 // INVERT VALUE | OUTPUT
1184 // true true | false
1185 // false true | true
1186 // false false | false
1187 // true false | true
1188 return $request->getBool( $this->mName
) xor $invert;
1190 return $this->getDefault();
1196 * A select dropdown field. Basically a wrapper for Xmlselect class
1198 class HTMLSelectField
extends HTMLFormField
{
1199 function validate( $value, $alldata ) {
1200 $p = parent
::validate( $value, $alldata );
1202 if ( $p !== true ) {
1206 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1208 if ( in_array( $value, $validOptions ) )
1211 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1214 function getInputHTML( $value ) {
1215 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1217 # If one of the options' 'name' is int(0), it is automatically selected.
1218 # because PHP sucks and things int(0) == 'some string'.
1219 # Working around this by forcing all of them to strings.
1220 $options = array_map( 'strval', $this->mParams
['options'] );
1222 if ( !empty( $this->mParams
['disabled'] ) ) {
1223 $select->setAttribute( 'disabled', 'disabled' );
1226 $select->addOptions( $options );
1228 return $select->getHTML();
1233 * Select dropdown field, with an additional "other" textbox.
1235 class HTMLSelectOrOtherField
extends HTMLTextField
{
1236 static $jsAdded = false;
1238 function __construct( $params ) {
1239 if ( !in_array( 'other', $params['options'], true ) ) {
1240 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1243 parent
::__construct( $params );
1246 static function forceToStringRecursive( $array ) {
1247 if ( is_array( $array ) ) {
1248 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1250 return strval( $array );
1254 function getInputHTML( $value ) {
1255 $valInSelect = false;
1257 if ( $value !== false ) {
1258 $valInSelect = in_array(
1260 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1264 $selected = $valInSelect ?
$value : 'other';
1266 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1268 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1269 $select->addOptions( $opts );
1271 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1273 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1275 if ( !empty( $this->mParams
['disabled'] ) ) {
1276 $select->setAttribute( 'disabled', 'disabled' );
1277 $tbAttribs['disabled'] = 'disabled';
1280 $select = $select->getHTML();
1282 if ( isset( $this->mParams
['maxlength'] ) ) {
1283 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1286 $textbox = Html
::input(
1287 $this->mName
. '-other',
1288 $valInSelect ?
'' : $value,
1293 return "$select<br />\n$textbox";
1296 function loadDataFromRequest( $request ) {
1297 if ( $request->getCheck( $this->mName
) ) {
1298 $val = $request->getText( $this->mName
);
1300 if ( $val == 'other' ) {
1301 $val = $request->getText( $this->mName
. '-other' );
1306 return $this->getDefault();
1312 * Multi-select field
1314 class HTMLMultiSelectField
extends HTMLFormField
{
1315 function validate( $value, $alldata ) {
1316 $p = parent
::validate( $value, $alldata );
1318 if ( $p !== true ) {
1322 if ( !is_array( $value ) ) {
1326 # If all options are valid, array_intersect of the valid options
1327 # and the provided options will return the provided options.
1328 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1330 $validValues = array_intersect( $value, $validOptions );
1331 if ( count( $validValues ) == count( $value ) ) {
1334 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1338 function getInputHTML( $value ) {
1339 $html = $this->formatOptions( $this->mParams
['options'], $value );
1344 function formatOptions( $options, $value ) {
1349 if ( !empty( $this->mParams
['disabled'] ) ) {
1350 $attribs['disabled'] = 'disabled';
1353 foreach ( $options as $label => $info ) {
1354 if ( is_array( $info ) ) {
1355 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1356 $html .= $this->formatOptions( $info, $value );
1358 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1360 $checkbox = Xml
::check(
1361 $this->mName
. '[]',
1362 in_array( $info, $value, true ),
1363 $attribs +
$thisAttribs );
1364 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1366 $html .= $checkbox . '<br />';
1373 function loadDataFromRequest( $request ) {
1374 # won't work with getCheck
1375 if ( $request->getCheck( 'wpEditToken' ) ) {
1376 $arr = $request->getArray( $this->mName
);
1384 return $this->getDefault();
1388 function getDefault() {
1389 if ( isset( $this->mDefault
) ) {
1390 return $this->mDefault
;
1396 protected function needsLabel() {
1402 * Radio checkbox fields.
1404 class HTMLRadioField
extends HTMLFormField
{
1405 function validate( $value, $alldata ) {
1406 $p = parent
::validate( $value, $alldata );
1408 if ( $p !== true ) {
1412 if ( !is_string( $value ) && !is_int( $value ) ) {
1416 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1418 if ( in_array( $value, $validOptions ) ) {
1421 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1426 * This returns a block of all the radio options, in one cell.
1427 * @see includes/HTMLFormField#getInputHTML()
1429 function getInputHTML( $value ) {
1430 $html = $this->formatOptions( $this->mParams
['options'], $value );
1435 function formatOptions( $options, $value ) {
1439 if ( !empty( $this->mParams
['disabled'] ) ) {
1440 $attribs['disabled'] = 'disabled';
1443 # TODO: should this produce an unordered list perhaps?
1444 foreach ( $options as $label => $info ) {
1445 if ( is_array( $info ) ) {
1446 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1447 $html .= $this->formatOptions( $info, $value );
1449 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1450 $html .= Xml
::radio(
1454 $attribs +
array( 'id' => $id )
1457 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1459 $html .= "<br />\n";
1466 protected function needsLabel() {
1472 * An information field (text blob), not a proper input.
1474 class HTMLInfoField
extends HTMLFormField
{
1475 function __construct( $info ) {
1476 $info['nodata'] = true;
1478 parent
::__construct( $info );
1481 function getInputHTML( $value ) {
1482 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1485 function getTableRow( $value ) {
1486 if ( !empty( $this->mParams
['rawrow'] ) ) {
1490 return parent
::getTableRow( $value );
1493 protected function needsLabel() {
1498 class HTMLHiddenField
extends HTMLFormField
{
1499 public function __construct( $params ) {
1500 parent
::__construct( $params );
1501 # forcing the 'wp' prefix on hidden field names
1503 $this->mName
= substr( $this->mName
, 2 );
1505 # Per HTML5 spec, hidden fields cannot be 'required'
1506 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1507 unset( $this->mParams
['required'] );
1510 public function getTableRow( $value ) {
1513 $params['id'] = $this->mID
;
1516 $this->mParent
->addHiddenField(
1525 public function getInputHTML( $value ) { return ''; }
1529 * Add a submit button inline in the form (as opposed to
1530 * HTMLForm::addButton(), which will add it at the end).
1532 class HTMLSubmitField
extends HTMLFormField
{
1534 function __construct( $info ) {
1535 $info['nodata'] = true;
1536 parent
::__construct( $info );
1539 function getInputHTML( $value ) {
1540 return Xml
::submitButton(
1543 'class' => 'mw-htmlform-submit',
1544 'name' => $this->mName
,
1550 protected function needsLabel() {
1555 * Button cannot be invalid
1557 public function validate( $value, $alldata ){
1562 class HTMLEditTools
extends HTMLFormField
{
1563 public function getInputHTML( $value ) {
1567 public function getTableRow( $value ) {
1568 return "<tr><td></td><td class=\"mw-input\">"
1569 . '<div class="mw-editTools">'
1570 . wfMsgExt( empty( $this->mParams
['message'] )
1571 ?
'edittools' : $this->mParams
['message'],
1572 array( 'parse', 'content' ) )
1573 . "</div></td></tr>\n";