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;
96 protected $mUseMultipart = false;
97 protected $mHiddenFields = array();
98 protected $mButtons = array();
100 protected $mWrapperLegend = false;
103 * Build a new HTMLForm from an array of field attributes
104 * @param $descriptor Array of Field constructs, as described above
105 * @param $messagePrefix String a prefix to go in front of default messages
107 public function __construct( $descriptor, $messagePrefix = '' ) {
108 $this->mMessagePrefix
= $messagePrefix;
110 // Expand out into a tree.
111 $loadedDescriptor = array();
112 $this->mFlatFields
= array();
114 foreach ( $descriptor as $fieldname => $info ) {
115 $section = isset( $info['section'] )
119 $info['name'] = isset( $info['name'] )
123 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
124 $this->mUseMultipart
= true;
127 $field = self
::loadInputFromParameters( $info );
128 $field->mParent
= $this;
130 $setSection =& $loadedDescriptor;
132 $sectionParts = explode( '/', $section );
134 while ( count( $sectionParts ) ) {
135 $newName = array_shift( $sectionParts );
137 if ( !isset( $setSection[$newName] ) ) {
138 $setSection[$newName] = array();
141 $setSection =& $setSection[$newName];
145 $setSection[$fieldname] = $field;
146 $this->mFlatFields
[$fieldname] = $field;
149 $this->mFieldTree
= $loadedDescriptor;
153 * Add the HTMLForm-specific JavaScript, if it hasn't been
156 static function addJS() {
157 if ( self
::$jsAdded ) return;
161 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
165 * Initialise a new Object for the field
166 * @param $descriptor input Descriptor, as described above
167 * @return HTMLFormField subclass
169 static function loadInputFromParameters( $descriptor ) {
170 if ( isset( $descriptor['class'] ) ) {
171 $class = $descriptor['class'];
172 } elseif ( isset( $descriptor['type'] ) ) {
173 $class = self
::$typeMappings[$descriptor['type']];
174 $descriptor['class'] = $class;
178 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
181 $obj = new $class( $descriptor );
187 * Prepare form for submission
189 function prepareForm() {
190 # Check if we have the info we need
191 if ( ! $this->mTitle
) {
192 throw new MWException( "You must call setTitle() on an HTMLForm" );
195 // FIXME shouldn't this be closer to displayForm() ?
198 # Load data from the request.
203 * Try submitting, with edit token check first
204 * @return Status|boolean
206 function tryAuthorizedSubmit() {
207 global $wgUser, $wgRequest;
208 $editToken = $wgRequest->getVal( 'wpEditToken' );
211 if ( $wgUser->matchEditToken( $editToken ) ) {
212 $result = $this->trySubmit();
218 * The here's-one-I-made-earlier option: do the submission if
219 * posted, or display the form with or without funky valiation
221 * @return Bool or Status whether submission was successful.
224 $this->prepareForm();
226 $result = $this->tryAuthorizedSubmit();
227 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
231 $this->displayForm( $result );
236 * Validate all the fields, and call the submision callback
237 * function if everything is kosher.
238 * @return Mixed Bool true == Successful submission, Bool false
239 * == No submission attempted, anything else == Error to
242 function trySubmit() {
243 # Check for validation
244 foreach ( $this->mFlatFields
as $fieldname => $field ) {
245 if ( !empty( $field->mParams
['nodata'] ) ) {
248 if ( $field->validate(
249 $this->mFieldData
[$fieldname],
253 return isset( $this->mValidationErrorMessage
)
254 ?
$this->mValidationErrorMessage
255 : array( 'htmlform-invalid-input' );
259 $callback = $this->mSubmitCallback
;
261 $data = $this->filterDataForSubmit( $this->mFieldData
);
263 $res = call_user_func( $callback, $data );
269 * Set a callback to a function to do something with the form
270 * once it's been successfully validated.
271 * @param $cb String function name. The function will be passed
272 * the output from HTMLForm::filterDataForSubmit, and must
273 * return Bool true on success, Bool false if no submission
274 * was attempted, or String HTML output to display on error.
276 function setSubmitCallback( $cb ) {
277 $this->mSubmitCallback
= $cb;
281 * Set a message to display on a validation error.
282 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
283 * (so each entry can be either a String or Array)
285 function setValidationErrorMessage( $msg ) {
286 $this->mValidationErrorMessage
= $msg;
290 * Set the introductory message, overwriting any existing message.
291 * @param $msg String complete text of message to display
293 function setIntro( $msg ) { $this->mPre
= $msg; }
296 * Add introductory text.
297 * @param $msg String complete text of message to display
299 function addPreText( $msg ) { $this->mPre
.= $msg; }
302 * Add header text, inside the form.
303 * @param $msg String complete text of message to display
305 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
308 * Add footer text, inside the form.
309 * @param $msg String complete text of message to display
311 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
314 * Add text to the end of the display.
315 * @param $msg String complete text of message to display
317 function addPostText( $msg ) { $this->mPost
.= $msg; }
320 * Add a hidden field to the output
321 * @param $name String field name
322 * @param $value String field value
323 * @param $attribs Array
325 public function addHiddenField( $name, $value, $attribs = array() ) {
326 $attribs +
= array( 'name' => $name );
327 $this->mHiddenFields
[] = array( $value, $attribs );
330 public function addButton( $name, $value, $id = null, $attribs = null ) {
331 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
335 * Display the form (sending to wgOut), with an appropriate error
336 * message or stack of messages, and any validation errors, etc.
337 * @param $submitResult Mixed output from HTMLForm::trySubmit()
339 function displayForm( $submitResult ) {
343 . $this->getErrors( $submitResult )
346 . $this->getHiddenFields()
347 . $this->getButtons()
351 $html = $this->wrapForm( $html );
361 * Wrap the form innards in an actual <form> element
362 * @param $html String HTML contents to wrap.
363 * @return String wrapped HTML.
365 function wrapForm( $html ) {
367 # Include a <fieldset> wrapper for style, if requested.
368 if ( $this->mWrapperLegend
!== false ) {
369 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
371 # Use multipart/form-data
372 $encType = $this->mUseMultipart
373 ?
'multipart/form-data'
374 : 'application/x-www-form-urlencoded';
377 'action' => $this->getTitle()->getFullURL(),
379 'class' => 'visualClear',
380 'enctype' => $encType,
382 if ( !empty( $this->mId
) ) {
383 $attribs['id'] = $this->mId
;
386 return Html
::rawElement( 'form', $attribs, $html );
390 * Get the hidden fields that should go inside the form.
391 * @return String HTML.
393 function getHiddenFields() {
397 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
398 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
400 foreach ( $this->mHiddenFields
as $data ) {
401 list( $value, $attribs ) = $data;
402 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
409 * Get the submit and (potentially) reset buttons.
410 * @return String HTML.
412 function getButtons() {
416 if ( isset( $this->mSubmitID
) ) {
417 $attribs['id'] = $this->mSubmitID
;
420 if ( isset( $this->mSubmitName
) ) {
421 $attribs['name'] = $this->mSubmitName
;
424 if ( isset( $this->mSubmitTooltip
) ) {
426 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
429 $attribs['class'] = 'mw-htmlform-submit';
431 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
433 if ( $this->mShowReset
) {
434 $html .= Html
::element(
438 'value' => wfMsg( 'htmlform-reset' )
443 foreach ( $this->mButtons
as $button ) {
446 'name' => $button['name'],
447 'value' => $button['value']
450 if ( $button['attribs'] ) {
451 $attrs +
= $button['attribs'];
454 if ( isset( $button['id'] ) ) {
455 $attrs['id'] = $button['id'];
458 $html .= Html
::element( 'input', $attrs );
465 * Get the whole body of the form.
468 return $this->displaySection( $this->mFieldTree
);
472 * Format and display an error message stack.
473 * @param $errors Mixed String or Array of message keys
476 function getErrors( $errors ) {
477 if ( $errors instanceof Status
) {
479 $errorstr = $wgOut->parse( $errors->getWikiText() );
480 } elseif ( is_array( $errors ) ) {
481 $errorstr = $this->formatErrors( $errors );
487 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
492 * Format a stack of error messages into a single HTML string
493 * @param $errors Array of message keys/values
494 * @return String HTML, a <ul> list of errors
496 static function formatErrors( $errors ) {
499 foreach ( $errors as $error ) {
500 if ( is_array( $error ) ) {
501 $msg = array_shift( $error );
507 $errorstr .= Html
::rawElement(
510 wfMsgExt( $msg, array( 'parseinline' ), $error )
514 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
520 * Set the text for the submit button
521 * @param $t String plaintext.
523 function setSubmitText( $t ) {
524 $this->mSubmitText
= $t;
528 * Get the text for the submit button, either customised or a default.
529 * @return unknown_type
531 function getSubmitText() {
532 return $this->mSubmitText
534 : wfMsg( 'htmlform-submit' );
537 public function setSubmitName( $name ) {
538 $this->mSubmitName
= $name;
541 public function setSubmitTooltip( $name ) {
542 $this->mSubmitTooltip
= $name;
546 * Set the id for the submit button.
547 * @param $t String. FIXME: Integrity is *not* validated
549 function setSubmitID( $t ) {
550 $this->mSubmitID
= $t;
553 public function setId( $id ) {
557 * Prompt the whole form to be wrapped in a <fieldset>, with
558 * this text as its <legend> element.
559 * @param $legend String HTML to go inside the <legend> element.
562 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
565 * Set the prefix for various default messages
566 * TODO: currently only used for the <fieldset> legend on forms
567 * with multiple sections; should be used elsewhre?
570 function setMessagePrefix( $p ) {
571 $this->mMessagePrefix
= $p;
575 * Set the title for form submission
576 * @param $t Title of page the form is on/should be posted to
578 function setTitle( $t ) {
586 function getTitle() {
587 return $this->mTitle
;
594 function displaySection( $fields, $sectionName = '' ) {
596 $subsectionHtml = '';
597 $hasLeftColumn = false;
599 foreach ( $fields as $key => $value ) {
600 if ( is_object( $value ) ) {
601 $v = empty( $value->mParams
['nodata'] )
602 ?
$this->mFieldData
[$key]
603 : $value->getDefault();
604 $tableHtml .= $value->getTableRow( $v );
606 if ( $value->getLabel() != ' ' )
607 $hasLeftColumn = true;
608 } elseif ( is_array( $value ) ) {
609 $section = $this->displaySection( $value, $key );
610 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
611 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
617 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
618 $classes[] = 'mw-htmlform-nolabel';
622 'class' => implode( ' ', $classes ),
625 if ( $sectionName ) {
626 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
629 $tableHtml = Html
::rawElement( 'table', $attribs,
630 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
632 return $subsectionHtml . "\n" . $tableHtml;
636 * Construct the form fields from the Descriptor array
638 function loadData() {
641 $fieldData = array();
643 foreach ( $this->mFlatFields
as $fieldname => $field ) {
644 if ( !empty( $field->mParams
['nodata'] ) ) {
646 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
647 $fieldData[$fieldname] = $field->getDefault();
649 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
654 foreach ( $fieldData as $name => &$value ) {
655 $field = $this->mFlatFields
[$name];
656 $value = $field->filter( $value, $this->mFlatFields
);
659 $this->mFieldData
= $fieldData;
663 * Stop a reset button being shown for this form
664 * @param $suppressReset Bool set to false to re-enable the
667 function suppressReset( $suppressReset = true ) {
668 $this->mShowReset
= !$suppressReset;
672 * Overload this if you want to apply special filtration routines
673 * to the form as a whole, after it's submitted but before it's
676 * @return unknown_type
678 function filterDataForSubmit( $data ) {
684 * The parent class to generate form fields. Any field type should
685 * be a subclass of this.
687 abstract class HTMLFormField
{
689 protected $mValidationCallback;
690 protected $mFilterCallback;
693 protected $mLabel; # String label. Set on construction
695 protected $mClass = '';
700 * This function must be implemented to return the HTML to generate
701 * the input object itself. It should not implement the surrounding
702 * table cells/rows, or labels/help messages.
703 * @param $value String the value to set the input to; eg a default
704 * text for a text input.
705 * @return String valid HTML.
707 abstract function getInputHTML( $value );
710 * Override this function to add specific validation checks on the
711 * field input. Don't forget to call parent::validate() to ensure
712 * that the user-defined callback mValidationCallback is still run
713 * @param $value String the value the field was submitted with
714 * @param $alldata Array the data collected from the form
715 * @return Mixed Bool true on success, or String error to display.
717 function validate( $value, $alldata ) {
718 if ( isset( $this->mValidationCallback
) ) {
719 return call_user_func( $this->mValidationCallback
, $value, $alldata );
722 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
723 return wfMsgExt( 'htmlform-required', 'parseinline' );
729 function filter( $value, $alldata ) {
730 if ( isset( $this->mFilterCallback
) ) {
731 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
738 * Should this field have a label, or is there no input element with the
739 * appropriate id for the label to point to?
741 * @return bool True to output a label, false to suppress
743 protected function needsLabel() {
748 * Get the value that this input has been set to from a posted form,
749 * or the input's default value if it has not been set.
750 * @param $request WebRequest
751 * @return String the value
753 function loadDataFromRequest( $request ) {
754 if ( $request->getCheck( $this->mName
) ) {
755 return $request->getText( $this->mName
);
757 return $this->getDefault();
762 * Initialise the object
763 * @param $params Associative Array. See HTMLForm doc for syntax.
765 function __construct( $params ) {
766 $this->mParams
= $params;
768 # Generate the label from a message, if possible
769 if ( isset( $params['label-message'] ) ) {
770 $msgInfo = $params['label-message'];
772 if ( is_array( $msgInfo ) ) {
773 $msg = array_shift( $msgInfo );
779 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
780 } elseif ( isset( $params['label'] ) ) {
781 $this->mLabel
= $params['label'];
784 if ( isset( $params['name'] ) ) {
785 $name = $params['name'];
786 $validName = Sanitizer
::escapeId( $name );
788 if ( $name != $validName ) {
789 throw new MWException( "Invalid name '$name' passed to " . __METHOD__
);
792 $this->mName
= 'wp' . $name;
793 $this->mID
= 'mw-input-' . $name;
796 if ( isset( $params['default'] ) ) {
797 $this->mDefault
= $params['default'];
800 if ( isset( $params['id'] ) ) {
802 $validId = Sanitizer
::escapeId( $id );
804 if ( $id != $validId ) {
805 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
811 if ( isset( $params['cssclass'] ) ) {
812 $this->mClass
= $params['cssclass'];
815 if ( isset( $params['validation-callback'] ) ) {
816 $this->mValidationCallback
= $params['validation-callback'];
819 if ( isset( $params['filter-callback'] ) ) {
820 $this->mFilterCallback
= $params['filter-callback'];
825 * Get the complete table row for the input, including help text,
826 * labels, and whatever.
827 * @param $value String the value to set the input to.
828 * @return String complete HTML table row.
830 function getTableRow( $value ) {
831 # Check for invalid data.
834 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
836 $cellAttributes = array();
837 $verticalLabel = false;
839 if ( !empty($this->mParams
['vertical-label']) ) {
840 $cellAttributes['colspan'] = 2;
841 $verticalLabel = true;
844 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
847 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
850 $label = $this->getLabelHtml( $cellAttributes );
851 $field = Html
::rawElement(
853 array( 'class' => 'mw-input' ) +
$cellAttributes,
854 $this->getInputHTML( $value ) . "\n$errors"
857 $fieldType = get_class( $this );
859 if ($verticalLabel) {
860 $html = Html
::rawElement( 'tr',
861 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
862 $html .= Html
::rawElement( 'tr',
863 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
866 $html = Html
::rawElement( 'tr',
867 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
873 if ( isset( $this->mParams
['help-message'] ) ) {
874 $msg = $this->mParams
['help-message'];
875 $helptext = wfMsgExt( $msg, 'parseinline' );
876 if ( wfEmptyMsg( $msg, $helptext ) ) {
880 } elseif ( isset( $this->mParams
['help'] ) ) {
881 $helptext = $this->mParams
['help'];
884 if ( !is_null( $helptext ) ) {
885 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
887 $row = Html
::rawElement( 'tr', array(), $row );
894 function getLabel() {
895 return $this->mLabel
;
897 function getLabelHtml( $cellAttributes = array() ) {
898 # Don't output a for= attribute for labels with no associated input.
899 # Kind of hacky here, possibly we don't want these to be <label>s at all.
902 if ( $this->needsLabel() ) {
903 $for['for'] = $this->mID
;
906 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
907 Html
::rawElement( 'label', $for, $this->getLabel() )
911 function getDefault() {
912 if ( isset( $this->mDefault
) ) {
913 return $this->mDefault
;
920 * Returns the attributes required for the tooltip and accesskey.
922 * @return array Attributes
924 public function getTooltipAndAccessKey() {
925 if ( empty( $this->mParams
['tooltip'] ) ) {
931 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
935 * flatten an array of options to a single array, for instance,
936 * a set of <options> inside <optgroups>.
937 * @param $options Associative Array with values either Strings
939 * @return Array flattened input
941 public static function flattenOptions( $options ) {
944 foreach ( $options as $value ) {
945 if ( is_array( $value ) ) {
946 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
948 $flatOpts[] = $value;
956 class HTMLTextField
extends HTMLFormField
{
958 return isset( $this->mParams
['size'] )
959 ?
$this->mParams
['size']
963 function getInputHTML( $value ) {
966 'name' => $this->mName
,
967 'size' => $this->getSize(),
969 ) +
$this->getTooltipAndAccessKey();
971 if ( isset( $this->mParams
['maxlength'] ) ) {
972 $attribs['maxlength'] = $this->mParams
['maxlength'];
975 if ( !empty( $this->mParams
['disabled'] ) ) {
976 $attribs['disabled'] = 'disabled';
979 # TODO: Enforce pattern, step, required, readonly on the server side as
981 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
982 'placeholder' ) as $param ) {
983 if ( isset( $this->mParams
[$param] ) ) {
984 $attribs[$param] = $this->mParams
[$param];
988 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
989 if ( isset( $this->mParams
[$param] ) ) {
990 $attribs[$param] = '';
994 # Implement tiny differences between some field variants
995 # here, rather than creating a new class for each one which
996 # is essentially just a clone of this one.
997 if ( isset( $this->mParams
['type'] ) ) {
998 switch ( $this->mParams
['type'] ) {
1000 $attribs['type'] = 'email';
1003 $attribs['type'] = 'number';
1006 $attribs['type'] = 'number';
1007 $attribs['step'] = 'any';
1012 $attribs['type'] = $this->mParams
['type'];
1017 return Html
::element( 'input', $attribs );
1020 class HTMLTextAreaField
extends HTMLFormField
{
1021 function getCols() {
1022 return isset( $this->mParams
['cols'] )
1023 ?
$this->mParams
['cols']
1027 function getRows() {
1028 return isset( $this->mParams
['rows'] )
1029 ?
$this->mParams
['rows']
1033 function getInputHTML( $value ) {
1036 'name' => $this->mName
,
1037 'cols' => $this->getCols(),
1038 'rows' => $this->getRows(),
1039 ) +
$this->getTooltipAndAccessKey();
1042 if ( !empty( $this->mParams
['disabled'] ) ) {
1043 $attribs['disabled'] = 'disabled';
1046 if ( !empty( $this->mParams
['readonly'] ) ) {
1047 $attribs['readonly'] = 'readonly';
1050 foreach ( array( 'required', 'autofocus' ) as $param ) {
1051 if ( isset( $this->mParams
[$param] ) ) {
1052 $attribs[$param] = '';
1056 return Html
::element( 'textarea', $attribs, $value );
1061 * A field that will contain a numeric value
1063 class HTMLFloatField
extends HTMLTextField
{
1064 function getSize() {
1065 return isset( $this->mParams
['size'] )
1066 ?
$this->mParams
['size']
1070 function validate( $value, $alldata ) {
1071 $p = parent
::validate( $value, $alldata );
1073 if ( $p !== true ) {
1077 $value = trim( $value );
1079 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1080 # with the addition that a leading '+' sign is ok.
1081 if ( !preg_match( '/^(\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?$/i', $value ) ) {
1082 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1085 # The "int" part of these message names is rather confusing.
1086 # They make equal sense for all numbers.
1087 if ( isset( $this->mParams
['min'] ) ) {
1088 $min = $this->mParams
['min'];
1090 if ( $min > $value ) {
1091 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1095 if ( isset( $this->mParams
['max'] ) ) {
1096 $max = $this->mParams
['max'];
1098 if ( $max < $value ) {
1099 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1108 * A field that must contain a number
1110 class HTMLIntField
extends HTMLFloatField
{
1111 function validate( $value, $alldata ) {
1112 $p = parent
::validate( $value, $alldata );
1114 if ( $p !== true ) {
1118 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1119 # with the addition that a leading '+' sign is ok. Note that leading zeros
1120 # are fine, and will be left in the input, which is useful for things like
1121 # phone numbers when you know that they are integers (the HTML5 type=tel
1122 # input does not require its value to be numeric). If you want a tidier
1123 # value to, eg, save in the DB, clean it up with intval().
1124 if ( !preg_match( '/^(\+|\-)?\d*$/', trim( $value ) )
1126 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1136 class HTMLCheckField
extends HTMLFormField
{
1137 function getInputHTML( $value ) {
1138 if ( !empty( $this->mParams
['invert'] ) ) {
1142 $attr = $this->getTooltipAndAccessKey();
1143 $attr['id'] = $this->mID
;
1145 if ( !empty( $this->mParams
['disabled'] ) ) {
1146 $attr['disabled'] = 'disabled';
1149 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1150 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1154 * For a checkbox, the label goes on the right hand side, and is
1155 * added in getInputHTML(), rather than HTMLFormField::getRow()
1157 function getLabel() {
1161 function loadDataFromRequest( $request ) {
1163 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1167 // GetCheck won't work like we want for checks.
1168 if ( $request->getCheck( 'wpEditToken' ) ) {
1169 // XOR has the following truth table, which is what we want
1170 // INVERT VALUE | OUTPUT
1171 // true true | false
1172 // false true | true
1173 // false false | false
1174 // true false | true
1175 return $request->getBool( $this->mName
) xor $invert;
1177 return $this->getDefault();
1183 * A select dropdown field. Basically a wrapper for Xmlselect class
1185 class HTMLSelectField
extends HTMLFormField
{
1186 function validate( $value, $alldata ) {
1187 $p = parent
::validate( $value, $alldata );
1189 if ( $p !== true ) {
1193 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1195 if ( in_array( $value, $validOptions ) )
1198 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1201 function getInputHTML( $value ) {
1202 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1204 # If one of the options' 'name' is int(0), it is automatically selected.
1205 # because PHP sucks and things int(0) == 'some string'.
1206 # Working around this by forcing all of them to strings.
1207 $options = array_map( 'strval', $this->mParams
['options'] );
1209 if ( !empty( $this->mParams
['disabled'] ) ) {
1210 $select->setAttribute( 'disabled', 'disabled' );
1213 $select->addOptions( $options );
1215 return $select->getHTML();
1220 * Select dropdown field, with an additional "other" textbox.
1222 class HTMLSelectOrOtherField
extends HTMLTextField
{
1223 static $jsAdded = false;
1225 function __construct( $params ) {
1226 if ( !in_array( 'other', $params['options'], true ) ) {
1227 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1230 parent
::__construct( $params );
1233 static function forceToStringRecursive( $array ) {
1234 if ( is_array( $array ) ) {
1235 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1237 return strval( $array );
1241 function getInputHTML( $value ) {
1242 $valInSelect = false;
1244 if ( $value !== false ) {
1245 $valInSelect = in_array(
1247 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1251 $selected = $valInSelect ?
$value : 'other';
1253 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1255 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1256 $select->addOptions( $opts );
1258 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1260 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1262 if ( !empty( $this->mParams
['disabled'] ) ) {
1263 $select->setAttribute( 'disabled', 'disabled' );
1264 $tbAttribs['disabled'] = 'disabled';
1267 $select = $select->getHTML();
1269 if ( isset( $this->mParams
['maxlength'] ) ) {
1270 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1273 $textbox = Html
::input(
1274 $this->mName
. '-other',
1275 $valInSelect ?
'' : $value,
1280 return "$select<br />\n$textbox";
1283 function loadDataFromRequest( $request ) {
1284 if ( $request->getCheck( $this->mName
) ) {
1285 $val = $request->getText( $this->mName
);
1287 if ( $val == 'other' ) {
1288 $val = $request->getText( $this->mName
. '-other' );
1293 return $this->getDefault();
1299 * Multi-select field
1301 class HTMLMultiSelectField
extends HTMLFormField
{
1302 function validate( $value, $alldata ) {
1303 $p = parent
::validate( $value, $alldata );
1305 if ( $p !== true ) {
1309 if ( !is_array( $value ) ) {
1313 # If all options are valid, array_intersect of the valid options
1314 # and the provided options will return the provided options.
1315 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1317 $validValues = array_intersect( $value, $validOptions );
1318 if ( count( $validValues ) == count( $value ) ) {
1321 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1325 function getInputHTML( $value ) {
1326 $html = $this->formatOptions( $this->mParams
['options'], $value );
1331 function formatOptions( $options, $value ) {
1336 if ( !empty( $this->mParams
['disabled'] ) ) {
1337 $attribs['disabled'] = 'disabled';
1340 foreach ( $options as $label => $info ) {
1341 if ( is_array( $info ) ) {
1342 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1343 $html .= $this->formatOptions( $info, $value );
1345 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1347 $checkbox = Xml
::check(
1348 $this->mName
. '[]',
1349 in_array( $info, $value, true ),
1350 $attribs +
$thisAttribs );
1351 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1353 $html .= $checkbox . '<br />';
1360 function loadDataFromRequest( $request ) {
1361 # won't work with getCheck
1362 if ( $request->getCheck( 'wpEditToken' ) ) {
1363 $arr = $request->getArray( $this->mName
);
1371 return $this->getDefault();
1375 function getDefault() {
1376 if ( isset( $this->mDefault
) ) {
1377 return $this->mDefault
;
1383 protected function needsLabel() {
1389 * Radio checkbox fields.
1391 class HTMLRadioField
extends HTMLFormField
{
1392 function validate( $value, $alldata ) {
1393 $p = parent
::validate( $value, $alldata );
1395 if ( $p !== true ) {
1399 if ( !is_string( $value ) && !is_int( $value ) ) {
1403 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1405 if ( in_array( $value, $validOptions ) ) {
1408 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1413 * This returns a block of all the radio options, in one cell.
1414 * @see includes/HTMLFormField#getInputHTML()
1416 function getInputHTML( $value ) {
1417 $html = $this->formatOptions( $this->mParams
['options'], $value );
1422 function formatOptions( $options, $value ) {
1426 if ( !empty( $this->mParams
['disabled'] ) ) {
1427 $attribs['disabled'] = 'disabled';
1430 # TODO: should this produce an unordered list perhaps?
1431 foreach ( $options as $label => $info ) {
1432 if ( is_array( $info ) ) {
1433 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1434 $html .= $this->formatOptions( $info, $value );
1436 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1437 $html .= Xml
::radio(
1441 $attribs +
array( 'id' => $id )
1444 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1446 $html .= "<br />\n";
1453 protected function needsLabel() {
1459 * An information field (text blob), not a proper input.
1461 class HTMLInfoField
extends HTMLFormField
{
1462 function __construct( $info ) {
1463 $info['nodata'] = true;
1465 parent
::__construct( $info );
1468 function getInputHTML( $value ) {
1469 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1472 function getTableRow( $value ) {
1473 if ( !empty( $this->mParams
['rawrow'] ) ) {
1477 return parent
::getTableRow( $value );
1480 protected function needsLabel() {
1485 class HTMLHiddenField
extends HTMLFormField
{
1486 public function __construct( $params ) {
1487 parent
::__construct( $params );
1488 # forcing the 'wp' prefix on hidden field names
1490 $this->mName
= substr( $this->mName
, 2 );
1492 # Per HTML5 spec, hidden fields cannot be 'required'
1493 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1494 unset( $this->mParams
['required'] );
1497 public function getTableRow( $value ) {
1500 $params['id'] = $this->mID
;
1503 $this->mParent
->addHiddenField(
1512 public function getInputHTML( $value ) { return ''; }
1516 * Add a submit button inline in the form (as opposed to
1517 * HTMLForm::addButton(), which will add it at the end).
1519 class HTMLSubmitField
extends HTMLFormField
{
1521 function __construct( $info ) {
1522 $info['nodata'] = true;
1523 parent
::__construct( $info );
1526 function getInputHTML( $value ) {
1527 return Xml
::submitButton(
1530 'class' => 'mw-htmlform-submit',
1531 'name' => $this->mName
,
1537 protected function needsLabel() {
1542 * Button cannot be invalid
1544 public function validate( $value, $alldata ){
1549 class HTMLEditTools
extends HTMLFormField
{
1550 public function getInputHTML( $value ) {
1554 public function getTableRow( $value ) {
1555 return "<tr><td></td><td class=\"mw-input\">"
1556 . '<div class="mw-editTools">'
1557 . wfMsgExt( empty( $this->mParams
['message'] )
1558 ?
'edittools' : $this->mParams
['message'],
1559 array( 'parse', 'content' ) )
1560 . "</div></td></tr>\n";