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 * Overwrites 'help-messages'.
37 * 'help-messages' -- array of message key. As above, each item can
38 * be an array of msg key and then parameters.
39 * Overwrites 'help-message'.
40 * 'required' -- passed through to the object, indicating that it
41 * is a required field.
42 * 'size' -- the length of text fields
43 * 'filter-callback -- a function name to give you the chance to
44 * massage the inputted value before it's processed.
45 * @see HTMLForm::filter()
46 * 'validation-callback' -- a function name to give you the chance
47 * to impose extra validation on the field input.
48 * @see HTMLForm::validate()
49 * 'name' -- By default, the 'name' attribute of the input field
50 * is "wp{$fieldname}". If you want a different name
51 * (eg one without the "wp" prefix), specify it here and
52 * it will be used without modification.
54 * TODO: Document 'section' / 'subsection' stuff
58 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
59 static $typeMappings = array(
60 'text' => 'HTMLTextField',
61 'textarea' => 'HTMLTextAreaField',
62 'select' => 'HTMLSelectField',
63 'radio' => 'HTMLRadioField',
64 'multiselect' => 'HTMLMultiSelectField',
65 'check' => 'HTMLCheckField',
66 'toggle' => 'HTMLCheckField',
67 'int' => 'HTMLIntField',
68 'float' => 'HTMLFloatField',
69 'info' => 'HTMLInfoField',
70 'selectorother' => 'HTMLSelectOrOtherField',
71 'selectandother' => 'HTMLSelectAndOtherField',
72 'submit' => 'HTMLSubmitField',
73 'hidden' => 'HTMLHiddenField',
74 'edittools' => 'HTMLEditTools',
76 # HTMLTextField will output the correct type="" attribute automagically.
77 # There are about four zillion other HTML5 input types, like url, but
78 # we don't use those at the moment, so no point in adding all of them.
79 'email' => 'HTMLTextField',
80 'password' => 'HTMLTextField',
83 protected $mMessagePrefix;
84 protected $mFlatFields;
85 protected $mFieldTree;
86 protected $mShowReset = false;
89 protected $mSubmitCallback;
90 protected $mValidationErrorMessage;
93 protected $mHeader = '';
94 protected $mFooter = '';
95 protected $mSectionHeaders = array();
96 protected $mSectionFooters = array();
97 protected $mPost = '';
100 protected $mSubmitID;
101 protected $mSubmitName;
102 protected $mSubmitText;
103 protected $mSubmitTooltip;
105 protected $mMethod = 'post';
107 protected $mUseMultipart = false;
108 protected $mHiddenFields = array();
109 protected $mButtons = array();
111 protected $mWrapperLegend = false;
114 * Build a new HTMLForm from an array of field attributes
115 * @param $descriptor Array of Field constructs, as described above
116 * @param $messagePrefix String a prefix to go in front of default messages
118 public function __construct( $descriptor, $messagePrefix = '' ) {
119 $this->mMessagePrefix
= $messagePrefix;
121 // Expand out into a tree.
122 $loadedDescriptor = array();
123 $this->mFlatFields
= array();
125 foreach ( $descriptor as $fieldname => $info ) {
126 $section = isset( $info['section'] )
130 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
131 $this->mUseMultipart
= true;
134 $field = self
::loadInputFromParameters( $fieldname, $info );
135 $field->mParent
= $this;
137 $setSection =& $loadedDescriptor;
139 $sectionParts = explode( '/', $section );
141 while ( count( $sectionParts ) ) {
142 $newName = array_shift( $sectionParts );
144 if ( !isset( $setSection[$newName] ) ) {
145 $setSection[$newName] = array();
148 $setSection =& $setSection[$newName];
152 $setSection[$fieldname] = $field;
153 $this->mFlatFields
[$fieldname] = $field;
156 $this->mFieldTree
= $loadedDescriptor;
160 * Add the HTMLForm-specific JavaScript, if it hasn't been
162 * @deprecated since 1.18 load modules with ResourceLoader instead
164 static function addJS() { }
167 * Initialise a new Object for the field
168 * @param $descriptor input Descriptor, as described above
169 * @return HTMLFormField subclass
171 static function loadInputFromParameters( $fieldname, $descriptor ) {
172 if ( isset( $descriptor['class'] ) ) {
173 $class = $descriptor['class'];
174 } elseif ( isset( $descriptor['type'] ) ) {
175 $class = self
::$typeMappings[$descriptor['type']];
176 $descriptor['class'] = $class;
180 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
183 $descriptor['fieldname'] = $fieldname;
185 $obj = new $class( $descriptor );
191 * Prepare form for submission
193 function prepareForm() {
194 # Check if we have the info we need
195 if ( ! $this->mTitle
) {
196 throw new MWException( "You must call setTitle() on an HTMLForm" );
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 ( $this->getMethod() != 'post' ||
$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, $section = null ) {
307 if ( is_null( $section ) ) {
308 $this->mHeader
.= $msg;
310 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
311 $this->mSectionHeaders
[$section] = '';
313 $this->mSectionHeaders
[$section] .= $msg;
318 * Add footer text, inside the form.
319 * @param $msg String complete text of message to display
321 function addFooterText( $msg, $section = null ) {
322 if ( is_null( $section ) ) {
323 $this->mFooter
.= $msg;
325 if ( !isset( $this->mSectionFooters
[$section] ) ) {
326 $this->mSectionFooters
[$section] = '';
328 $this->mSectionFooters
[$section] .= $msg;
333 * Add text to the end of the display.
334 * @param $msg String complete text of message to display
336 function addPostText( $msg ) { $this->mPost
.= $msg; }
339 * Add a hidden field to the output
340 * @param $name String field name. This will be used exactly as entered
341 * @param $value String field value
342 * @param $attribs Array
344 public function addHiddenField( $name, $value, $attribs = array() ) {
345 $attribs +
= array( 'name' => $name );
346 $this->mHiddenFields
[] = array( $value, $attribs );
349 public function addButton( $name, $value, $id = null, $attribs = null ) {
350 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
354 * Display the form (sending to wgOut), with an appropriate error
355 * message or stack of messages, and any validation errors, etc.
356 * @param $submitResult Mixed output from HTMLForm::trySubmit()
358 function displayForm( $submitResult ) {
361 # For good measure (it is the default)
362 $wgOut->preventClickjacking();
363 $wgOut->addModules( 'mediawiki.htmlform' );
366 . $this->getErrors( $submitResult )
369 . $this->getHiddenFields()
370 . $this->getButtons()
374 $html = $this->wrapForm( $html );
384 * Wrap the form innards in an actual <form> element
385 * @param $html String HTML contents to wrap.
386 * @return String wrapped HTML.
388 function wrapForm( $html ) {
390 # Include a <fieldset> wrapper for style, if requested.
391 if ( $this->mWrapperLegend
!== false ) {
392 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
394 # Use multipart/form-data
395 $encType = $this->mUseMultipart
396 ?
'multipart/form-data'
397 : 'application/x-www-form-urlencoded';
400 'action' => $this->getTitle()->getFullURL(),
401 'method' => $this->mMethod
,
402 'class' => 'visualClear',
403 'enctype' => $encType,
405 if ( !empty( $this->mId
) ) {
406 $attribs['id'] = $this->mId
;
409 return Html
::rawElement( 'form', $attribs, $html );
413 * Get the hidden fields that should go inside the form.
414 * @return String HTML.
416 function getHiddenFields() {
420 if( $this->getMethod() == 'post' ){
421 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
422 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
425 foreach ( $this->mHiddenFields
as $data ) {
426 list( $value, $attribs ) = $data;
427 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
434 * Get the submit and (potentially) reset buttons.
435 * @return String HTML.
437 function getButtons() {
441 if ( isset( $this->mSubmitID
) ) {
442 $attribs['id'] = $this->mSubmitID
;
445 if ( isset( $this->mSubmitName
) ) {
446 $attribs['name'] = $this->mSubmitName
;
449 if ( isset( $this->mSubmitTooltip
) ) {
451 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
454 $attribs['class'] = 'mw-htmlform-submit';
456 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
458 if ( $this->mShowReset
) {
459 $html .= Html
::element(
463 'value' => wfMsg( 'htmlform-reset' )
468 foreach ( $this->mButtons
as $button ) {
471 'name' => $button['name'],
472 'value' => $button['value']
475 if ( $button['attribs'] ) {
476 $attrs +
= $button['attribs'];
479 if ( isset( $button['id'] ) ) {
480 $attrs['id'] = $button['id'];
483 $html .= Html
::element( 'input', $attrs );
490 * Get the whole body of the form.
493 return $this->displaySection( $this->mFieldTree
);
497 * Format and display an error message stack.
498 * @param $errors Mixed String or Array of message keys
501 function getErrors( $errors ) {
502 if ( $errors instanceof Status
) {
504 if ( $errors->isOK() ) {
507 $errorstr = $wgOut->parse( $errors->getWikiText() );
509 } elseif ( is_array( $errors ) ) {
510 $errorstr = $this->formatErrors( $errors );
516 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
521 * Format a stack of error messages into a single HTML string
522 * @param $errors Array of message keys/values
523 * @return String HTML, a <ul> list of errors
525 static function formatErrors( $errors ) {
528 foreach ( $errors as $error ) {
529 if ( is_array( $error ) ) {
530 $msg = array_shift( $error );
536 $errorstr .= Html
::rawElement(
539 wfMsgExt( $msg, array( 'parseinline' ), $error )
543 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
549 * Set the text for the submit button
550 * @param $t String plaintext.
552 function setSubmitText( $t ) {
553 $this->mSubmitText
= $t;
557 * Get the text for the submit button, either customised or a default.
558 * @return unknown_type
560 function getSubmitText() {
561 return $this->mSubmitText
563 : wfMsg( 'htmlform-submit' );
566 public function setSubmitName( $name ) {
567 $this->mSubmitName
= $name;
570 public function setSubmitTooltip( $name ) {
571 $this->mSubmitTooltip
= $name;
575 * Set the id for the submit button.
576 * @param $t String. FIXME: Integrity is *not* validated
578 function setSubmitID( $t ) {
579 $this->mSubmitID
= $t;
582 public function setId( $id ) {
586 * Prompt the whole form to be wrapped in a <fieldset>, with
587 * this text as its <legend> element.
588 * @param $legend String HTML to go inside the <legend> element.
591 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
594 * Set the prefix for various default messages
595 * TODO: currently only used for the <fieldset> legend on forms
596 * with multiple sections; should be used elsewhre?
599 function setMessagePrefix( $p ) {
600 $this->mMessagePrefix
= $p;
604 * Set the title for form submission
605 * @param $t Title of page the form is on/should be posted to
607 function setTitle( $t ) {
615 function getTitle() {
616 return $this->mTitle
;
620 * Set the method used to submit the form
621 * @param $method String
623 public function setMethod( $method='post' ){
624 $this->mMethod
= $method;
627 public function getMethod(){
628 return $this->mMethod
;
635 function displaySection( $fields, $sectionName = '' ) {
637 $subsectionHtml = '';
638 $hasLeftColumn = false;
640 foreach ( $fields as $key => $value ) {
641 if ( is_object( $value ) ) {
642 $v = empty( $value->mParams
['nodata'] )
643 ?
$this->mFieldData
[$key]
644 : $value->getDefault();
645 $tableHtml .= $value->getTableRow( $v );
647 if ( $value->getLabel() != ' ' )
648 $hasLeftColumn = true;
649 } elseif ( is_array( $value ) ) {
650 $section = $this->displaySection( $value, $key );
651 $legend = $this->getLegend( $key );
652 if ( isset( $this->mSectionHeaders
[$key] ) ) {
653 $section = $this->mSectionHeaders
[$key] . $section;
655 if ( isset( $this->mSectionFooters
[$key] ) ) {
656 $section .= $this->mSectionFooters
[$key];
658 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
664 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
665 $classes[] = 'mw-htmlform-nolabel';
669 'class' => implode( ' ', $classes ),
672 if ( $sectionName ) {
673 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
676 $tableHtml = Html
::rawElement( 'table', $attribs,
677 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
679 return $subsectionHtml . "\n" . $tableHtml;
683 * Construct the form fields from the Descriptor array
685 function loadData() {
688 $fieldData = array();
690 foreach ( $this->mFlatFields
as $fieldname => $field ) {
691 if ( !empty( $field->mParams
['nodata'] ) ) {
693 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
694 $fieldData[$fieldname] = $field->getDefault();
696 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
701 foreach ( $fieldData as $name => &$value ) {
702 $field = $this->mFlatFields
[$name];
703 $value = $field->filter( $value, $this->mFlatFields
);
706 $this->mFieldData
= $fieldData;
710 * Stop a reset button being shown for this form
711 * @param $suppressReset Bool set to false to re-enable the
714 function suppressReset( $suppressReset = true ) {
715 $this->mShowReset
= !$suppressReset;
719 * Overload this if you want to apply special filtration routines
720 * to the form as a whole, after it's submitted but before it's
723 * @return unknown_type
725 function filterDataForSubmit( $data ) {
730 * Get a string to go in the <legend> of a section fieldset. Override this if you
731 * want something more complicated
735 public function getLegend( $key ) {
736 return wfMsg( "{$this->mMessagePrefix}-$key" );
741 * The parent class to generate form fields. Any field type should
742 * be a subclass of this.
744 abstract class HTMLFormField
{
746 protected $mValidationCallback;
747 protected $mFilterCallback;
750 protected $mLabel; # String label. Set on construction
752 protected $mClass = '';
757 * This function must be implemented to return the HTML to generate
758 * the input object itself. It should not implement the surrounding
759 * table cells/rows, or labels/help messages.
760 * @param $value String the value to set the input to; eg a default
761 * text for a text input.
762 * @return String valid HTML.
764 abstract function getInputHTML( $value );
767 * Override this function to add specific validation checks on the
768 * field input. Don't forget to call parent::validate() to ensure
769 * that the user-defined callback mValidationCallback is still run
770 * @param $value String the value the field was submitted with
771 * @param $alldata Array the data collected from the form
772 * @return Mixed Bool true on success, or String error to display.
774 function validate( $value, $alldata ) {
775 if ( isset( $this->mValidationCallback
) ) {
776 return call_user_func( $this->mValidationCallback
, $value, $alldata );
779 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
780 return wfMsgExt( 'htmlform-required', 'parseinline' );
786 function filter( $value, $alldata ) {
787 if ( isset( $this->mFilterCallback
) ) {
788 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
795 * Should this field have a label, or is there no input element with the
796 * appropriate id for the label to point to?
798 * @return bool True to output a label, false to suppress
800 protected function needsLabel() {
805 * Get the value that this input has been set to from a posted form,
806 * or the input's default value if it has not been set.
807 * @param $request WebRequest
808 * @return String the value
810 function loadDataFromRequest( $request ) {
811 if ( $request->getCheck( $this->mName
) ) {
812 return $request->getText( $this->mName
);
814 return $this->getDefault();
819 * Initialise the object
820 * @param $params Associative Array. See HTMLForm doc for syntax.
822 function __construct( $params ) {
823 $this->mParams
= $params;
825 # Generate the label from a message, if possible
826 if ( isset( $params['label-message'] ) ) {
827 $msgInfo = $params['label-message'];
829 if ( is_array( $msgInfo ) ) {
830 $msg = array_shift( $msgInfo );
836 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
837 } elseif ( isset( $params['label'] ) ) {
838 $this->mLabel
= $params['label'];
841 $this->mName
= "wp{$params['fieldname']}";
842 if ( isset( $params['name'] ) ) {
843 $this->mName
= $params['name'];
846 $validName = Sanitizer
::escapeId( $this->mName
);
847 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
848 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
851 $this->mID
= "mw-input-{$this->mName}";
853 if ( isset( $params['default'] ) ) {
854 $this->mDefault
= $params['default'];
857 if ( isset( $params['id'] ) ) {
859 $validId = Sanitizer
::escapeId( $id );
861 if ( $id != $validId ) {
862 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
868 if ( isset( $params['cssclass'] ) ) {
869 $this->mClass
= $params['cssclass'];
872 if ( isset( $params['validation-callback'] ) ) {
873 $this->mValidationCallback
= $params['validation-callback'];
876 if ( isset( $params['filter-callback'] ) ) {
877 $this->mFilterCallback
= $params['filter-callback'];
882 * Get the complete table row for the input, including help text,
883 * labels, and whatever.
884 * @param $value String the value to set the input to.
885 * @return String complete HTML table row.
887 function getTableRow( $value ) {
888 # Check for invalid data.
891 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
893 $cellAttributes = array();
894 $verticalLabel = false;
896 if ( !empty($this->mParams
['vertical-label']) ) {
897 $cellAttributes['colspan'] = 2;
898 $verticalLabel = true;
901 if ( $errors === true ||
( !$wgRequest->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
905 $errors = self
::formatErrors( $errors );
906 $errorClass = 'mw-htmlform-invalid-input';
909 $label = $this->getLabelHtml( $cellAttributes );
910 $field = Html
::rawElement(
912 array( 'class' => 'mw-input' ) +
$cellAttributes,
913 $this->getInputHTML( $value ) . "\n$errors"
916 $fieldType = get_class( $this );
918 if ( $verticalLabel ) {
919 $html = Html
::rawElement( 'tr',
920 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
921 $html .= Html
::rawElement( 'tr',
922 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
925 $html = Html
::rawElement( 'tr',
926 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
932 if ( isset( $this->mParams
['help-message'] ) ) {
933 $msg = $this->mParams
['help-message'];
934 $helptext = wfMsgExt( $msg, 'parseinline' );
935 if ( wfEmptyMsg( $msg ) ) {
939 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
940 # help-message can be passed a message key (string) or an array containing
941 # a message key and additional parameters. This makes it impossible to pass
942 # an array of message key
943 foreach( $this->mParams
['help-messages'] as $msg ) {
944 $candidate = wfMsgExt( $msg, 'parseinline' );
945 if( wfEmptyMsg( $msg ) ) {
948 $helptext .= $candidate; // append message
950 } elseif ( isset( $this->mParams
['help'] ) ) {
951 $helptext = $this->mParams
['help'];
954 if ( !is_null( $helptext ) ) {
955 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
957 $row = Html
::rawElement( 'tr', array(), $row );
964 function getLabel() {
965 return $this->mLabel
;
967 function getLabelHtml( $cellAttributes = array() ) {
968 # Don't output a for= attribute for labels with no associated input.
969 # Kind of hacky here, possibly we don't want these to be <label>s at all.
972 if ( $this->needsLabel() ) {
973 $for['for'] = $this->mID
;
976 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
977 Html
::rawElement( 'label', $for, $this->getLabel() )
981 function getDefault() {
982 if ( isset( $this->mDefault
) ) {
983 return $this->mDefault
;
990 * Returns the attributes required for the tooltip and accesskey.
992 * @return array Attributes
994 public function getTooltipAndAccessKey() {
995 if ( empty( $this->mParams
['tooltip'] ) ) {
1001 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
1005 * flatten an array of options to a single array, for instance,
1006 * a set of <options> inside <optgroups>.
1007 * @param $options Associative Array with values either Strings
1009 * @return Array flattened input
1011 public static function flattenOptions( $options ) {
1012 $flatOpts = array();
1014 foreach ( $options as $value ) {
1015 if ( is_array( $value ) ) {
1016 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1018 $flatOpts[] = $value;
1026 * Formats one or more errors as accepted by field validation-callback.
1027 * @param $errors String|Message|Array of strings or Message instances
1028 * @return String html
1031 protected static function formatErrors( $errors ) {
1032 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1033 $errors = array_shift( $errors );
1036 if ( is_array( $errors ) ) {
1038 foreach ( $errors as $error ) {
1039 if ( $error instanceof Message
) {
1040 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1042 $lines[] = Html
::rawElement( 'li', array(), $error );
1045 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1047 if ( $errors instanceof Message
) {
1048 $errors = $errors->parse();
1050 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1055 class HTMLTextField
extends HTMLFormField
{
1056 function getSize() {
1057 return isset( $this->mParams
['size'] )
1058 ?
$this->mParams
['size']
1062 function getInputHTML( $value ) {
1065 'name' => $this->mName
,
1066 'size' => $this->getSize(),
1068 ) +
$this->getTooltipAndAccessKey();
1070 if ( isset( $this->mParams
['maxlength'] ) ) {
1071 $attribs['maxlength'] = $this->mParams
['maxlength'];
1074 if ( !empty( $this->mParams
['disabled'] ) ) {
1075 $attribs['disabled'] = 'disabled';
1078 # TODO: Enforce pattern, step, required, readonly on the server side as
1080 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1081 'placeholder' ) as $param ) {
1082 if ( isset( $this->mParams
[$param] ) ) {
1083 $attribs[$param] = $this->mParams
[$param];
1087 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1088 if ( isset( $this->mParams
[$param] ) ) {
1089 $attribs[$param] = '';
1093 # Implement tiny differences between some field variants
1094 # here, rather than creating a new class for each one which
1095 # is essentially just a clone of this one.
1096 if ( isset( $this->mParams
['type'] ) ) {
1097 switch ( $this->mParams
['type'] ) {
1099 $attribs['type'] = 'email';
1102 $attribs['type'] = 'number';
1105 $attribs['type'] = 'number';
1106 $attribs['step'] = 'any';
1111 $attribs['type'] = $this->mParams
['type'];
1116 return Html
::element( 'input', $attribs );
1119 class HTMLTextAreaField
extends HTMLFormField
{
1120 function getCols() {
1121 return isset( $this->mParams
['cols'] )
1122 ?
$this->mParams
['cols']
1126 function getRows() {
1127 return isset( $this->mParams
['rows'] )
1128 ?
$this->mParams
['rows']
1132 function getInputHTML( $value ) {
1135 'name' => $this->mName
,
1136 'cols' => $this->getCols(),
1137 'rows' => $this->getRows(),
1138 ) +
$this->getTooltipAndAccessKey();
1141 if ( !empty( $this->mParams
['disabled'] ) ) {
1142 $attribs['disabled'] = 'disabled';
1145 if ( !empty( $this->mParams
['readonly'] ) ) {
1146 $attribs['readonly'] = 'readonly';
1149 foreach ( array( 'required', 'autofocus' ) as $param ) {
1150 if ( isset( $this->mParams
[$param] ) ) {
1151 $attribs[$param] = '';
1155 return Html
::element( 'textarea', $attribs, $value );
1160 * A field that will contain a numeric value
1162 class HTMLFloatField
extends HTMLTextField
{
1163 function getSize() {
1164 return isset( $this->mParams
['size'] )
1165 ?
$this->mParams
['size']
1169 function validate( $value, $alldata ) {
1170 $p = parent
::validate( $value, $alldata );
1172 if ( $p !== true ) {
1176 $value = trim( $value );
1178 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1179 # with the addition that a leading '+' sign is ok.
1180 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1181 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1184 # The "int" part of these message names is rather confusing.
1185 # They make equal sense for all numbers.
1186 if ( isset( $this->mParams
['min'] ) ) {
1187 $min = $this->mParams
['min'];
1189 if ( $min > $value ) {
1190 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1194 if ( isset( $this->mParams
['max'] ) ) {
1195 $max = $this->mParams
['max'];
1197 if ( $max < $value ) {
1198 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1207 * A field that must contain a number
1209 class HTMLIntField
extends HTMLFloatField
{
1210 function validate( $value, $alldata ) {
1211 $p = parent
::validate( $value, $alldata );
1213 if ( $p !== true ) {
1217 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1218 # with the addition that a leading '+' sign is ok. Note that leading zeros
1219 # are fine, and will be left in the input, which is useful for things like
1220 # phone numbers when you know that they are integers (the HTML5 type=tel
1221 # input does not require its value to be numeric). If you want a tidier
1222 # value to, eg, save in the DB, clean it up with intval().
1223 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1225 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1235 class HTMLCheckField
extends HTMLFormField
{
1236 function getInputHTML( $value ) {
1237 if ( !empty( $this->mParams
['invert'] ) ) {
1241 $attr = $this->getTooltipAndAccessKey();
1242 $attr['id'] = $this->mID
;
1244 if ( !empty( $this->mParams
['disabled'] ) ) {
1245 $attr['disabled'] = 'disabled';
1248 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1249 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1253 * For a checkbox, the label goes on the right hand side, and is
1254 * added in getInputHTML(), rather than HTMLFormField::getRow()
1256 function getLabel() {
1260 function loadDataFromRequest( $request ) {
1262 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1266 // GetCheck won't work like we want for checks.
1267 if ( $request->getCheck( 'wpEditToken' ) ) {
1268 // XOR has the following truth table, which is what we want
1269 // INVERT VALUE | OUTPUT
1270 // true true | false
1271 // false true | true
1272 // false false | false
1273 // true false | true
1274 return $request->getBool( $this->mName
) xor $invert;
1276 return $this->getDefault();
1282 * A select dropdown field. Basically a wrapper for Xmlselect class
1284 class HTMLSelectField
extends HTMLFormField
{
1285 function validate( $value, $alldata ) {
1286 $p = parent
::validate( $value, $alldata );
1288 if ( $p !== true ) {
1292 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1294 if ( in_array( $value, $validOptions ) )
1297 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1300 function getInputHTML( $value ) {
1301 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1303 # If one of the options' 'name' is int(0), it is automatically selected.
1304 # because PHP sucks and things int(0) == 'some string'.
1305 # Working around this by forcing all of them to strings.
1306 foreach( $this->mParams
['options'] as $key => &$opt ){
1307 if( is_int( $opt ) ){
1308 $opt = strval( $opt );
1311 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1313 if ( !empty( $this->mParams
['disabled'] ) ) {
1314 $select->setAttribute( 'disabled', 'disabled' );
1317 $select->addOptions( $this->mParams
['options'] );
1319 return $select->getHTML();
1324 * Select dropdown field, with an additional "other" textbox.
1326 class HTMLSelectOrOtherField
extends HTMLTextField
{
1327 static $jsAdded = false;
1329 function __construct( $params ) {
1330 if ( !in_array( 'other', $params['options'], true ) ) {
1331 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1334 parent
::__construct( $params );
1337 static function forceToStringRecursive( $array ) {
1338 if ( is_array( $array ) ) {
1339 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1341 return strval( $array );
1345 function getInputHTML( $value ) {
1346 $valInSelect = false;
1348 if ( $value !== false ) {
1349 $valInSelect = in_array(
1351 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1355 $selected = $valInSelect ?
$value : 'other';
1357 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1359 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1360 $select->addOptions( $opts );
1362 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1364 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1366 if ( !empty( $this->mParams
['disabled'] ) ) {
1367 $select->setAttribute( 'disabled', 'disabled' );
1368 $tbAttribs['disabled'] = 'disabled';
1371 $select = $select->getHTML();
1373 if ( isset( $this->mParams
['maxlength'] ) ) {
1374 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1377 $textbox = Html
::input(
1378 $this->mName
. '-other',
1379 $valInSelect ?
'' : $value,
1384 return "$select<br />\n$textbox";
1387 function loadDataFromRequest( $request ) {
1388 if ( $request->getCheck( $this->mName
) ) {
1389 $val = $request->getText( $this->mName
);
1391 if ( $val == 'other' ) {
1392 $val = $request->getText( $this->mName
. '-other' );
1397 return $this->getDefault();
1403 * Multi-select field
1405 class HTMLMultiSelectField
extends HTMLFormField
{
1406 function validate( $value, $alldata ) {
1407 $p = parent
::validate( $value, $alldata );
1409 if ( $p !== true ) {
1413 if ( !is_array( $value ) ) {
1417 # If all options are valid, array_intersect of the valid options
1418 # and the provided options will return the provided options.
1419 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1421 $validValues = array_intersect( $value, $validOptions );
1422 if ( count( $validValues ) == count( $value ) ) {
1425 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1429 function getInputHTML( $value ) {
1430 $html = $this->formatOptions( $this->mParams
['options'], $value );
1435 function formatOptions( $options, $value ) {
1440 if ( !empty( $this->mParams
['disabled'] ) ) {
1441 $attribs['disabled'] = 'disabled';
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 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1451 $checkbox = Xml
::check(
1452 $this->mName
. '[]',
1453 in_array( $info, $value, true ),
1454 $attribs +
$thisAttribs );
1455 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1457 $html .= Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1464 function loadDataFromRequest( $request ) {
1465 if ( $this->mParent
->getMethod() == 'post' ) {
1466 if( $request->wasPosted() ){
1467 # Checkboxes are just not added to the request arrays if they're not checked,
1468 # so it's perfectly possible for there not to be an entry at all
1469 return $request->getArray( $this->mName
, array() );
1471 # That's ok, the user has not yet submitted the form, so show the defaults
1472 return $this->getDefault();
1475 # This is the impossible case: if we look at $_GET and see no data for our
1476 # field, is it because the user has not yet submitted the form, or that they
1477 # have submitted it with all the options unchecked? We will have to assume the
1478 # latter, which basically means that you can't specify 'positive' defaults
1479 # for GET forms. FIXME...
1480 return $request->getArray( $this->mName
, array() );
1484 function getDefault() {
1485 if ( isset( $this->mDefault
) ) {
1486 return $this->mDefault
;
1492 protected function needsLabel() {
1498 * Double field with a dropdown list constructed from a system message in the format
1500 * ** <option value>|<option name>
1501 * ** <option value == option name>
1502 * * New Optgroup header
1503 * Plus a text field underneath for an additional reason. The 'value' of the field is
1504 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1506 * FIXME: If made 'required', only the text field should be compulsory.
1508 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1510 function __construct( $params ) {
1511 if ( array_key_exists( 'other', $params ) ) {
1512 } elseif( array_key_exists( 'other-message', $params ) ){
1513 $params['other'] = wfMsg( $params['other-message'] );
1515 $params['other'] = wfMsg( 'htmlform-selectorother-other' );
1518 if ( array_key_exists( 'options', $params ) ) {
1519 # Options array already specified
1520 } elseif( array_key_exists( 'options-message', $params ) ){
1521 # Generate options array from a system message
1522 $params['options'] = self
::parseMessage( wfMsg( $params['options-message'], $params['other'] ) );
1525 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1527 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1529 parent
::__construct( $params );
1533 * Build a drop-down box from a textual list.
1534 * @param $string String message text
1535 * @param $otherName String name of "other reason" option
1537 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1539 public static function parseMessage( $string, $otherName=null ) {
1540 if( $otherName === null ){
1541 $otherName = wfMsg( 'htmlform-selectorother-other' );
1545 $options = array( $otherName => 'other' );
1547 foreach ( explode( "\n", $string ) as $option ) {
1548 $value = trim( $option );
1549 if ( $value == '' ) {
1551 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1552 # A new group is starting...
1553 $value = trim( substr( $value, 1 ) );
1555 } elseif ( substr( $value, 0, 2) == '**' ) {
1557 $opt = trim( substr( $value, 2 ) );
1558 $parts = array_map( 'trim', explode( '|', $opt, 2 ) );
1559 if( count( $parts ) === 1 ){
1560 $parts[1] = $parts[0];
1562 if( $optgroup === false ){
1563 $options[$parts[1]] = $parts[0];
1565 $options[$optgroup][$parts[1]] = $parts[0];
1568 # groupless reason list
1570 $parts = array_map( 'trim', explode( '|', $opt, 2 ) );
1571 if( count( $parts ) === 1 ){
1572 $parts[1] = $parts[0];
1574 $options[$parts[1]] = $parts[0];
1581 function getInputHTML( $value ) {
1582 $select = parent
::getInputHTML( $value[1] );
1584 $textAttribs = array(
1585 'id' => $this->mID
. '-other',
1586 'size' => $this->getSize(),
1589 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1590 if ( isset( $this->mParams
[$param] ) ) {
1591 $textAttribs[$param] = '';
1595 $textbox = Html
::input(
1596 $this->mName
. '-other',
1602 return "$select<br />\n$textbox";
1606 * @param $request WebRequest
1607 * @return Array( <overall message>, <select value>, <text field value> )
1609 function loadDataFromRequest( $request ) {
1610 if ( $request->getCheck( $this->mName
) ) {
1612 $list = $request->getText( $this->mName
);
1613 $text = $request->getText( $this->mName
. '-other' );
1615 if ( $list == 'other' ) {
1617 } elseif( !in_array( $list, $this->mFlatOptions
) ){
1618 # User has spoofed the select form to give an option which wasn't
1619 # in the original offer. Sulk...
1621 } elseif( $text == '' ) {
1624 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1628 $final = $this->getDefault();
1631 return array( $final, $list, $text );
1634 function getSize() {
1635 return isset( $this->mParams
['size'] )
1636 ?
$this->mParams
['size']
1640 function validate( $value, $alldata ) {
1641 # HTMLSelectField forces $value to be one of the options in the select
1642 # field, which is not useful here. But we do want the validation further up
1644 $p = parent
::validate( $value[1], $alldata );
1646 if ( $p !== true ) {
1650 if( isset( $this->mParams
['required'] ) && $value[1] === '' ){
1651 return wfMsgExt( 'htmlform-required', 'parseinline' );
1659 * Radio checkbox fields.
1661 class HTMLRadioField
extends HTMLFormField
{
1662 function validate( $value, $alldata ) {
1663 $p = parent
::validate( $value, $alldata );
1665 if ( $p !== true ) {
1669 if ( !is_string( $value ) && !is_int( $value ) ) {
1673 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1675 if ( in_array( $value, $validOptions ) ) {
1678 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1683 * This returns a block of all the radio options, in one cell.
1684 * @see includes/HTMLFormField#getInputHTML()
1686 function getInputHTML( $value ) {
1687 $html = $this->formatOptions( $this->mParams
['options'], $value );
1692 function formatOptions( $options, $value ) {
1696 if ( !empty( $this->mParams
['disabled'] ) ) {
1697 $attribs['disabled'] = 'disabled';
1700 # TODO: should this produce an unordered list perhaps?
1701 foreach ( $options as $label => $info ) {
1702 if ( is_array( $info ) ) {
1703 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1704 $html .= $this->formatOptions( $info, $value );
1706 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1707 $html .= Xml
::radio(
1711 $attribs +
array( 'id' => $id )
1714 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1716 $html .= "<br />\n";
1723 protected function needsLabel() {
1729 * An information field (text blob), not a proper input.
1731 class HTMLInfoField
extends HTMLFormField
{
1732 function __construct( $info ) {
1733 $info['nodata'] = true;
1735 parent
::__construct( $info );
1738 function getInputHTML( $value ) {
1739 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1742 function getTableRow( $value ) {
1743 if ( !empty( $this->mParams
['rawrow'] ) ) {
1747 return parent
::getTableRow( $value );
1750 protected function needsLabel() {
1755 class HTMLHiddenField
extends HTMLFormField
{
1756 public function __construct( $params ) {
1757 parent
::__construct( $params );
1759 # Per HTML5 spec, hidden fields cannot be 'required'
1760 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1761 unset( $this->mParams
['required'] );
1764 public function getTableRow( $value ) {
1767 $params['id'] = $this->mID
;
1770 $this->mParent
->addHiddenField(
1779 public function getInputHTML( $value ) { return ''; }
1783 * Add a submit button inline in the form (as opposed to
1784 * HTMLForm::addButton(), which will add it at the end).
1786 class HTMLSubmitField
extends HTMLFormField
{
1788 function __construct( $info ) {
1789 $info['nodata'] = true;
1790 parent
::__construct( $info );
1793 function getInputHTML( $value ) {
1794 return Xml
::submitButton(
1797 'class' => 'mw-htmlform-submit',
1798 'name' => $this->mName
,
1804 protected function needsLabel() {
1809 * Button cannot be invalid
1811 public function validate( $value, $alldata ){
1816 class HTMLEditTools
extends HTMLFormField
{
1817 public function getInputHTML( $value ) {
1821 public function getTableRow( $value ) {
1822 if ( empty( $this->mParams
['message'] ) ) {
1823 $msg = wfMessage( 'edittools' );
1825 $msg = wfMessage( $this->mParams
['message'] );
1826 if ( $msg->isDisabled() ) {
1827 $msg = wfMessage( 'edittools' );
1830 $msg->inContentLanguage();
1833 return '<tr><td></td><td class="mw-input">'
1834 . '<div class="mw-editTools">'
1835 . $msg->parseAsBlock()
1836 . "</div></td></tr>\n";