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()
45 * 'name' -- By default, the 'name' attribute of the input field
46 * is "wp{$fieldname}". If you want a different name
47 * (eg one without the "wp" prefix), specify it here and
48 * it will be used without modification.
50 * TODO: Document 'section' / 'subsection' stuff
53 static $jsAdded = false;
55 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
56 static $typeMappings = array(
57 'text' => 'HTMLTextField',
58 'textarea' => 'HTMLTextAreaField',
59 'select' => 'HTMLSelectField',
60 'radio' => 'HTMLRadioField',
61 'multiselect' => 'HTMLMultiSelectField',
62 'check' => 'HTMLCheckField',
63 'toggle' => 'HTMLCheckField',
64 'int' => 'HTMLIntField',
65 'float' => 'HTMLFloatField',
66 'info' => 'HTMLInfoField',
67 'selectorother' => 'HTMLSelectOrOtherField',
68 'submit' => 'HTMLSubmitField',
69 'hidden' => 'HTMLHiddenField',
70 'edittools' => 'HTMLEditTools',
72 # HTMLTextField will output the correct type="" attribute automagically.
73 # There are about four zillion other HTML5 input types, like url, but
74 # we don't use those at the moment, so no point in adding all of them.
75 'email' => 'HTMLTextField',
76 'password' => 'HTMLTextField',
79 protected $mMessagePrefix;
80 protected $mFlatFields;
81 protected $mFieldTree;
82 protected $mShowReset = false;
85 protected $mSubmitCallback;
86 protected $mValidationErrorMessage;
89 protected $mHeader = '';
90 protected $mFooter = '';
91 protected $mPost = '';
95 protected $mSubmitName;
96 protected $mSubmitText;
97 protected $mSubmitTooltip;
99 protected $mMethod = 'post';
101 protected $mUseMultipart = false;
102 protected $mHiddenFields = array();
103 protected $mButtons = array();
105 protected $mWrapperLegend = false;
108 * Build a new HTMLForm from an array of field attributes
109 * @param $descriptor Array of Field constructs, as described above
110 * @param $messagePrefix String a prefix to go in front of default messages
112 public function __construct( $descriptor, $messagePrefix = '' ) {
113 $this->mMessagePrefix
= $messagePrefix;
115 // Expand out into a tree.
116 $loadedDescriptor = array();
117 $this->mFlatFields
= array();
119 foreach ( $descriptor as $fieldname => $info ) {
120 $section = isset( $info['section'] )
124 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
125 $this->mUseMultipart
= true;
128 $field = self
::loadInputFromParameters( $fieldname, $info );
129 $field->mParent
= $this;
131 $setSection =& $loadedDescriptor;
133 $sectionParts = explode( '/', $section );
135 while ( count( $sectionParts ) ) {
136 $newName = array_shift( $sectionParts );
138 if ( !isset( $setSection[$newName] ) ) {
139 $setSection[$newName] = array();
142 $setSection =& $setSection[$newName];
146 $setSection[$fieldname] = $field;
147 $this->mFlatFields
[$fieldname] = $field;
150 $this->mFieldTree
= $loadedDescriptor;
154 * Add the HTMLForm-specific JavaScript, if it hasn't been
157 static function addJS() {
158 if ( self
::$jsAdded ) return;
162 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
166 * Initialise a new Object for the field
167 * @param $descriptor input Descriptor, as described above
168 * @return HTMLFormField subclass
170 static function loadInputFromParameters( $fieldname, $descriptor ) {
171 if ( isset( $descriptor['class'] ) ) {
172 $class = $descriptor['class'];
173 } elseif ( isset( $descriptor['type'] ) ) {
174 $class = self
::$typeMappings[$descriptor['type']];
175 $descriptor['class'] = $class;
179 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
182 $descriptor['fieldname'] = $fieldname;
184 $obj = new $class( $descriptor );
190 * Prepare form for submission
192 function prepareForm() {
193 # Check if we have the info we need
194 if ( ! $this->mTitle
) {
195 throw new MWException( "You must call setTitle() on an HTMLForm" );
198 // FIXME shouldn't this be closer to displayForm() ?
201 # Load data from the request.
206 * Try submitting, with edit token check first
207 * @return Status|boolean
209 function tryAuthorizedSubmit() {
210 global $wgUser, $wgRequest;
211 $editToken = $wgRequest->getVal( 'wpEditToken' );
214 if ( $this->getMethod() != 'post' ||
$wgUser->matchEditToken( $editToken ) ) {
215 $result = $this->trySubmit();
221 * The here's-one-I-made-earlier option: do the submission if
222 * posted, or display the form with or without funky valiation
224 * @return Bool or Status whether submission was successful.
227 $this->prepareForm();
229 $result = $this->tryAuthorizedSubmit();
230 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
234 $this->displayForm( $result );
239 * Validate all the fields, and call the submision callback
240 * function if everything is kosher.
241 * @return Mixed Bool true == Successful submission, Bool false
242 * == No submission attempted, anything else == Error to
245 function trySubmit() {
246 # Check for validation
247 foreach ( $this->mFlatFields
as $fieldname => $field ) {
248 if ( !empty( $field->mParams
['nodata'] ) ) {
251 if ( $field->validate(
252 $this->mFieldData
[$fieldname],
256 return isset( $this->mValidationErrorMessage
)
257 ?
$this->mValidationErrorMessage
258 : array( 'htmlform-invalid-input' );
262 $callback = $this->mSubmitCallback
;
264 $data = $this->filterDataForSubmit( $this->mFieldData
);
266 $res = call_user_func( $callback, $data );
272 * Set a callback to a function to do something with the form
273 * once it's been successfully validated.
274 * @param $cb String function name. The function will be passed
275 * the output from HTMLForm::filterDataForSubmit, and must
276 * return Bool true on success, Bool false if no submission
277 * was attempted, or String HTML output to display on error.
279 function setSubmitCallback( $cb ) {
280 $this->mSubmitCallback
= $cb;
284 * Set a message to display on a validation error.
285 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
286 * (so each entry can be either a String or Array)
288 function setValidationErrorMessage( $msg ) {
289 $this->mValidationErrorMessage
= $msg;
293 * Set the introductory message, overwriting any existing message.
294 * @param $msg String complete text of message to display
296 function setIntro( $msg ) { $this->mPre
= $msg; }
299 * Add introductory text.
300 * @param $msg String complete text of message to display
302 function addPreText( $msg ) { $this->mPre
.= $msg; }
305 * Add header text, inside the form.
306 * @param $msg String complete text of message to display
308 function addHeaderText( $msg ) { $this->mHeader
.= $msg; }
311 * Add footer text, inside the form.
312 * @param $msg String complete text of message to display
314 function addFooterText( $msg ) { $this->mFooter
.= $msg; }
317 * Add text to the end of the display.
318 * @param $msg String complete text of message to display
320 function addPostText( $msg ) { $this->mPost
.= $msg; }
323 * Add a hidden field to the output
324 * @param $name String field name. This will be used exactly as entered
325 * @param $value String field value
326 * @param $attribs Array
328 public function addHiddenField( $name, $value, $attribs = array() ) {
329 $attribs +
= array( 'name' => $name );
330 $this->mHiddenFields
[] = array( $value, $attribs );
333 public function addButton( $name, $value, $id = null, $attribs = null ) {
334 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
338 * Display the form (sending to wgOut), with an appropriate error
339 * message or stack of messages, and any validation errors, etc.
340 * @param $submitResult Mixed output from HTMLForm::trySubmit()
342 function displayForm( $submitResult ) {
346 . $this->getErrors( $submitResult )
349 . $this->getHiddenFields()
350 . $this->getButtons()
354 $html = $this->wrapForm( $html );
364 * Wrap the form innards in an actual <form> element
365 * @param $html String HTML contents to wrap.
366 * @return String wrapped HTML.
368 function wrapForm( $html ) {
370 # Include a <fieldset> wrapper for style, if requested.
371 if ( $this->mWrapperLegend
!== false ) {
372 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
374 # Use multipart/form-data
375 $encType = $this->mUseMultipart
376 ?
'multipart/form-data'
377 : 'application/x-www-form-urlencoded';
380 'action' => $this->getTitle()->getFullURL(),
381 'method' => $this->mMethod
,
382 'class' => 'visualClear',
383 'enctype' => $encType,
385 if ( !empty( $this->mId
) ) {
386 $attribs['id'] = $this->mId
;
389 return Html
::rawElement( 'form', $attribs, $html );
393 * Get the hidden fields that should go inside the form.
394 * @return String HTML.
396 function getHiddenFields() {
401 if( $this->getMethod() == 'post' ){
402 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
403 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
406 foreach ( $this->mHiddenFields
as $data ) {
407 list( $value, $attribs ) = $data;
408 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
415 * Get the submit and (potentially) reset buttons.
416 * @return String HTML.
418 function getButtons() {
422 if ( isset( $this->mSubmitID
) ) {
423 $attribs['id'] = $this->mSubmitID
;
426 if ( isset( $this->mSubmitName
) ) {
427 $attribs['name'] = $this->mSubmitName
;
430 if ( isset( $this->mSubmitTooltip
) ) {
432 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
435 $attribs['class'] = 'mw-htmlform-submit';
437 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
439 if ( $this->mShowReset
) {
440 $html .= Html
::element(
444 'value' => wfMsg( 'htmlform-reset' )
449 foreach ( $this->mButtons
as $button ) {
452 'name' => $button['name'],
453 'value' => $button['value']
456 if ( $button['attribs'] ) {
457 $attrs +
= $button['attribs'];
460 if ( isset( $button['id'] ) ) {
461 $attrs['id'] = $button['id'];
464 $html .= Html
::element( 'input', $attrs );
471 * Get the whole body of the form.
474 return $this->displaySection( $this->mFieldTree
);
478 * Format and display an error message stack.
479 * @param $errors Mixed String or Array of message keys
482 function getErrors( $errors ) {
483 if ( $errors instanceof Status
) {
485 $errorstr = $wgOut->parse( $errors->getWikiText() );
486 } elseif ( is_array( $errors ) ) {
487 $errorstr = $this->formatErrors( $errors );
493 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
498 * Format a stack of error messages into a single HTML string
499 * @param $errors Array of message keys/values
500 * @return String HTML, a <ul> list of errors
502 static function formatErrors( $errors ) {
505 foreach ( $errors as $error ) {
506 if ( is_array( $error ) ) {
507 $msg = array_shift( $error );
513 $errorstr .= Html
::rawElement(
516 wfMsgExt( $msg, array( 'parseinline' ), $error )
520 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
526 * Set the text for the submit button
527 * @param $t String plaintext.
529 function setSubmitText( $t ) {
530 $this->mSubmitText
= $t;
534 * Get the text for the submit button, either customised or a default.
535 * @return unknown_type
537 function getSubmitText() {
538 return $this->mSubmitText
540 : wfMsg( 'htmlform-submit' );
543 public function setSubmitName( $name ) {
544 $this->mSubmitName
= $name;
547 public function setSubmitTooltip( $name ) {
548 $this->mSubmitTooltip
= $name;
552 * Set the id for the submit button.
553 * @param $t String. FIXME: Integrity is *not* validated
555 function setSubmitID( $t ) {
556 $this->mSubmitID
= $t;
559 public function setId( $id ) {
563 * Prompt the whole form to be wrapped in a <fieldset>, with
564 * this text as its <legend> element.
565 * @param $legend String HTML to go inside the <legend> element.
568 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
571 * Set the prefix for various default messages
572 * TODO: currently only used for the <fieldset> legend on forms
573 * with multiple sections; should be used elsewhre?
576 function setMessagePrefix( $p ) {
577 $this->mMessagePrefix
= $p;
581 * Set the title for form submission
582 * @param $t Title of page the form is on/should be posted to
584 function setTitle( $t ) {
592 function getTitle() {
593 return $this->mTitle
;
597 * Set the method used to submit the form
598 * @param $method String
600 public function setMethod( $method='post' ){
601 $this->mMethod
= $method;
604 public function getMethod(){
605 return $this->mMethod
;
612 function displaySection( $fields, $sectionName = '' ) {
614 $subsectionHtml = '';
615 $hasLeftColumn = false;
617 foreach ( $fields as $key => $value ) {
618 if ( is_object( $value ) ) {
619 $v = empty( $value->mParams
['nodata'] )
620 ?
$this->mFieldData
[$key]
621 : $value->getDefault();
622 $tableHtml .= $value->getTableRow( $v );
624 if ( $value->getLabel() != ' ' )
625 $hasLeftColumn = true;
626 } elseif ( is_array( $value ) ) {
627 $section = $this->displaySection( $value, $key );
628 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
629 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
635 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
636 $classes[] = 'mw-htmlform-nolabel';
640 'class' => implode( ' ', $classes ),
643 if ( $sectionName ) {
644 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
647 $tableHtml = Html
::rawElement( 'table', $attribs,
648 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
650 return $subsectionHtml . "\n" . $tableHtml;
654 * Construct the form fields from the Descriptor array
656 function loadData() {
659 $fieldData = array();
661 foreach ( $this->mFlatFields
as $fieldname => $field ) {
662 if ( !empty( $field->mParams
['nodata'] ) ) {
664 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
665 $fieldData[$fieldname] = $field->getDefault();
667 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
672 foreach ( $fieldData as $name => &$value ) {
673 $field = $this->mFlatFields
[$name];
674 $value = $field->filter( $value, $this->mFlatFields
);
677 $this->mFieldData
= $fieldData;
681 * Stop a reset button being shown for this form
682 * @param $suppressReset Bool set to false to re-enable the
685 function suppressReset( $suppressReset = true ) {
686 $this->mShowReset
= !$suppressReset;
690 * Overload this if you want to apply special filtration routines
691 * to the form as a whole, after it's submitted but before it's
694 * @return unknown_type
696 function filterDataForSubmit( $data ) {
702 * The parent class to generate form fields. Any field type should
703 * be a subclass of this.
705 abstract class HTMLFormField
{
707 protected $mValidationCallback;
708 protected $mFilterCallback;
711 protected $mLabel; # String label. Set on construction
713 protected $mClass = '';
718 * This function must be implemented to return the HTML to generate
719 * the input object itself. It should not implement the surrounding
720 * table cells/rows, or labels/help messages.
721 * @param $value String the value to set the input to; eg a default
722 * text for a text input.
723 * @return String valid HTML.
725 abstract function getInputHTML( $value );
728 * Override this function to add specific validation checks on the
729 * field input. Don't forget to call parent::validate() to ensure
730 * that the user-defined callback mValidationCallback is still run
731 * @param $value String the value the field was submitted with
732 * @param $alldata Array the data collected from the form
733 * @return Mixed Bool true on success, or String error to display.
735 function validate( $value, $alldata ) {
736 if ( isset( $this->mValidationCallback
) ) {
737 return call_user_func( $this->mValidationCallback
, $value, $alldata );
740 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
741 return wfMsgExt( 'htmlform-required', 'parseinline' );
747 function filter( $value, $alldata ) {
748 if ( isset( $this->mFilterCallback
) ) {
749 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
756 * Should this field have a label, or is there no input element with the
757 * appropriate id for the label to point to?
759 * @return bool True to output a label, false to suppress
761 protected function needsLabel() {
766 * Get the value that this input has been set to from a posted form,
767 * or the input's default value if it has not been set.
768 * @param $request WebRequest
769 * @return String the value
771 function loadDataFromRequest( $request ) {
772 if ( $request->getCheck( $this->mName
) ) {
773 return $request->getText( $this->mName
);
775 return $this->getDefault();
780 * Initialise the object
781 * @param $params Associative Array. See HTMLForm doc for syntax.
783 function __construct( $params ) {
784 $this->mParams
= $params;
786 # Generate the label from a message, if possible
787 if ( isset( $params['label-message'] ) ) {
788 $msgInfo = $params['label-message'];
790 if ( is_array( $msgInfo ) ) {
791 $msg = array_shift( $msgInfo );
797 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
798 } elseif ( isset( $params['label'] ) ) {
799 $this->mLabel
= $params['label'];
802 $this->mName
= "wp{$params['fieldname']}";
803 if ( isset( $params['name'] ) ) {
804 $this->mName
= $params['name'];
807 $validName = Sanitizer
::escapeId( $this->mName
);
808 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
809 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
812 $this->mID
= "mw-input-{$this->mName}";
814 if ( isset( $params['default'] ) ) {
815 $this->mDefault
= $params['default'];
818 if ( isset( $params['id'] ) ) {
820 $validId = Sanitizer
::escapeId( $id );
822 if ( $id != $validId ) {
823 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
829 if ( isset( $params['cssclass'] ) ) {
830 $this->mClass
= $params['cssclass'];
833 if ( isset( $params['validation-callback'] ) ) {
834 $this->mValidationCallback
= $params['validation-callback'];
837 if ( isset( $params['filter-callback'] ) ) {
838 $this->mFilterCallback
= $params['filter-callback'];
843 * Get the complete table row for the input, including help text,
844 * labels, and whatever.
845 * @param $value String the value to set the input to.
846 * @return String complete HTML table row.
848 function getTableRow( $value ) {
849 # Check for invalid data.
852 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
854 $cellAttributes = array();
855 $verticalLabel = false;
857 if ( !empty($this->mParams
['vertical-label']) ) {
858 $cellAttributes['colspan'] = 2;
859 $verticalLabel = true;
862 if ( $errors === true ||
( !$wgRequest->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
865 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
868 $label = $this->getLabelHtml( $cellAttributes );
869 $field = Html
::rawElement(
871 array( 'class' => 'mw-input' ) +
$cellAttributes,
872 $this->getInputHTML( $value ) . "\n$errors"
875 $fieldType = get_class( $this );
877 if ($verticalLabel) {
878 $html = Html
::rawElement( 'tr',
879 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
880 $html .= Html
::rawElement( 'tr',
881 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
884 $html = Html
::rawElement( 'tr',
885 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
891 if ( isset( $this->mParams
['help-message'] ) ) {
892 $msg = $this->mParams
['help-message'];
893 $helptext = wfMsgExt( $msg, 'parseinline' );
894 if ( wfEmptyMsg( $msg, $helptext ) ) {
898 } elseif ( isset( $this->mParams
['help'] ) ) {
899 $helptext = $this->mParams
['help'];
902 if ( !is_null( $helptext ) ) {
903 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
905 $row = Html
::rawElement( 'tr', array(), $row );
912 function getLabel() {
913 return $this->mLabel
;
915 function getLabelHtml( $cellAttributes = array() ) {
916 # Don't output a for= attribute for labels with no associated input.
917 # Kind of hacky here, possibly we don't want these to be <label>s at all.
920 if ( $this->needsLabel() ) {
921 $for['for'] = $this->mID
;
924 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
925 Html
::rawElement( 'label', $for, $this->getLabel() )
929 function getDefault() {
930 if ( isset( $this->mDefault
) ) {
931 return $this->mDefault
;
938 * Returns the attributes required for the tooltip and accesskey.
940 * @return array Attributes
942 public function getTooltipAndAccessKey() {
943 if ( empty( $this->mParams
['tooltip'] ) ) {
949 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
953 * flatten an array of options to a single array, for instance,
954 * a set of <options> inside <optgroups>.
955 * @param $options Associative Array with values either Strings
957 * @return Array flattened input
959 public static function flattenOptions( $options ) {
962 foreach ( $options as $value ) {
963 if ( is_array( $value ) ) {
964 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
966 $flatOpts[] = $value;
974 class HTMLTextField
extends HTMLFormField
{
976 return isset( $this->mParams
['size'] )
977 ?
$this->mParams
['size']
981 function getInputHTML( $value ) {
984 'name' => $this->mName
,
985 'size' => $this->getSize(),
987 ) +
$this->getTooltipAndAccessKey();
989 if ( isset( $this->mParams
['maxlength'] ) ) {
990 $attribs['maxlength'] = $this->mParams
['maxlength'];
993 if ( !empty( $this->mParams
['disabled'] ) ) {
994 $attribs['disabled'] = 'disabled';
997 # TODO: Enforce pattern, step, required, readonly on the server side as
999 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1000 'placeholder' ) as $param ) {
1001 if ( isset( $this->mParams
[$param] ) ) {
1002 $attribs[$param] = $this->mParams
[$param];
1006 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1007 if ( isset( $this->mParams
[$param] ) ) {
1008 $attribs[$param] = '';
1012 # Implement tiny differences between some field variants
1013 # here, rather than creating a new class for each one which
1014 # is essentially just a clone of this one.
1015 if ( isset( $this->mParams
['type'] ) ) {
1016 switch ( $this->mParams
['type'] ) {
1018 $attribs['type'] = 'email';
1021 $attribs['type'] = 'number';
1024 $attribs['type'] = 'number';
1025 $attribs['step'] = 'any';
1030 $attribs['type'] = $this->mParams
['type'];
1035 return Html
::element( 'input', $attribs );
1038 class HTMLTextAreaField
extends HTMLFormField
{
1039 function getCols() {
1040 return isset( $this->mParams
['cols'] )
1041 ?
$this->mParams
['cols']
1045 function getRows() {
1046 return isset( $this->mParams
['rows'] )
1047 ?
$this->mParams
['rows']
1051 function getInputHTML( $value ) {
1054 'name' => $this->mName
,
1055 'cols' => $this->getCols(),
1056 'rows' => $this->getRows(),
1057 ) +
$this->getTooltipAndAccessKey();
1060 if ( !empty( $this->mParams
['disabled'] ) ) {
1061 $attribs['disabled'] = 'disabled';
1064 if ( !empty( $this->mParams
['readonly'] ) ) {
1065 $attribs['readonly'] = 'readonly';
1068 foreach ( array( 'required', 'autofocus' ) as $param ) {
1069 if ( isset( $this->mParams
[$param] ) ) {
1070 $attribs[$param] = '';
1074 return Html
::element( 'textarea', $attribs, $value );
1079 * A field that will contain a numeric value
1081 class HTMLFloatField
extends HTMLTextField
{
1082 function getSize() {
1083 return isset( $this->mParams
['size'] )
1084 ?
$this->mParams
['size']
1088 function validate( $value, $alldata ) {
1089 $p = parent
::validate( $value, $alldata );
1091 if ( $p !== true ) {
1095 $value = trim( $value );
1097 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1098 # with the addition that a leading '+' sign is ok.
1099 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1100 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1103 # The "int" part of these message names is rather confusing.
1104 # They make equal sense for all numbers.
1105 if ( isset( $this->mParams
['min'] ) ) {
1106 $min = $this->mParams
['min'];
1108 if ( $min > $value ) {
1109 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1113 if ( isset( $this->mParams
['max'] ) ) {
1114 $max = $this->mParams
['max'];
1116 if ( $max < $value ) {
1117 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1126 * A field that must contain a number
1128 class HTMLIntField
extends HTMLFloatField
{
1129 function validate( $value, $alldata ) {
1130 $p = parent
::validate( $value, $alldata );
1132 if ( $p !== true ) {
1136 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1137 # with the addition that a leading '+' sign is ok. Note that leading zeros
1138 # are fine, and will be left in the input, which is useful for things like
1139 # phone numbers when you know that they are integers (the HTML5 type=tel
1140 # input does not require its value to be numeric). If you want a tidier
1141 # value to, eg, save in the DB, clean it up with intval().
1142 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1144 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1154 class HTMLCheckField
extends HTMLFormField
{
1155 function getInputHTML( $value ) {
1156 if ( !empty( $this->mParams
['invert'] ) ) {
1160 $attr = $this->getTooltipAndAccessKey();
1161 $attr['id'] = $this->mID
;
1163 if ( !empty( $this->mParams
['disabled'] ) ) {
1164 $attr['disabled'] = 'disabled';
1167 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1168 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1172 * For a checkbox, the label goes on the right hand side, and is
1173 * added in getInputHTML(), rather than HTMLFormField::getRow()
1175 function getLabel() {
1179 function loadDataFromRequest( $request ) {
1181 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1185 // GetCheck won't work like we want for checks.
1186 if ( $request->getCheck( 'wpEditToken' ) ) {
1187 // XOR has the following truth table, which is what we want
1188 // INVERT VALUE | OUTPUT
1189 // true true | false
1190 // false true | true
1191 // false false | false
1192 // true false | true
1193 return $request->getBool( $this->mName
) xor $invert;
1195 return $this->getDefault();
1201 * A select dropdown field. Basically a wrapper for Xmlselect class
1203 class HTMLSelectField
extends HTMLFormField
{
1204 function validate( $value, $alldata ) {
1205 $p = parent
::validate( $value, $alldata );
1207 if ( $p !== true ) {
1211 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1213 if ( in_array( $value, $validOptions ) )
1216 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1219 function getInputHTML( $value ) {
1220 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1222 # If one of the options' 'name' is int(0), it is automatically selected.
1223 # because PHP sucks and things int(0) == 'some string'.
1224 # Working around this by forcing all of them to strings.
1225 $options = array_map( 'strval', $this->mParams
['options'] );
1227 if ( !empty( $this->mParams
['disabled'] ) ) {
1228 $select->setAttribute( 'disabled', 'disabled' );
1231 $select->addOptions( $options );
1233 return $select->getHTML();
1238 * Select dropdown field, with an additional "other" textbox.
1240 class HTMLSelectOrOtherField
extends HTMLTextField
{
1241 static $jsAdded = false;
1243 function __construct( $params ) {
1244 if ( !in_array( 'other', $params['options'], true ) ) {
1245 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1248 parent
::__construct( $params );
1251 static function forceToStringRecursive( $array ) {
1252 if ( is_array( $array ) ) {
1253 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1255 return strval( $array );
1259 function getInputHTML( $value ) {
1260 $valInSelect = false;
1262 if ( $value !== false ) {
1263 $valInSelect = in_array(
1265 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1269 $selected = $valInSelect ?
$value : 'other';
1271 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1273 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1274 $select->addOptions( $opts );
1276 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1278 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1280 if ( !empty( $this->mParams
['disabled'] ) ) {
1281 $select->setAttribute( 'disabled', 'disabled' );
1282 $tbAttribs['disabled'] = 'disabled';
1285 $select = $select->getHTML();
1287 if ( isset( $this->mParams
['maxlength'] ) ) {
1288 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1291 $textbox = Html
::input(
1292 $this->mName
. '-other',
1293 $valInSelect ?
'' : $value,
1298 return "$select<br />\n$textbox";
1301 function loadDataFromRequest( $request ) {
1302 if ( $request->getCheck( $this->mName
) ) {
1303 $val = $request->getText( $this->mName
);
1305 if ( $val == 'other' ) {
1306 $val = $request->getText( $this->mName
. '-other' );
1311 return $this->getDefault();
1317 * Multi-select field
1319 class HTMLMultiSelectField
extends HTMLFormField
{
1320 function validate( $value, $alldata ) {
1321 $p = parent
::validate( $value, $alldata );
1323 if ( $p !== true ) {
1327 if ( !is_array( $value ) ) {
1331 # If all options are valid, array_intersect of the valid options
1332 # and the provided options will return the provided options.
1333 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1335 $validValues = array_intersect( $value, $validOptions );
1336 if ( count( $validValues ) == count( $value ) ) {
1339 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1343 function getInputHTML( $value ) {
1344 $html = $this->formatOptions( $this->mParams
['options'], $value );
1349 function formatOptions( $options, $value ) {
1354 if ( !empty( $this->mParams
['disabled'] ) ) {
1355 $attribs['disabled'] = 'disabled';
1358 foreach ( $options as $label => $info ) {
1359 if ( is_array( $info ) ) {
1360 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1361 $html .= $this->formatOptions( $info, $value );
1363 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1365 $checkbox = Xml
::check(
1366 $this->mName
. '[]',
1367 in_array( $info, $value, true ),
1368 $attribs +
$thisAttribs );
1369 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1371 $html .= $checkbox . '<br />';
1378 function loadDataFromRequest( $request ) {
1379 # won't work with getCheck
1380 if ( $request->getCheck( 'wpEditToken' ) ) {
1381 $arr = $request->getArray( $this->mName
);
1389 return $this->getDefault();
1393 function getDefault() {
1394 if ( isset( $this->mDefault
) ) {
1395 return $this->mDefault
;
1401 protected function needsLabel() {
1407 * Radio checkbox fields.
1409 class HTMLRadioField
extends HTMLFormField
{
1410 function validate( $value, $alldata ) {
1411 $p = parent
::validate( $value, $alldata );
1413 if ( $p !== true ) {
1417 if ( !is_string( $value ) && !is_int( $value ) ) {
1421 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1423 if ( in_array( $value, $validOptions ) ) {
1426 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1431 * This returns a block of all the radio options, in one cell.
1432 * @see includes/HTMLFormField#getInputHTML()
1434 function getInputHTML( $value ) {
1435 $html = $this->formatOptions( $this->mParams
['options'], $value );
1440 function formatOptions( $options, $value ) {
1444 if ( !empty( $this->mParams
['disabled'] ) ) {
1445 $attribs['disabled'] = 'disabled';
1448 # TODO: should this produce an unordered list perhaps?
1449 foreach ( $options as $label => $info ) {
1450 if ( is_array( $info ) ) {
1451 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1452 $html .= $this->formatOptions( $info, $value );
1454 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1455 $html .= Xml
::radio(
1459 $attribs +
array( 'id' => $id )
1462 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1464 $html .= "<br />\n";
1471 protected function needsLabel() {
1477 * An information field (text blob), not a proper input.
1479 class HTMLInfoField
extends HTMLFormField
{
1480 function __construct( $info ) {
1481 $info['nodata'] = true;
1483 parent
::__construct( $info );
1486 function getInputHTML( $value ) {
1487 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1490 function getTableRow( $value ) {
1491 if ( !empty( $this->mParams
['rawrow'] ) ) {
1495 return parent
::getTableRow( $value );
1498 protected function needsLabel() {
1503 class HTMLHiddenField
extends HTMLFormField
{
1504 public function __construct( $params ) {
1505 parent
::__construct( $params );
1507 # Per HTML5 spec, hidden fields cannot be 'required'
1508 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1509 unset( $this->mParams
['required'] );
1512 public function getTableRow( $value ) {
1515 $params['id'] = $this->mID
;
1518 $this->mParent
->addHiddenField(
1527 public function getInputHTML( $value ) { return ''; }
1531 * Add a submit button inline in the form (as opposed to
1532 * HTMLForm::addButton(), which will add it at the end).
1534 class HTMLSubmitField
extends HTMLFormField
{
1536 function __construct( $info ) {
1537 $info['nodata'] = true;
1538 parent
::__construct( $info );
1541 function getInputHTML( $value ) {
1542 return Xml
::submitButton(
1545 'class' => 'mw-htmlform-submit',
1546 'name' => $this->mName
,
1552 protected function needsLabel() {
1557 * Button cannot be invalid
1559 public function validate( $value, $alldata ){
1564 class HTMLEditTools
extends HTMLFormField
{
1565 public function getInputHTML( $value ) {
1569 public function getTableRow( $value ) {
1570 return "<tr><td></td><td class=\"mw-input\">"
1571 . '<div class="mw-editTools">'
1572 . wfMsgExt( empty( $this->mParams
['message'] )
1573 ?
'edittools' : $this->mParams
['message'],
1574 array( 'parse', 'content' ) )
1575 . "</div></td></tr>\n";