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;
85 /** @var HTMLFormField[] */
86 protected $mFlatFields;
88 protected $mFieldTree;
89 protected $mShowReset = false;
92 protected $mSubmitCallback;
93 protected $mValidationErrorMessage;
96 protected $mHeader = '';
97 protected $mFooter = '';
98 protected $mSectionHeaders = array();
99 protected $mSectionFooters = array();
100 protected $mPost = '';
103 protected $mSubmitID;
104 protected $mSubmitName;
105 protected $mSubmitText;
106 protected $mSubmitTooltip;
108 protected $mContext; // <! IContextSource
110 protected $mMethod = 'post';
112 protected $mUseMultipart = false;
113 protected $mHiddenFields = array();
114 protected $mButtons = array();
116 protected $mWrapperLegend = false;
119 * Build a new HTMLForm from an array of field attributes
120 * @param $descriptor Array of Field constructs, as described above
121 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
122 * Obviates the need to call $form->setTitle()
123 * @param $messagePrefix String a prefix to go in front of default messages
125 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
126 if( $context instanceof IContextSource
){
127 $this->mContext
= $context;
128 $this->mTitle
= false; // We don't need them to set a title
129 $this->mMessagePrefix
= $messagePrefix;
132 if( is_string( $context ) && $messagePrefix === '' ){
133 // it's actually $messagePrefix
134 $this->mMessagePrefix
= $context;
138 // Expand out into a tree.
139 $loadedDescriptor = array();
140 $this->mFlatFields
= array();
142 foreach ( $descriptor as $fieldname => $info ) {
143 $section = isset( $info['section'] )
147 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
148 $this->mUseMultipart
= true;
151 $field = self
::loadInputFromParameters( $fieldname, $info );
152 $field->mParent
= $this;
154 $setSection =& $loadedDescriptor;
156 $sectionParts = explode( '/', $section );
158 while ( count( $sectionParts ) ) {
159 $newName = array_shift( $sectionParts );
161 if ( !isset( $setSection[$newName] ) ) {
162 $setSection[$newName] = array();
165 $setSection =& $setSection[$newName];
169 $setSection[$fieldname] = $field;
170 $this->mFlatFields
[$fieldname] = $field;
173 $this->mFieldTree
= $loadedDescriptor;
177 * Add the HTMLForm-specific JavaScript, if it hasn't been
179 * @deprecated since 1.18 load modules with ResourceLoader instead
181 static function addJS() { }
184 * Initialise a new Object for the field
185 * @param $fieldname string
186 * @param $descriptor string input Descriptor, as described above
187 * @return HTMLFormField subclass
189 static function loadInputFromParameters( $fieldname, $descriptor ) {
190 if ( isset( $descriptor['class'] ) ) {
191 $class = $descriptor['class'];
192 } elseif ( isset( $descriptor['type'] ) ) {
193 $class = self
::$typeMappings[$descriptor['type']];
194 $descriptor['class'] = $class;
200 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
203 $descriptor['fieldname'] = $fieldname;
205 $obj = new $class( $descriptor );
211 * Prepare form for submission
213 function prepareForm() {
214 # Check if we have the info we need
215 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
216 throw new MWException( "You must call setTitle() on an HTMLForm" );
219 # Load data from the request.
224 * Try submitting, with edit token check first
225 * @return Status|boolean
227 function tryAuthorizedSubmit() {
228 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
231 if ( $this->getMethod() != 'post' ||
$this->getUser()->matchEditToken( $editToken ) ) {
232 $result = $this->trySubmit();
238 * The here's-one-I-made-earlier option: do the submission if
239 * posted, or display the form with or without funky valiation
241 * @return Bool or Status whether submission was successful.
244 $this->prepareForm();
246 $result = $this->tryAuthorizedSubmit();
247 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
251 $this->displayForm( $result );
256 * Validate all the fields, and call the submision callback
257 * function if everything is kosher.
258 * @return Mixed Bool true == Successful submission, Bool false
259 * == No submission attempted, anything else == Error to
262 function trySubmit() {
263 # Check for validation
264 foreach ( $this->mFlatFields
as $fieldname => $field ) {
265 if ( !empty( $field->mParams
['nodata'] ) ) {
268 if ( $field->validate(
269 $this->mFieldData
[$fieldname],
273 return isset( $this->mValidationErrorMessage
)
274 ?
$this->mValidationErrorMessage
275 : array( 'htmlform-invalid-input' );
279 $callback = $this->mSubmitCallback
;
281 $data = $this->filterDataForSubmit( $this->mFieldData
);
283 $res = call_user_func( $callback, $data, $this );
289 * Set a callback to a function to do something with the form
290 * once it's been successfully validated.
291 * @param $cb String function name. The function will be passed
292 * the output from HTMLForm::filterDataForSubmit, and must
293 * return Bool true on success, Bool false if no submission
294 * was attempted, or String HTML output to display on error.
296 function setSubmitCallback( $cb ) {
297 $this->mSubmitCallback
= $cb;
301 * Set a message to display on a validation error.
302 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
303 * (so each entry can be either a String or Array)
305 function setValidationErrorMessage( $msg ) {
306 $this->mValidationErrorMessage
= $msg;
310 * Set the introductory message, overwriting any existing message.
311 * @param $msg String complete text of message to display
313 function setIntro( $msg ) { $this->mPre
= $msg; }
316 * Add introductory text.
317 * @param $msg String complete text of message to display
319 function addPreText( $msg ) { $this->mPre
.= $msg; }
322 * Add header text, inside the form.
323 * @param $msg String complete text of message to display
324 * @param $section The section to add the header to
326 function addHeaderText( $msg, $section = null ) {
327 if ( is_null( $section ) ) {
328 $this->mHeader
.= $msg;
330 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
331 $this->mSectionHeaders
[$section] = '';
333 $this->mSectionHeaders
[$section] .= $msg;
338 * Add footer text, inside the form.
339 * @param $msg String complete text of message to display
340 * @param $section string The section to add the footer text to
342 function addFooterText( $msg, $section = null ) {
343 if ( is_null( $section ) ) {
344 $this->mFooter
.= $msg;
346 if ( !isset( $this->mSectionFooters
[$section] ) ) {
347 $this->mSectionFooters
[$section] = '';
349 $this->mSectionFooters
[$section] .= $msg;
354 * Add text to the end of the display.
355 * @param $msg String complete text of message to display
357 function addPostText( $msg ) { $this->mPost
.= $msg; }
360 * Add a hidden field to the output
361 * @param $name String field name. This will be used exactly as entered
362 * @param $value String field value
363 * @param $attribs Array
365 public function addHiddenField( $name, $value, $attribs = array() ) {
366 $attribs +
= array( 'name' => $name );
367 $this->mHiddenFields
[] = array( $value, $attribs );
370 public function addButton( $name, $value, $id = null, $attribs = null ) {
371 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
375 * Display the form (sending to wgOut), with an appropriate error
376 * message or stack of messages, and any validation errors, etc.
377 * @param $submitResult Mixed output from HTMLForm::trySubmit()
379 function displayForm( $submitResult ) {
380 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
384 * Returns the raw HTML generated by the form
385 * @param $submitResult Mixed output from HTMLForm::trySubmit()
388 function getHTML( $submitResult ) {
389 # For good measure (it is the default)
390 $this->getOutput()->preventClickjacking();
391 $this->getOutput()->addModules( 'mediawiki.htmlform' );
394 . $this->getErrors( $submitResult )
397 . $this->getHiddenFields()
398 . $this->getButtons()
402 $html = $this->wrapForm( $html );
404 return '' . $this->mPre
. $html . $this->mPost
;
408 * Wrap the form innards in an actual <form> element
409 * @param $html String HTML contents to wrap.
410 * @return String wrapped HTML.
412 function wrapForm( $html ) {
414 # Include a <fieldset> wrapper for style, if requested.
415 if ( $this->mWrapperLegend
!== false ) {
416 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
418 # Use multipart/form-data
419 $encType = $this->mUseMultipart
420 ?
'multipart/form-data'
421 : 'application/x-www-form-urlencoded';
424 'action' => $this->getTitle()->getFullURL(),
425 'method' => $this->mMethod
,
426 'class' => 'visualClear',
427 'enctype' => $encType,
429 if ( !empty( $this->mId
) ) {
430 $attribs['id'] = $this->mId
;
433 return Html
::rawElement( 'form', $attribs, $html );
437 * Get the hidden fields that should go inside the form.
438 * @return String HTML.
440 function getHiddenFields() {
441 global $wgUsePathInfo;
444 if( $this->getMethod() == 'post' ){
445 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
446 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
449 if ( !$wgUsePathInfo && $this->getMethod() == 'get' ) {
450 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
453 foreach ( $this->mHiddenFields
as $data ) {
454 list( $value, $attribs ) = $data;
455 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
462 * Get the submit and (potentially) reset buttons.
463 * @return String HTML.
465 function getButtons() {
469 if ( isset( $this->mSubmitID
) ) {
470 $attribs['id'] = $this->mSubmitID
;
473 if ( isset( $this->mSubmitName
) ) {
474 $attribs['name'] = $this->mSubmitName
;
477 if ( isset( $this->mSubmitTooltip
) ) {
478 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
481 $attribs['class'] = 'mw-htmlform-submit';
483 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
485 if ( $this->mShowReset
) {
486 $html .= Html
::element(
490 'value' => wfMsg( 'htmlform-reset' )
495 foreach ( $this->mButtons
as $button ) {
498 'name' => $button['name'],
499 'value' => $button['value']
502 if ( $button['attribs'] ) {
503 $attrs +
= $button['attribs'];
506 if ( isset( $button['id'] ) ) {
507 $attrs['id'] = $button['id'];
510 $html .= Html
::element( 'input', $attrs );
517 * Get the whole body of the form.
521 return $this->displaySection( $this->mFieldTree
);
525 * Format and display an error message stack.
526 * @param $errors String|Array|Status
529 function getErrors( $errors ) {
530 if ( $errors instanceof Status
) {
531 if ( $errors->isOK() ) {
534 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
536 } elseif ( is_array( $errors ) ) {
537 $errorstr = $this->formatErrors( $errors );
543 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
548 * Format a stack of error messages into a single HTML string
549 * @param $errors Array of message keys/values
550 * @return String HTML, a <ul> list of errors
552 public static function formatErrors( $errors ) {
555 foreach ( $errors as $error ) {
556 if ( is_array( $error ) ) {
557 $msg = array_shift( $error );
563 $errorstr .= Html
::rawElement(
566 wfMsgExt( $msg, array( 'parseinline' ), $error )
570 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
576 * Set the text for the submit button
577 * @param $t String plaintext.
579 function setSubmitText( $t ) {
580 $this->mSubmitText
= $t;
584 * Get the text for the submit button, either customised or a default.
585 * @return unknown_type
587 function getSubmitText() {
588 return $this->mSubmitText
590 : wfMsg( 'htmlform-submit' );
593 public function setSubmitName( $name ) {
594 $this->mSubmitName
= $name;
597 public function setSubmitTooltip( $name ) {
598 $this->mSubmitTooltip
= $name;
602 * Set the id for the submit button.
604 * @todo FIXME: Integrity of $t is *not* validated
606 function setSubmitID( $t ) {
607 $this->mSubmitID
= $t;
610 public function setId( $id ) {
614 * Prompt the whole form to be wrapped in a <fieldset>, with
615 * this text as its <legend> element.
616 * @param $legend String HTML to go inside the <legend> element.
619 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
622 * Set the prefix for various default messages
623 * TODO: currently only used for the <fieldset> legend on forms
624 * with multiple sections; should be used elsewhre?
627 function setMessagePrefix( $p ) {
628 $this->mMessagePrefix
= $p;
632 * Set the title for form submission
633 * @param $t Title of page the form is on/should be posted to
635 function setTitle( $t ) {
643 function getTitle() {
644 return $this->mTitle
=== false
645 ?
$this->getContext()->getTitle()
650 * @return IContextSource
652 public function getContext(){
653 return $this->mContext
instanceof IContextSource
655 : RequestContext
::getMain();
661 public function getOutput(){
662 return $this->getContext()->getOutput();
668 public function getRequest(){
669 return $this->getContext()->getRequest();
675 public function getUser(){
676 return $this->getContext()->getUser();
680 * Set the method used to submit the form
681 * @param $method String
683 public function setMethod( $method='post' ){
684 $this->mMethod
= $method;
687 public function getMethod(){
688 return $this->mMethod
;
693 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
694 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
695 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
698 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
700 $subsectionHtml = '';
701 $hasLeftColumn = false;
703 foreach ( $fields as $key => $value ) {
704 if ( is_object( $value ) ) {
705 $v = empty( $value->mParams
['nodata'] )
706 ?
$this->mFieldData
[$key]
707 : $value->getDefault();
708 $tableHtml .= $value->getTableRow( $v );
710 if ( $value->getLabel() != ' ' ) {
711 $hasLeftColumn = true;
713 } elseif ( is_array( $value ) ) {
714 $section = $this->displaySection( $value, $key );
715 $legend = $this->getLegend( $key );
716 if ( isset( $this->mSectionHeaders
[$key] ) ) {
717 $section = $this->mSectionHeaders
[$key] . $section;
719 if ( isset( $this->mSectionFooters
[$key] ) ) {
720 $section .= $this->mSectionFooters
[$key];
722 $attributes = array();
723 if ( $fieldsetIDPrefix ) {
724 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
726 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
732 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
733 $classes[] = 'mw-htmlform-nolabel';
737 'class' => implode( ' ', $classes ),
740 if ( $sectionName ) {
741 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
744 $tableHtml = Html
::rawElement( 'table', $attribs,
745 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
747 return $subsectionHtml . "\n" . $tableHtml;
751 * Construct the form fields from the Descriptor array
753 function loadData() {
754 $fieldData = array();
756 foreach ( $this->mFlatFields
as $fieldname => $field ) {
757 if ( !empty( $field->mParams
['nodata'] ) ) {
759 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
760 $fieldData[$fieldname] = $field->getDefault();
762 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
767 foreach ( $fieldData as $name => &$value ) {
768 $field = $this->mFlatFields
[$name];
769 $value = $field->filter( $value, $this->mFlatFields
);
772 $this->mFieldData
= $fieldData;
776 * Stop a reset button being shown for this form
777 * @param $suppressReset Bool set to false to re-enable the
780 function suppressReset( $suppressReset = true ) {
781 $this->mShowReset
= !$suppressReset;
785 * Overload this if you want to apply special filtration routines
786 * to the form as a whole, after it's submitted but before it's
789 * @return unknown_type
791 function filterDataForSubmit( $data ) {
796 * Get a string to go in the <legend> of a section fieldset. Override this if you
797 * want something more complicated
801 public function getLegend( $key ) {
802 return wfMsg( "{$this->mMessagePrefix}-$key" );
807 * The parent class to generate form fields. Any field type should
808 * be a subclass of this.
810 abstract class HTMLFormField
{
812 protected $mValidationCallback;
813 protected $mFilterCallback;
816 protected $mLabel; # String label. Set on construction
818 protected $mClass = '';
827 * This function must be implemented to return the HTML to generate
828 * the input object itself. It should not implement the surrounding
829 * table cells/rows, or labels/help messages.
830 * @param $value String the value to set the input to; eg a default
831 * text for a text input.
832 * @return String valid HTML.
834 abstract function getInputHTML( $value );
837 * Override this function to add specific validation checks on the
838 * field input. Don't forget to call parent::validate() to ensure
839 * that the user-defined callback mValidationCallback is still run
840 * @param $value String the value the field was submitted with
841 * @param $alldata Array the data collected from the form
842 * @return Mixed Bool true on success, or String error to display.
844 function validate( $value, $alldata ) {
845 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
846 return wfMsgExt( 'htmlform-required', 'parseinline' );
849 if ( isset( $this->mValidationCallback
) ) {
850 return call_user_func( $this->mValidationCallback
, $value, $alldata );
856 function filter( $value, $alldata ) {
857 if ( isset( $this->mFilterCallback
) ) {
858 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
865 * Should this field have a label, or is there no input element with the
866 * appropriate id for the label to point to?
868 * @return bool True to output a label, false to suppress
870 protected function needsLabel() {
875 * Get the value that this input has been set to from a posted form,
876 * or the input's default value if it has not been set.
877 * @param $request WebRequest
878 * @return String the value
880 function loadDataFromRequest( $request ) {
881 if ( $request->getCheck( $this->mName
) ) {
882 return $request->getText( $this->mName
);
884 return $this->getDefault();
889 * Initialise the object
890 * @param $params array Associative Array. See HTMLForm doc for syntax.
892 function __construct( $params ) {
893 $this->mParams
= $params;
895 # Generate the label from a message, if possible
896 if ( isset( $params['label-message'] ) ) {
897 $msgInfo = $params['label-message'];
899 if ( is_array( $msgInfo ) ) {
900 $msg = array_shift( $msgInfo );
906 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
907 } elseif ( isset( $params['label'] ) ) {
908 $this->mLabel
= $params['label'];
911 $this->mName
= "wp{$params['fieldname']}";
912 if ( isset( $params['name'] ) ) {
913 $this->mName
= $params['name'];
916 $validName = Sanitizer
::escapeId( $this->mName
);
917 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
918 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
921 $this->mID
= "mw-input-{$this->mName}";
923 if ( isset( $params['default'] ) ) {
924 $this->mDefault
= $params['default'];
927 if ( isset( $params['id'] ) ) {
929 $validId = Sanitizer
::escapeId( $id );
931 if ( $id != $validId ) {
932 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
938 if ( isset( $params['cssclass'] ) ) {
939 $this->mClass
= $params['cssclass'];
942 if ( isset( $params['validation-callback'] ) ) {
943 $this->mValidationCallback
= $params['validation-callback'];
946 if ( isset( $params['filter-callback'] ) ) {
947 $this->mFilterCallback
= $params['filter-callback'];
952 * Get the complete table row for the input, including help text,
953 * labels, and whatever.
954 * @param $value String the value to set the input to.
955 * @return String complete HTML table row.
957 function getTableRow( $value ) {
958 # Check for invalid data.
960 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
962 $cellAttributes = array();
963 $verticalLabel = false;
965 if ( !empty($this->mParams
['vertical-label']) ) {
966 $cellAttributes['colspan'] = 2;
967 $verticalLabel = true;
970 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
974 $errors = self
::formatErrors( $errors );
975 $errorClass = 'mw-htmlform-invalid-input';
978 $label = $this->getLabelHtml( $cellAttributes );
979 $field = Html
::rawElement(
981 array( 'class' => 'mw-input' ) +
$cellAttributes,
982 $this->getInputHTML( $value ) . "\n$errors"
985 $fieldType = get_class( $this );
987 if ( $verticalLabel ) {
988 $html = Html
::rawElement( 'tr',
989 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
990 $html .= Html
::rawElement( 'tr',
991 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
994 $html = Html
::rawElement( 'tr',
995 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1001 if ( isset( $this->mParams
['help-message'] ) ) {
1002 $msg = wfMessage( $this->mParams
['help-message'] );
1003 if ( $msg->exists() ) {
1004 $helptext = $msg->parse();
1006 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
1007 # help-message can be passed a message key (string) or an array containing
1008 # a message key and additional parameters. This makes it impossible to pass
1009 # an array of message key
1010 foreach( $this->mParams
['help-messages'] as $name ) {
1011 $msg = wfMessage( $name );
1012 if( $msg->exists() ) {
1013 $helptext .= $msg->parse(); // append message
1016 } elseif ( isset( $this->mParams
['help'] ) ) {
1017 $helptext = $this->mParams
['help'];
1020 if ( !is_null( $helptext ) ) {
1021 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1023 $row = Html
::rawElement( 'tr', array(), $row );
1030 function getLabel() {
1031 return $this->mLabel
;
1033 function getLabelHtml( $cellAttributes = array() ) {
1034 # Don't output a for= attribute for labels with no associated input.
1035 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1038 if ( $this->needsLabel() ) {
1039 $for['for'] = $this->mID
;
1042 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1043 Html
::rawElement( 'label', $for, $this->getLabel() )
1047 function getDefault() {
1048 if ( isset( $this->mDefault
) ) {
1049 return $this->mDefault
;
1056 * Returns the attributes required for the tooltip and accesskey.
1058 * @return array Attributes
1060 public function getTooltipAndAccessKey() {
1061 if ( empty( $this->mParams
['tooltip'] ) ) {
1064 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1068 * flatten an array of options to a single array, for instance,
1069 * a set of <options> inside <optgroups>.
1070 * @param $options Associative Array with values either Strings
1072 * @return Array flattened input
1074 public static function flattenOptions( $options ) {
1075 $flatOpts = array();
1077 foreach ( $options as $value ) {
1078 if ( is_array( $value ) ) {
1079 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1081 $flatOpts[] = $value;
1089 * Formats one or more errors as accepted by field validation-callback.
1090 * @param $errors String|Message|Array of strings or Message instances
1091 * @return String html
1094 protected static function formatErrors( $errors ) {
1095 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1096 $errors = array_shift( $errors );
1099 if ( is_array( $errors ) ) {
1101 foreach ( $errors as $error ) {
1102 if ( $error instanceof Message
) {
1103 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1105 $lines[] = Html
::rawElement( 'li', array(), $error );
1108 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1110 if ( $errors instanceof Message
) {
1111 $errors = $errors->parse();
1113 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1118 class HTMLTextField
extends HTMLFormField
{
1119 function getSize() {
1120 return isset( $this->mParams
['size'] )
1121 ?
$this->mParams
['size']
1125 function getInputHTML( $value ) {
1128 'name' => $this->mName
,
1129 'size' => $this->getSize(),
1131 ) +
$this->getTooltipAndAccessKey();
1133 if ( isset( $this->mParams
['maxlength'] ) ) {
1134 $attribs['maxlength'] = $this->mParams
['maxlength'];
1137 if ( !empty( $this->mParams
['disabled'] ) ) {
1138 $attribs['disabled'] = 'disabled';
1141 # TODO: Enforce pattern, step, required, readonly on the server side as
1143 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1144 'placeholder' ) as $param ) {
1145 if ( isset( $this->mParams
[$param] ) ) {
1146 $attribs[$param] = $this->mParams
[$param];
1150 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1151 if ( isset( $this->mParams
[$param] ) ) {
1152 $attribs[$param] = '';
1156 # Implement tiny differences between some field variants
1157 # here, rather than creating a new class for each one which
1158 # is essentially just a clone of this one.
1159 if ( isset( $this->mParams
['type'] ) ) {
1160 switch ( $this->mParams
['type'] ) {
1162 $attribs['type'] = 'email';
1165 $attribs['type'] = 'number';
1168 $attribs['type'] = 'number';
1169 $attribs['step'] = 'any';
1174 $attribs['type'] = $this->mParams
['type'];
1179 return Html
::element( 'input', $attribs );
1182 class HTMLTextAreaField
extends HTMLFormField
{
1183 function getCols() {
1184 return isset( $this->mParams
['cols'] )
1185 ?
$this->mParams
['cols']
1189 function getRows() {
1190 return isset( $this->mParams
['rows'] )
1191 ?
$this->mParams
['rows']
1195 function getInputHTML( $value ) {
1198 'name' => $this->mName
,
1199 'cols' => $this->getCols(),
1200 'rows' => $this->getRows(),
1201 ) +
$this->getTooltipAndAccessKey();
1204 if ( !empty( $this->mParams
['disabled'] ) ) {
1205 $attribs['disabled'] = 'disabled';
1208 if ( !empty( $this->mParams
['readonly'] ) ) {
1209 $attribs['readonly'] = 'readonly';
1212 foreach ( array( 'required', 'autofocus' ) as $param ) {
1213 if ( isset( $this->mParams
[$param] ) ) {
1214 $attribs[$param] = '';
1218 return Html
::element( 'textarea', $attribs, $value );
1223 * A field that will contain a numeric value
1225 class HTMLFloatField
extends HTMLTextField
{
1226 function getSize() {
1227 return isset( $this->mParams
['size'] )
1228 ?
$this->mParams
['size']
1232 function validate( $value, $alldata ) {
1233 $p = parent
::validate( $value, $alldata );
1235 if ( $p !== true ) {
1239 $value = trim( $value );
1241 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1242 # with the addition that a leading '+' sign is ok.
1243 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1244 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1247 # The "int" part of these message names is rather confusing.
1248 # They make equal sense for all numbers.
1249 if ( isset( $this->mParams
['min'] ) ) {
1250 $min = $this->mParams
['min'];
1252 if ( $min > $value ) {
1253 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1257 if ( isset( $this->mParams
['max'] ) ) {
1258 $max = $this->mParams
['max'];
1260 if ( $max < $value ) {
1261 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1270 * A field that must contain a number
1272 class HTMLIntField
extends HTMLFloatField
{
1273 function validate( $value, $alldata ) {
1274 $p = parent
::validate( $value, $alldata );
1276 if ( $p !== true ) {
1280 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1281 # with the addition that a leading '+' sign is ok. Note that leading zeros
1282 # are fine, and will be left in the input, which is useful for things like
1283 # phone numbers when you know that they are integers (the HTML5 type=tel
1284 # input does not require its value to be numeric). If you want a tidier
1285 # value to, eg, save in the DB, clean it up with intval().
1286 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1288 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1298 class HTMLCheckField
extends HTMLFormField
{
1299 function getInputHTML( $value ) {
1300 if ( !empty( $this->mParams
['invert'] ) ) {
1304 $attr = $this->getTooltipAndAccessKey();
1305 $attr['id'] = $this->mID
;
1307 if ( !empty( $this->mParams
['disabled'] ) ) {
1308 $attr['disabled'] = 'disabled';
1311 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1312 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1316 * For a checkbox, the label goes on the right hand side, and is
1317 * added in getInputHTML(), rather than HTMLFormField::getRow()
1320 function getLabel() {
1325 * @param $request WebRequest
1328 function loadDataFromRequest( $request ) {
1330 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1334 // GetCheck won't work like we want for checks.
1335 if ( $request->getCheck( 'wpEditToken' ) ||
$this->mParent
->getMethod() != 'post' ) {
1336 // XOR has the following truth table, which is what we want
1337 // INVERT VALUE | OUTPUT
1338 // true true | false
1339 // false true | true
1340 // false false | false
1341 // true false | true
1342 return $request->getBool( $this->mName
) xor $invert;
1344 return $this->getDefault();
1350 * A select dropdown field. Basically a wrapper for Xmlselect class
1352 class HTMLSelectField
extends HTMLFormField
{
1353 function validate( $value, $alldata ) {
1354 $p = parent
::validate( $value, $alldata );
1356 if ( $p !== true ) {
1360 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1362 if ( in_array( $value, $validOptions ) )
1365 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1368 function getInputHTML( $value ) {
1369 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1371 # If one of the options' 'name' is int(0), it is automatically selected.
1372 # because PHP sucks and thinks int(0) == 'some string'.
1373 # Working around this by forcing all of them to strings.
1374 foreach( $this->mParams
['options'] as &$opt ){
1375 if( is_int( $opt ) ){
1376 $opt = strval( $opt );
1379 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1381 if ( !empty( $this->mParams
['disabled'] ) ) {
1382 $select->setAttribute( 'disabled', 'disabled' );
1385 $select->addOptions( $this->mParams
['options'] );
1387 return $select->getHTML();
1392 * Select dropdown field, with an additional "other" textbox.
1394 class HTMLSelectOrOtherField
extends HTMLTextField
{
1395 static $jsAdded = false;
1397 function __construct( $params ) {
1398 if ( !in_array( 'other', $params['options'], true ) ) {
1399 $msg = isset( $params['other'] ) ?
$params['other'] : wfMsg( 'htmlform-selectorother-other' );
1400 $params['options'][$msg] = 'other';
1403 parent
::__construct( $params );
1406 static function forceToStringRecursive( $array ) {
1407 if ( is_array( $array ) ) {
1408 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1410 return strval( $array );
1414 function getInputHTML( $value ) {
1415 $valInSelect = false;
1417 if ( $value !== false ) {
1418 $valInSelect = in_array(
1420 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1424 $selected = $valInSelect ?
$value : 'other';
1426 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1428 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1429 $select->addOptions( $opts );
1431 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1433 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1435 if ( !empty( $this->mParams
['disabled'] ) ) {
1436 $select->setAttribute( 'disabled', 'disabled' );
1437 $tbAttribs['disabled'] = 'disabled';
1440 $select = $select->getHTML();
1442 if ( isset( $this->mParams
['maxlength'] ) ) {
1443 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1446 $textbox = Html
::input(
1447 $this->mName
. '-other',
1448 $valInSelect ?
'' : $value,
1453 return "$select<br />\n$textbox";
1457 * @param $request WebRequest
1460 function loadDataFromRequest( $request ) {
1461 if ( $request->getCheck( $this->mName
) ) {
1462 $val = $request->getText( $this->mName
);
1464 if ( $val == 'other' ) {
1465 $val = $request->getText( $this->mName
. '-other' );
1470 return $this->getDefault();
1476 * Multi-select field
1478 class HTMLMultiSelectField
extends HTMLFormField
{
1480 public function __construct( $params ){
1481 parent
::__construct( $params );
1482 if( isset( $params['flatlist'] ) ){
1483 $this->mClass
.= ' mw-htmlform-multiselect-flatlist';
1487 function validate( $value, $alldata ) {
1488 $p = parent
::validate( $value, $alldata );
1490 if ( $p !== true ) {
1494 if ( !is_array( $value ) ) {
1498 # If all options are valid, array_intersect of the valid options
1499 # and the provided options will return the provided options.
1500 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1502 $validValues = array_intersect( $value, $validOptions );
1503 if ( count( $validValues ) == count( $value ) ) {
1506 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1510 function getInputHTML( $value ) {
1511 $html = $this->formatOptions( $this->mParams
['options'], $value );
1516 function formatOptions( $options, $value ) {
1521 if ( !empty( $this->mParams
['disabled'] ) ) {
1522 $attribs['disabled'] = 'disabled';
1525 foreach ( $options as $label => $info ) {
1526 if ( is_array( $info ) ) {
1527 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1528 $html .= $this->formatOptions( $info, $value );
1530 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1532 $checkbox = Xml
::check(
1533 $this->mName
. '[]',
1534 in_array( $info, $value, true ),
1535 $attribs +
$thisAttribs );
1536 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1538 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1546 * @param $request WebRequest
1549 function loadDataFromRequest( $request ) {
1550 if ( $this->mParent
->getMethod() == 'post' ) {
1551 if( $request->wasPosted() ){
1552 # Checkboxes are just not added to the request arrays if they're not checked,
1553 # so it's perfectly possible for there not to be an entry at all
1554 return $request->getArray( $this->mName
, array() );
1556 # That's ok, the user has not yet submitted the form, so show the defaults
1557 return $this->getDefault();
1560 # This is the impossible case: if we look at $_GET and see no data for our
1561 # field, is it because the user has not yet submitted the form, or that they
1562 # have submitted it with all the options unchecked? We will have to assume the
1563 # latter, which basically means that you can't specify 'positive' defaults
1566 return $request->getArray( $this->mName
, array() );
1570 function getDefault() {
1571 if ( isset( $this->mDefault
) ) {
1572 return $this->mDefault
;
1578 protected function needsLabel() {
1584 * Double field with a dropdown list constructed from a system message in the format
1587 * * New Optgroup header
1588 * Plus a text field underneath for an additional reason. The 'value' of the field is
1589 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1591 * @todo FIXME: If made 'required', only the text field should be compulsory.
1593 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1595 function __construct( $params ) {
1596 if ( array_key_exists( 'other', $params ) ) {
1597 } elseif( array_key_exists( 'other-message', $params ) ){
1598 $params['other'] = wfMessage( $params['other-message'] )->plain();
1600 $params['other'] = null;
1603 if ( array_key_exists( 'options', $params ) ) {
1604 # Options array already specified
1605 } elseif( array_key_exists( 'options-message', $params ) ){
1606 # Generate options array from a system message
1607 $params['options'] = self
::parseMessage(
1608 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1613 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1615 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1617 parent
::__construct( $params );
1621 * Build a drop-down box from a textual list.
1622 * @param $string String message text
1623 * @param $otherName String name of "other reason" option
1625 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1627 public static function parseMessage( $string, $otherName=null ) {
1628 if( $otherName === null ){
1629 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1633 $options = array( $otherName => 'other' );
1635 foreach ( explode( "\n", $string ) as $option ) {
1636 $value = trim( $option );
1637 if ( $value == '' ) {
1639 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1640 # A new group is starting...
1641 $value = trim( substr( $value, 1 ) );
1643 } elseif ( substr( $value, 0, 2) == '**' ) {
1645 $opt = trim( substr( $value, 2 ) );
1646 if( $optgroup === false ){
1647 $options[$opt] = $opt;
1649 $options[$optgroup][$opt] = $opt;
1652 # groupless reason list
1654 $options[$option] = $option;
1661 function getInputHTML( $value ) {
1662 $select = parent
::getInputHTML( $value[1] );
1664 $textAttribs = array(
1665 'id' => $this->mID
. '-other',
1666 'size' => $this->getSize(),
1669 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1670 if ( isset( $this->mParams
[$param] ) ) {
1671 $textAttribs[$param] = '';
1675 $textbox = Html
::input(
1676 $this->mName
. '-other',
1682 return "$select<br />\n$textbox";
1686 * @param $request WebRequest
1687 * @return Array( <overall message>, <select value>, <text field value> )
1689 function loadDataFromRequest( $request ) {
1690 if ( $request->getCheck( $this->mName
) ) {
1692 $list = $request->getText( $this->mName
);
1693 $text = $request->getText( $this->mName
. '-other' );
1695 if ( $list == 'other' ) {
1697 } elseif( !in_array( $list, $this->mFlatOptions
) ){
1698 # User has spoofed the select form to give an option which wasn't
1699 # in the original offer. Sulk...
1701 } elseif( $text == '' ) {
1704 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1708 $final = $this->getDefault();
1712 foreach ( $this->mFlatOptions
as $option ) {
1713 $match = $option . wfMsgForContent( 'colon-separator' );
1714 if( strpos( $text, $match ) === 0 ) {
1716 $text = substr( $text, strlen( $match ) );
1721 return array( $final, $list, $text );
1724 function getSize() {
1725 return isset( $this->mParams
['size'] )
1726 ?
$this->mParams
['size']
1730 function validate( $value, $alldata ) {
1731 # HTMLSelectField forces $value to be one of the options in the select
1732 # field, which is not useful here. But we do want the validation further up
1734 $p = parent
::validate( $value[1], $alldata );
1736 if ( $p !== true ) {
1740 if( isset( $this->mParams
['required'] ) && $value[1] === '' ){
1741 return wfMsgExt( 'htmlform-required', 'parseinline' );
1749 * Radio checkbox fields.
1751 class HTMLRadioField
extends HTMLFormField
{
1752 function validate( $value, $alldata ) {
1753 $p = parent
::validate( $value, $alldata );
1755 if ( $p !== true ) {
1759 if ( !is_string( $value ) && !is_int( $value ) ) {
1763 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1765 if ( in_array( $value, $validOptions ) ) {
1768 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1773 * This returns a block of all the radio options, in one cell.
1774 * @see includes/HTMLFormField#getInputHTML()
1775 * @param $value String
1778 function getInputHTML( $value ) {
1779 $html = $this->formatOptions( $this->mParams
['options'], $value );
1784 function formatOptions( $options, $value ) {
1788 if ( !empty( $this->mParams
['disabled'] ) ) {
1789 $attribs['disabled'] = 'disabled';
1792 # TODO: should this produce an unordered list perhaps?
1793 foreach ( $options as $label => $info ) {
1794 if ( is_array( $info ) ) {
1795 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1796 $html .= $this->formatOptions( $info, $value );
1798 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1799 $html .= Xml
::radio(
1803 $attribs +
array( 'id' => $id )
1806 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1808 $html .= "<br />\n";
1815 protected function needsLabel() {
1821 * An information field (text blob), not a proper input.
1823 class HTMLInfoField
extends HTMLFormField
{
1824 function __construct( $info ) {
1825 $info['nodata'] = true;
1827 parent
::__construct( $info );
1830 function getInputHTML( $value ) {
1831 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1834 function getTableRow( $value ) {
1835 if ( !empty( $this->mParams
['rawrow'] ) ) {
1839 return parent
::getTableRow( $value );
1842 protected function needsLabel() {
1847 class HTMLHiddenField
extends HTMLFormField
{
1848 public function __construct( $params ) {
1849 parent
::__construct( $params );
1851 # Per HTML5 spec, hidden fields cannot be 'required'
1852 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1853 unset( $this->mParams
['required'] );
1856 public function getTableRow( $value ) {
1859 $params['id'] = $this->mID
;
1862 $this->mParent
->addHiddenField(
1871 public function getInputHTML( $value ) { return ''; }
1875 * Add a submit button inline in the form (as opposed to
1876 * HTMLForm::addButton(), which will add it at the end).
1878 class HTMLSubmitField
extends HTMLFormField
{
1880 function __construct( $info ) {
1881 $info['nodata'] = true;
1882 parent
::__construct( $info );
1885 function getInputHTML( $value ) {
1886 return Xml
::submitButton(
1889 'class' => 'mw-htmlform-submit',
1890 'name' => $this->mName
,
1896 protected function needsLabel() {
1901 * Button cannot be invalid
1902 * @param $value String
1903 * @param $alldata Array
1906 public function validate( $value, $alldata ){
1911 class HTMLEditTools
extends HTMLFormField
{
1912 public function getInputHTML( $value ) {
1916 public function getTableRow( $value ) {
1917 if ( empty( $this->mParams
['message'] ) ) {
1918 $msg = wfMessage( 'edittools' );
1920 $msg = wfMessage( $this->mParams
['message'] );
1921 if ( $msg->isDisabled() ) {
1922 $msg = wfMessage( 'edittools' );
1925 $msg->inContentLanguage();
1928 return '<tr><td></td><td class="mw-input">'
1929 . '<div class="mw-editTools">'
1930 . $msg->parseAsBlock()
1931 . "</div></td></tr>\n";