0fddfe46171244d1af6aef20523810e8cdce3834
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 * The here's-one-I-made-earlier option: do the submission if
188 * posted, or display the form with or without funky valiation
190 * @return Bool or Status whether submission was successful.
193 # Check if we have the info we need
194 if ( ! $this->mTitle
) {
195 throw new MWException( "You must call setTitle() on an HTMLForm" );
200 # Load data from the request.
204 global $wgUser, $wgRequest;
205 $editToken = $wgRequest->getVal( 'wpEditToken' );
208 if ( $wgUser->matchEditToken( $editToken ) ) {
209 $result = $this->trySubmit();
212 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
217 $this->displayForm( $result );
222 * Validate all the fields, and call the submision callback
223 * function if everything is kosher.
224 * @return Mixed Bool true == Successful submission, Bool false
225 * == No submission attempted, anything else == Error to
228 function trySubmit() {
229 # Check for validation
230 foreach ( $this->mFlatFields
as $fieldname => $field ) {
231 if ( !empty( $field->mParams
['nodata'] ) ) {
234 if ( $field->validate(
235 $this->mFieldData
[$fieldname],
239 return isset( $this->mValidationErrorMessage
)
240 ?
$this->mValidationErrorMessage
241 : array( 'htmlform-invalid-input' );
245 $callback = $this->mSubmitCallback
;
247 $data = $this->filterDataForSubmit( $this->mFieldData
);
249 $res = call_user_func( $callback, $data );
255 * Set a callback to a function to do something with the form
256 * once it's been successfully validated.
257 * @param $cb String function name. The function will be passed
258 * the output from HTMLForm::filterDataForSubmit, and must
259 * return Bool true on success, Bool false if no submission
260 * was attempted, or String HTML output to display on error.
262 function setSubmitCallback( $cb ) {
263 $this->mSubmitCallback
= $cb;
267 * Set a message to display on a validation error.
268 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
269 * (so each entry can be either a String or Array)
271 function setValidationErrorMessage( $msg ) {
272 $this->mValidationErrorMessage
= $msg;
276 * Set the introductory message, overwriting any existing message.
277 * @param $msg String complete text of message to display
279 function setIntro( $msg ) { $this->mPre
= $msg; }
282 * Add introductory text.
283 * @param $msg String complete text of message to display
285 function addPreText( $msg ) { $this->mPre
.= $msg; }
288 * Add header text, inside the form.
289 * @param $msg String complete text of message to display
291 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
294 * Add footer text, inside the form.
295 * @param $msg String complete text of message to display
297 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
300 * Add text to the end of the display.
301 * @param $msg String complete text of message to display
303 function addPostText( $msg ) { $this->mPost
.= $msg; }
306 * Add a hidden field to the output
307 * @param $name String field name
308 * @param $value String field value
309 * @param $attribs Array
311 public function addHiddenField( $name, $value, $attribs = array() ) {
312 $attribs +
= array( 'name' => $name );
313 $this->mHiddenFields
[] = array( $value, $attribs );
316 public function addButton( $name, $value, $id = null, $attribs = null ) {
317 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
321 * Display the form (sending to wgOut), with an appropriate error
322 * message or stack of messages, and any validation errors, etc.
323 * @param $submitResult Mixed output from HTMLForm::trySubmit()
325 function displayForm( $submitResult ) {
329 . $this->getErrors( $submitResult )
332 . $this->getHiddenFields()
333 . $this->getButtons()
337 $html = $this->wrapForm( $html );
347 * Wrap the form innards in an actual <form> element
348 * @param $html String HTML contents to wrap.
349 * @return String wrapped HTML.
351 function wrapForm( $html ) {
353 # Include a <fieldset> wrapper for style, if requested.
354 if ( $this->mWrapperLegend
!== false ) {
355 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
357 # Use multipart/form-data
358 $encType = $this->mUseMultipart
359 ?
'multipart/form-data'
360 : 'application/x-www-form-urlencoded';
363 'action' => $this->getTitle()->getFullURL(),
365 'class' => 'visualClear',
366 'enctype' => $encType,
368 if ( !empty( $this->mId
) ) {
369 $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() {
402 if ( isset( $this->mSubmitID
) ) {
403 $attribs['id'] = $this->mSubmitID
;
406 if ( isset( $this->mSubmitName
) ) {
407 $attribs['name'] = $this->mSubmitName
;
410 if ( isset( $this->mSubmitTooltip
) ) {
412 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
415 $attribs['class'] = 'mw-htmlform-submit';
417 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
419 if ( $this->mShowReset
) {
420 $html .= Html
::element(
424 'value' => wfMsg( 'htmlform-reset' )
429 foreach ( $this->mButtons
as $button ) {
432 'name' => $button['name'],
433 'value' => $button['value']
436 if ( $button['attribs'] ) {
437 $attrs +
= $button['attribs'];
440 if ( isset( $button['id'] ) ) {
441 $attrs['id'] = $button['id'];
444 $html .= Html
::element( 'input', $attrs );
451 * Get the whole body of the form.
454 return $this->displaySection( $this->mFieldTree
);
458 * Format and display an error message stack.
459 * @param $errors Mixed String or Array of message keys
462 function getErrors( $errors ) {
463 if ( $errors instanceof Status
) {
465 $errorstr = $wgOut->parse( $errors->getWikiText() );
466 } elseif ( is_array( $errors ) ) {
467 $errorstr = $this->formatErrors( $errors );
473 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
478 * Format a stack of error messages into a single HTML string
479 * @param $errors Array of message keys/values
480 * @return String HTML, a <ul> list of errors
482 static function formatErrors( $errors ) {
485 foreach ( $errors as $error ) {
486 if ( is_array( $error ) ) {
487 $msg = array_shift( $error );
493 $errorstr .= Html
::rawElement(
496 wfMsgExt( $msg, array( 'parseinline' ), $error )
500 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
506 * Set the text for the submit button
507 * @param $t String plaintext.
509 function setSubmitText( $t ) {
510 $this->mSubmitText
= $t;
514 * Get the text for the submit button, either customised or a default.
515 * @return unknown_type
517 function getSubmitText() {
518 return $this->mSubmitText
520 : wfMsg( 'htmlform-submit' );
523 public function setSubmitName( $name ) {
524 $this->mSubmitName
= $name;
527 public function setSubmitTooltip( $name ) {
528 $this->mSubmitTooltip
= $name;
533 * Set the id for the submit button.
534 * @param $t String. FIXME: Integrity is *not* validated
536 function setSubmitID( $t ) {
537 $this->mSubmitID
= $t;
540 public function setId( $id ) {
544 * Prompt the whole form to be wrapped in a <fieldset>, with
545 * this text as its <legend> element.
546 * @param $legend String HTML to go inside the <legend> element.
549 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
552 * Set the prefix for various default messages
553 * TODO: currently only used for the <fieldset> legend on forms
554 * with multiple sections; should be used elsewhre?
557 function setMessagePrefix( $p ) {
558 $this->mMessagePrefix
= $p;
562 * Set the title for form submission
563 * @param $t Title of page the form is on/should be posted to
565 function setTitle( $t ) {
573 function getTitle() {
574 return $this->mTitle
;
581 function displaySection( $fields, $sectionName = '' ) {
583 $subsectionHtml = '';
584 $hasLeftColumn = false;
586 foreach ( $fields as $key => $value ) {
587 if ( is_object( $value ) ) {
588 $v = empty( $value->mParams
['nodata'] )
589 ?
$this->mFieldData
[$key]
590 : $value->getDefault();
591 $tableHtml .= $value->getTableRow( $v );
593 if ( $value->getLabel() != ' ' )
594 $hasLeftColumn = true;
595 } elseif ( is_array( $value ) ) {
596 $section = $this->displaySection( $value, $key );
597 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
598 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
604 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
605 $classes[] = 'mw-htmlform-nolabel';
609 'class' => implode( ' ', $classes ),
612 if ( $sectionName ) {
613 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
616 $tableHtml = Html
::rawElement( 'table', $attribs,
617 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
619 return $subsectionHtml . "\n" . $tableHtml;
623 * Construct the form fields from the Descriptor array
625 function loadData() {
628 $fieldData = array();
630 foreach ( $this->mFlatFields
as $fieldname => $field ) {
631 if ( !empty( $field->mParams
['nodata'] ) ) {
633 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
634 $fieldData[$fieldname] = $field->getDefault();
636 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
641 foreach ( $fieldData as $name => &$value ) {
642 $field = $this->mFlatFields
[$name];
643 $value = $field->filter( $value, $this->mFlatFields
);
646 $this->mFieldData
= $fieldData;
650 * Stop a reset button being shown for this form
651 * @param $suppressReset Bool set to false to re-enable the
654 function suppressReset( $suppressReset = true ) {
655 $this->mShowReset
= !$suppressReset;
659 * Overload this if you want to apply special filtration routines
660 * to the form as a whole, after it's submitted but before it's
663 * @return unknown_type
665 function filterDataForSubmit( $data ) {
671 * The parent class to generate form fields. Any field type should
672 * be a subclass of this.
674 abstract class HTMLFormField
{
676 protected $mValidationCallback;
677 protected $mFilterCallback;
680 protected $mLabel; # String label. Set on construction
682 protected $mClass = '';
687 * This function must be implemented to return the HTML to generate
688 * the input object itself. It should not implement the surrounding
689 * table cells/rows, or labels/help messages.
690 * @param $value String the value to set the input to; eg a default
691 * text for a text input.
692 * @return String valid HTML.
694 abstract function getInputHTML( $value );
697 * Override this function to add specific validation checks on the
698 * field input. Don't forget to call parent::validate() to ensure
699 * that the user-defined callback mValidationCallback is still run
700 * @param $value String the value the field was submitted with
701 * @param $alldata Array the data collected from the form
702 * @return Mixed Bool true on success, or String error to display.
704 function validate( $value, $alldata ) {
705 if ( isset( $this->mValidationCallback
) ) {
706 return call_user_func( $this->mValidationCallback
, $value, $alldata );
709 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
710 return wfMsgExt( 'htmlform-required', 'parseinline' );
716 function filter( $value, $alldata ) {
717 if ( isset( $this->mFilterCallback
) ) {
718 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
725 * Should this field have a label, or is there no input element with the
726 * appropriate id for the label to point to?
728 * @return bool True to output a label, false to suppress
730 protected function needsLabel() {
735 * Get the value that this input has been set to from a posted form,
736 * or the input's default value if it has not been set.
737 * @param $request WebRequest
738 * @return String the value
740 function loadDataFromRequest( $request ) {
741 if ( $request->getCheck( $this->mName
) ) {
742 return $request->getText( $this->mName
);
744 return $this->getDefault();
749 * Initialise the object
750 * @param $params Associative Array. See HTMLForm doc for syntax.
752 function __construct( $params ) {
753 $this->mParams
= $params;
755 # Generate the label from a message, if possible
756 if ( isset( $params['label-message'] ) ) {
757 $msgInfo = $params['label-message'];
759 if ( is_array( $msgInfo ) ) {
760 $msg = array_shift( $msgInfo );
766 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
767 } elseif ( isset( $params['label'] ) ) {
768 $this->mLabel
= $params['label'];
771 if ( isset( $params['name'] ) ) {
772 $name = $params['name'];
773 $validName = Sanitizer
::escapeId( $name );
775 if ( $name != $validName ) {
776 throw new MWException( "Invalid name '$name' passed to " . __METHOD__
);
779 $this->mName
= 'wp' . $name;
780 $this->mID
= 'mw-input-' . $name;
783 if ( isset( $params['default'] ) ) {
784 $this->mDefault
= $params['default'];
787 if ( isset( $params['id'] ) ) {
789 $validId = Sanitizer
::escapeId( $id );
791 if ( $id != $validId ) {
792 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
798 if ( isset( $params['cssclass'] ) ) {
799 $this->mClass
= $params['cssclass'];
802 if ( isset( $params['validation-callback'] ) ) {
803 $this->mValidationCallback
= $params['validation-callback'];
806 if ( isset( $params['filter-callback'] ) ) {
807 $this->mFilterCallback
= $params['filter-callback'];
812 * Get the complete table row for the input, including help text,
813 * labels, and whatever.
814 * @param $value String the value to set the input to.
815 * @return String complete HTML table row.
817 function getTableRow( $value ) {
818 # Check for invalid data.
821 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
823 $cellAttributes = array();
824 $verticalLabel = false;
826 if ( !empty($this->mParams
['vertical-label']) ) {
827 $cellAttributes['colspan'] = 2;
828 $verticalLabel = true;
831 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
834 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
837 $label = $this->getLabelHtml( $cellAttributes );
838 $field = Html
::rawElement(
840 array( 'class' => 'mw-input' ) +
$cellAttributes,
841 $this->getInputHTML( $value ) . "\n$errors"
844 $fieldType = get_class( $this );
846 if ($verticalLabel) {
847 $html = Html
::rawElement( 'tr',
848 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
849 $html .= Html
::rawElement( 'tr',
850 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
853 $html = Html
::rawElement( 'tr',
854 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
860 if ( isset( $this->mParams
['help-message'] ) ) {
861 $msg = $this->mParams
['help-message'];
862 $helptext = wfMsgExt( $msg, 'parseinline' );
863 if ( wfEmptyMsg( $msg, $helptext ) ) {
867 } elseif ( isset( $this->mParams
['help'] ) ) {
868 $helptext = $this->mParams
['help'];
871 if ( !is_null( $helptext ) ) {
872 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
874 $row = Html
::rawElement( 'tr', array(), $row );
881 function getLabel() {
882 return $this->mLabel
;
884 function getLabelHtml( $cellAttributes = array() ) {
885 # Don't output a for= attribute for labels with no associated input.
886 # Kind of hacky here, possibly we don't want these to be <label>s at all.
889 if ( $this->needsLabel() ) {
890 $for['for'] = $this->mID
;
893 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
894 Html
::rawElement( 'label', $for, $this->getLabel() )
898 function getDefault() {
899 if ( isset( $this->mDefault
) ) {
900 return $this->mDefault
;
907 * Returns the attributes required for the tooltip and accesskey.
909 * @return array Attributes
911 public function getTooltipAndAccessKey() {
912 if ( empty( $this->mParams
['tooltip'] ) ) {
918 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
922 * flatten an array of options to a single array, for instance,
923 * a set of <options> inside <optgroups>.
924 * @param $options Associative Array with values either Strings
926 * @return Array flattened input
928 public static function flattenOptions( $options ) {
931 foreach ( $options as $value ) {
932 if ( is_array( $value ) ) {
933 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
935 $flatOpts[] = $value;
943 class HTMLTextField
extends HTMLFormField
{
945 return isset( $this->mParams
['size'] )
946 ?
$this->mParams
['size']
950 function getInputHTML( $value ) {
953 'name' => $this->mName
,
954 'size' => $this->getSize(),
956 ) +
$this->getTooltipAndAccessKey();
958 if ( isset( $this->mParams
['maxlength'] ) ) {
959 $attribs['maxlength'] = $this->mParams
['maxlength'];
962 if ( !empty( $this->mParams
['disabled'] ) ) {
963 $attribs['disabled'] = 'disabled';
966 # TODO: Enforce pattern, step, required, readonly on the server side as
968 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
969 'placeholder' ) as $param ) {
970 if ( isset( $this->mParams
[$param] ) ) {
971 $attribs[$param] = $this->mParams
[$param];
975 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
976 if ( isset( $this->mParams
[$param] ) ) {
977 $attribs[$param] = '';
981 # Implement tiny differences between some field variants
982 # here, rather than creating a new class for each one which
983 # is essentially just a clone of this one.
984 if ( isset( $this->mParams
['type'] ) ) {
985 switch ( $this->mParams
['type'] ) {
987 $attribs['type'] = 'email';
990 $attribs['type'] = 'number';
993 $attribs['type'] = 'number';
994 $attribs['step'] = 'any';
999 $attribs['type'] = $this->mParams
['type'];
1004 return Html
::element( 'input', $attribs );
1007 class HTMLTextAreaField
extends HTMLFormField
{
1008 function getCols() {
1009 return isset( $this->mParams
['cols'] )
1010 ?
$this->mParams
['cols']
1014 function getRows() {
1015 return isset( $this->mParams
['rows'] )
1016 ?
$this->mParams
['rows']
1020 function getInputHTML( $value ) {
1023 'name' => $this->mName
,
1024 'cols' => $this->getCols(),
1025 'rows' => $this->getRows(),
1026 ) +
$this->getTooltipAndAccessKey();
1029 if ( !empty( $this->mParams
['disabled'] ) ) {
1030 $attribs['disabled'] = 'disabled';
1033 if ( !empty( $this->mParams
['readonly'] ) ) {
1034 $attribs['readonly'] = 'readonly';
1037 foreach ( array( 'required', 'autofocus' ) as $param ) {
1038 if ( isset( $this->mParams
[$param] ) ) {
1039 $attribs[$param] = '';
1043 return Html
::element( 'textarea', $attribs, $value );
1048 * A field that will contain a numeric value
1050 class HTMLFloatField
extends HTMLTextField
{
1051 function getSize() {
1052 return isset( $this->mParams
['size'] )
1053 ?
$this->mParams
['size']
1057 function validate( $value, $alldata ) {
1058 $p = parent
::validate( $value, $alldata );
1060 if ( $p !== true ) {
1064 $value = trim( $value );
1066 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1067 # with the addition that a leading '+' sign is ok.
1068 if ( !preg_match( '/^(\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?$/i', $value ) ) {
1069 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1072 # The "int" part of these message names is rather confusing.
1073 # They make equal sense for all numbers.
1074 if ( isset( $this->mParams
['min'] ) ) {
1075 $min = $this->mParams
['min'];
1077 if ( $min > $value ) {
1078 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1082 if ( isset( $this->mParams
['max'] ) ) {
1083 $max = $this->mParams
['max'];
1085 if ( $max < $value ) {
1086 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1095 * A field that must contain a number
1097 class HTMLIntField
extends HTMLFloatField
{
1098 function validate( $value, $alldata ) {
1099 $p = parent
::validate( $value, $alldata );
1101 if ( $p !== true ) {
1105 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1106 # with the addition that a leading '+' sign is ok. Note that leading zeros
1107 # are fine, and will be left in the input, which is useful for things like
1108 # phone numbers when you know that they are integers (the HTML5 type=tel
1109 # input does not require its value to be numeric). If you want a tidier
1110 # value to, eg, save in the DB, clean it up with intval().
1111 if ( !preg_match( '/^(\+|\-)?\d*$/', trim( $value ) )
1113 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1123 class HTMLCheckField
extends HTMLFormField
{
1124 function getInputHTML( $value ) {
1125 if ( !empty( $this->mParams
['invert'] ) ) {
1129 $attr = $this->getTooltipAndAccessKey();
1130 $attr['id'] = $this->mID
;
1132 if ( !empty( $this->mParams
['disabled'] ) ) {
1133 $attr['disabled'] = 'disabled';
1136 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1137 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1141 * For a checkbox, the label goes on the right hand side, and is
1142 * added in getInputHTML(), rather than HTMLFormField::getRow()
1144 function getLabel() {
1148 function loadDataFromRequest( $request ) {
1150 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1154 // GetCheck won't work like we want for checks.
1155 if ( $request->getCheck( 'wpEditToken' ) ) {
1156 // XOR has the following truth table, which is what we want
1157 // INVERT VALUE | OUTPUT
1158 // true true | false
1159 // false true | true
1160 // false false | false
1161 // true false | true
1162 return $request->getBool( $this->mName
) xor $invert;
1164 return $this->getDefault();
1170 * A select dropdown field. Basically a wrapper for Xmlselect class
1172 class HTMLSelectField
extends HTMLFormField
{
1173 function validate( $value, $alldata ) {
1174 $p = parent
::validate( $value, $alldata );
1176 if ( $p !== true ) {
1180 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1182 if ( in_array( $value, $validOptions ) )
1185 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1188 function getInputHTML( $value ) {
1189 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1191 # If one of the options' 'name' is int(0), it is automatically selected.
1192 # because PHP sucks and things int(0) == 'some string'.
1193 # Working around this by forcing all of them to strings.
1194 $options = array_map( 'strval', $this->mParams
['options'] );
1196 if ( !empty( $this->mParams
['disabled'] ) ) {
1197 $select->setAttribute( 'disabled', 'disabled' );
1200 $select->addOptions( $options );
1202 return $select->getHTML();
1207 * Select dropdown field, with an additional "other" textbox.
1209 class HTMLSelectOrOtherField
extends HTMLTextField
{
1210 static $jsAdded = false;
1212 function __construct( $params ) {
1213 if ( !in_array( 'other', $params['options'], true ) ) {
1214 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1217 parent
::__construct( $params );
1220 static function forceToStringRecursive( $array ) {
1221 if ( is_array( $array ) ) {
1222 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1224 return strval( $array );
1228 function getInputHTML( $value ) {
1229 $valInSelect = false;
1231 if ( $value !== false ) {
1232 $valInSelect = in_array(
1234 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1238 $selected = $valInSelect ?
$value : 'other';
1240 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1242 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1243 $select->addOptions( $opts );
1245 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1247 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1249 if ( !empty( $this->mParams
['disabled'] ) ) {
1250 $select->setAttribute( 'disabled', 'disabled' );
1251 $tbAttribs['disabled'] = 'disabled';
1254 $select = $select->getHTML();
1256 if ( isset( $this->mParams
['maxlength'] ) ) {
1257 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1260 $textbox = Html
::input(
1261 $this->mName
. '-other',
1262 $valInSelect ?
'' : $value,
1267 return "$select<br />\n$textbox";
1270 function loadDataFromRequest( $request ) {
1271 if ( $request->getCheck( $this->mName
) ) {
1272 $val = $request->getText( $this->mName
);
1274 if ( $val == 'other' ) {
1275 $val = $request->getText( $this->mName
. '-other' );
1280 return $this->getDefault();
1286 * Multi-select field
1288 class HTMLMultiSelectField
extends HTMLFormField
{
1289 function validate( $value, $alldata ) {
1290 $p = parent
::validate( $value, $alldata );
1292 if ( $p !== true ) {
1296 if ( !is_array( $value ) ) {
1300 # If all options are valid, array_intersect of the valid options
1301 # and the provided options will return the provided options.
1302 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1304 $validValues = array_intersect( $value, $validOptions );
1305 if ( count( $validValues ) == count( $value ) ) {
1308 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1312 function getInputHTML( $value ) {
1313 $html = $this->formatOptions( $this->mParams
['options'], $value );
1318 function formatOptions( $options, $value ) {
1323 if ( !empty( $this->mParams
['disabled'] ) ) {
1324 $attribs['disabled'] = 'disabled';
1327 foreach ( $options as $label => $info ) {
1328 if ( is_array( $info ) ) {
1329 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1330 $html .= $this->formatOptions( $info, $value );
1332 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1334 $checkbox = Xml
::check(
1335 $this->mName
. '[]',
1336 in_array( $info, $value, true ),
1337 $attribs +
$thisAttribs );
1338 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1340 $html .= $checkbox . '<br />';
1347 function loadDataFromRequest( $request ) {
1348 # won't work with getCheck
1349 if ( $request->getCheck( 'wpEditToken' ) ) {
1350 $arr = $request->getArray( $this->mName
);
1358 return $this->getDefault();
1362 function getDefault() {
1363 if ( isset( $this->mDefault
) ) {
1364 return $this->mDefault
;
1370 protected function needsLabel() {
1376 * Radio checkbox fields.
1378 class HTMLRadioField
extends HTMLFormField
{
1379 function validate( $value, $alldata ) {
1380 $p = parent
::validate( $value, $alldata );
1382 if ( $p !== true ) {
1386 if ( !is_string( $value ) && !is_int( $value ) ) {
1390 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1392 if ( in_array( $value, $validOptions ) ) {
1395 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1400 * This returns a block of all the radio options, in one cell.
1401 * @see includes/HTMLFormField#getInputHTML()
1403 function getInputHTML( $value ) {
1404 $html = $this->formatOptions( $this->mParams
['options'], $value );
1409 function formatOptions( $options, $value ) {
1413 if ( !empty( $this->mParams
['disabled'] ) ) {
1414 $attribs['disabled'] = 'disabled';
1417 # TODO: should this produce an unordered list perhaps?
1418 foreach ( $options as $label => $info ) {
1419 if ( is_array( $info ) ) {
1420 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1421 $html .= $this->formatOptions( $info, $value );
1423 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1424 $html .= Xml
::radio(
1428 $attribs +
array( 'id' => $id )
1431 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1433 $html .= "<br />\n";
1440 protected function needsLabel() {
1446 * An information field (text blob), not a proper input.
1448 class HTMLInfoField
extends HTMLFormField
{
1449 function __construct( $info ) {
1450 $info['nodata'] = true;
1452 parent
::__construct( $info );
1455 function getInputHTML( $value ) {
1456 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1459 function getTableRow( $value ) {
1460 if ( !empty( $this->mParams
['rawrow'] ) ) {
1464 return parent
::getTableRow( $value );
1467 protected function needsLabel() {
1472 class HTMLHiddenField
extends HTMLFormField
{
1473 public function __construct( $params ) {
1474 parent
::__construct( $params );
1475 # forcing the 'wp' prefix on hidden field names
1477 $this->mName
= substr( $this->mName
, 2 );
1479 # Per HTML5 spec, hidden fields cannot be 'required'
1480 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1481 unset( $this->mParams
['required'] );
1484 public function getTableRow( $value ) {
1487 $params['id'] = $this->mID
;
1490 $this->mParent
->addHiddenField(
1499 public function getInputHTML( $value ) { return ''; }
1503 * Add a submit button inline in the form (as opposed to
1504 * HTMLForm::addButton(), which will add it at the end).
1506 class HTMLSubmitField
extends HTMLFormField
{
1508 function __construct( $info ) {
1509 $info['nodata'] = true;
1510 parent
::__construct( $info );
1513 function getInputHTML( $value ) {
1514 return Xml
::submitButton(
1517 'class' => 'mw-htmlform-submit',
1518 'name' => $this->mName
,
1524 protected function needsLabel() {
1529 * Button cannot be invalid
1531 public function validate( $value, $alldata ){
1536 class HTMLEditTools
extends HTMLFormField
{
1537 public function getInputHTML( $value ) {
1541 public function getTableRow( $value ) {
1542 return "<tr><td></td><td class=\"mw-input\">"
1543 . '<div class="mw-editTools">'
1544 . wfMsgExt( empty( $this->mParams
['message'] )
1545 ?
'edittools' : $this->mParams
['message'],
1546 array( 'parse', 'content' ) )
1547 . "</div></td></tr>\n";