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 ) {
345 # For good measure (it is the default)
346 $wgOut->preventClickjacking();
349 . $this->getErrors( $submitResult )
352 . $this->getHiddenFields()
353 . $this->getButtons()
357 $html = $this->wrapForm( $html );
367 * Wrap the form innards in an actual <form> element
368 * @param $html String HTML contents to wrap.
369 * @return String wrapped HTML.
371 function wrapForm( $html ) {
373 # Include a <fieldset> wrapper for style, if requested.
374 if ( $this->mWrapperLegend
!== false ) {
375 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
377 # Use multipart/form-data
378 $encType = $this->mUseMultipart
379 ?
'multipart/form-data'
380 : 'application/x-www-form-urlencoded';
383 'action' => $this->getTitle()->getFullURL(),
384 'method' => $this->mMethod
,
385 'class' => 'visualClear',
386 'enctype' => $encType,
388 if ( !empty( $this->mId
) ) {
389 $attribs['id'] = $this->mId
;
392 return Html
::rawElement( 'form', $attribs, $html );
396 * Get the hidden fields that should go inside the form.
397 * @return String HTML.
399 function getHiddenFields() {
404 if( $this->getMethod() == 'post' ){
405 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
406 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
409 foreach ( $this->mHiddenFields
as $data ) {
410 list( $value, $attribs ) = $data;
411 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
418 * Get the submit and (potentially) reset buttons.
419 * @return String HTML.
421 function getButtons() {
425 if ( isset( $this->mSubmitID
) ) {
426 $attribs['id'] = $this->mSubmitID
;
429 if ( isset( $this->mSubmitName
) ) {
430 $attribs['name'] = $this->mSubmitName
;
433 if ( isset( $this->mSubmitTooltip
) ) {
435 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
438 $attribs['class'] = 'mw-htmlform-submit';
440 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
442 if ( $this->mShowReset
) {
443 $html .= Html
::element(
447 'value' => wfMsg( 'htmlform-reset' )
452 foreach ( $this->mButtons
as $button ) {
455 'name' => $button['name'],
456 'value' => $button['value']
459 if ( $button['attribs'] ) {
460 $attrs +
= $button['attribs'];
463 if ( isset( $button['id'] ) ) {
464 $attrs['id'] = $button['id'];
467 $html .= Html
::element( 'input', $attrs );
474 * Get the whole body of the form.
477 return $this->displaySection( $this->mFieldTree
);
481 * Format and display an error message stack.
482 * @param $errors Mixed String or Array of message keys
485 function getErrors( $errors ) {
486 if ( $errors instanceof Status
) {
488 $errorstr = $wgOut->parse( $errors->getWikiText() );
489 } elseif ( is_array( $errors ) ) {
490 $errorstr = $this->formatErrors( $errors );
496 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
501 * Format a stack of error messages into a single HTML string
502 * @param $errors Array of message keys/values
503 * @return String HTML, a <ul> list of errors
505 static function formatErrors( $errors ) {
508 foreach ( $errors as $error ) {
509 if ( is_array( $error ) ) {
510 $msg = array_shift( $error );
516 $errorstr .= Html
::rawElement(
519 wfMsgExt( $msg, array( 'parseinline' ), $error )
523 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
529 * Set the text for the submit button
530 * @param $t String plaintext.
532 function setSubmitText( $t ) {
533 $this->mSubmitText
= $t;
537 * Get the text for the submit button, either customised or a default.
538 * @return unknown_type
540 function getSubmitText() {
541 return $this->mSubmitText
543 : wfMsg( 'htmlform-submit' );
546 public function setSubmitName( $name ) {
547 $this->mSubmitName
= $name;
550 public function setSubmitTooltip( $name ) {
551 $this->mSubmitTooltip
= $name;
555 * Set the id for the submit button.
556 * @param $t String. FIXME: Integrity is *not* validated
558 function setSubmitID( $t ) {
559 $this->mSubmitID
= $t;
562 public function setId( $id ) {
566 * Prompt the whole form to be wrapped in a <fieldset>, with
567 * this text as its <legend> element.
568 * @param $legend String HTML to go inside the <legend> element.
571 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
574 * Set the prefix for various default messages
575 * TODO: currently only used for the <fieldset> legend on forms
576 * with multiple sections; should be used elsewhre?
579 function setMessagePrefix( $p ) {
580 $this->mMessagePrefix
= $p;
584 * Set the title for form submission
585 * @param $t Title of page the form is on/should be posted to
587 function setTitle( $t ) {
595 function getTitle() {
596 return $this->mTitle
;
600 * Set the method used to submit the form
601 * @param $method String
603 public function setMethod( $method='post' ){
604 $this->mMethod
= $method;
607 public function getMethod(){
608 return $this->mMethod
;
615 function displaySection( $fields, $sectionName = '' ) {
617 $subsectionHtml = '';
618 $hasLeftColumn = false;
620 foreach ( $fields as $key => $value ) {
621 if ( is_object( $value ) ) {
622 $v = empty( $value->mParams
['nodata'] )
623 ?
$this->mFieldData
[$key]
624 : $value->getDefault();
625 $tableHtml .= $value->getTableRow( $v );
627 if ( $value->getLabel() != ' ' )
628 $hasLeftColumn = true;
629 } elseif ( is_array( $value ) ) {
630 $section = $this->displaySection( $value, $key );
631 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
632 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
638 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
639 $classes[] = 'mw-htmlform-nolabel';
643 'class' => implode( ' ', $classes ),
646 if ( $sectionName ) {
647 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
650 $tableHtml = Html
::rawElement( 'table', $attribs,
651 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
653 return $subsectionHtml . "\n" . $tableHtml;
657 * Construct the form fields from the Descriptor array
659 function loadData() {
662 $fieldData = array();
664 foreach ( $this->mFlatFields
as $fieldname => $field ) {
665 if ( !empty( $field->mParams
['nodata'] ) ) {
667 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
668 $fieldData[$fieldname] = $field->getDefault();
670 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
675 foreach ( $fieldData as $name => &$value ) {
676 $field = $this->mFlatFields
[$name];
677 $value = $field->filter( $value, $this->mFlatFields
);
680 $this->mFieldData
= $fieldData;
684 * Stop a reset button being shown for this form
685 * @param $suppressReset Bool set to false to re-enable the
688 function suppressReset( $suppressReset = true ) {
689 $this->mShowReset
= !$suppressReset;
693 * Overload this if you want to apply special filtration routines
694 * to the form as a whole, after it's submitted but before it's
697 * @return unknown_type
699 function filterDataForSubmit( $data ) {
705 * The parent class to generate form fields. Any field type should
706 * be a subclass of this.
708 abstract class HTMLFormField
{
710 protected $mValidationCallback;
711 protected $mFilterCallback;
714 protected $mLabel; # String label. Set on construction
716 protected $mClass = '';
721 * This function must be implemented to return the HTML to generate
722 * the input object itself. It should not implement the surrounding
723 * table cells/rows, or labels/help messages.
724 * @param $value String the value to set the input to; eg a default
725 * text for a text input.
726 * @return String valid HTML.
728 abstract function getInputHTML( $value );
731 * Override this function to add specific validation checks on the
732 * field input. Don't forget to call parent::validate() to ensure
733 * that the user-defined callback mValidationCallback is still run
734 * @param $value String the value the field was submitted with
735 * @param $alldata Array the data collected from the form
736 * @return Mixed Bool true on success, or String error to display.
738 function validate( $value, $alldata ) {
739 if ( isset( $this->mValidationCallback
) ) {
740 return call_user_func( $this->mValidationCallback
, $value, $alldata );
743 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
744 return wfMsgExt( 'htmlform-required', 'parseinline' );
750 function filter( $value, $alldata ) {
751 if ( isset( $this->mFilterCallback
) ) {
752 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
759 * Should this field have a label, or is there no input element with the
760 * appropriate id for the label to point to?
762 * @return bool True to output a label, false to suppress
764 protected function needsLabel() {
769 * Get the value that this input has been set to from a posted form,
770 * or the input's default value if it has not been set.
771 * @param $request WebRequest
772 * @return String the value
774 function loadDataFromRequest( $request ) {
775 if ( $request->getCheck( $this->mName
) ) {
776 return $request->getText( $this->mName
);
778 return $this->getDefault();
783 * Initialise the object
784 * @param $params Associative Array. See HTMLForm doc for syntax.
786 function __construct( $params ) {
787 $this->mParams
= $params;
789 # Generate the label from a message, if possible
790 if ( isset( $params['label-message'] ) ) {
791 $msgInfo = $params['label-message'];
793 if ( is_array( $msgInfo ) ) {
794 $msg = array_shift( $msgInfo );
800 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
801 } elseif ( isset( $params['label'] ) ) {
802 $this->mLabel
= $params['label'];
805 $this->mName
= "wp{$params['fieldname']}";
806 if ( isset( $params['name'] ) ) {
807 $this->mName
= $params['name'];
810 $validName = Sanitizer
::escapeId( $this->mName
);
811 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
812 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
815 $this->mID
= "mw-input-{$this->mName}";
817 if ( isset( $params['default'] ) ) {
818 $this->mDefault
= $params['default'];
821 if ( isset( $params['id'] ) ) {
823 $validId = Sanitizer
::escapeId( $id );
825 if ( $id != $validId ) {
826 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
832 if ( isset( $params['cssclass'] ) ) {
833 $this->mClass
= $params['cssclass'];
836 if ( isset( $params['validation-callback'] ) ) {
837 $this->mValidationCallback
= $params['validation-callback'];
840 if ( isset( $params['filter-callback'] ) ) {
841 $this->mFilterCallback
= $params['filter-callback'];
846 * Get the complete table row for the input, including help text,
847 * labels, and whatever.
848 * @param $value String the value to set the input to.
849 * @return String complete HTML table row.
851 function getTableRow( $value ) {
852 # Check for invalid data.
855 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
857 $cellAttributes = array();
858 $verticalLabel = false;
860 if ( !empty($this->mParams
['vertical-label']) ) {
861 $cellAttributes['colspan'] = 2;
862 $verticalLabel = true;
865 if ( $errors === true ||
( !$wgRequest->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
868 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
871 $label = $this->getLabelHtml( $cellAttributes );
872 $field = Html
::rawElement(
874 array( 'class' => 'mw-input' ) +
$cellAttributes,
875 $this->getInputHTML( $value ) . "\n$errors"
878 $fieldType = get_class( $this );
880 if ($verticalLabel) {
881 $html = Html
::rawElement( 'tr',
882 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
883 $html .= Html
::rawElement( 'tr',
884 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
887 $html = Html
::rawElement( 'tr',
888 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
894 if ( isset( $this->mParams
['help-message'] ) ) {
895 $msg = $this->mParams
['help-message'];
896 $helptext = wfMsgExt( $msg, 'parseinline' );
897 if ( wfEmptyMsg( $msg, $helptext ) ) {
901 } elseif ( isset( $this->mParams
['help'] ) ) {
902 $helptext = $this->mParams
['help'];
905 if ( !is_null( $helptext ) ) {
906 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
908 $row = Html
::rawElement( 'tr', array(), $row );
915 function getLabel() {
916 return $this->mLabel
;
918 function getLabelHtml( $cellAttributes = array() ) {
919 # Don't output a for= attribute for labels with no associated input.
920 # Kind of hacky here, possibly we don't want these to be <label>s at all.
923 if ( $this->needsLabel() ) {
924 $for['for'] = $this->mID
;
927 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
928 Html
::rawElement( 'label', $for, $this->getLabel() )
932 function getDefault() {
933 if ( isset( $this->mDefault
) ) {
934 return $this->mDefault
;
941 * Returns the attributes required for the tooltip and accesskey.
943 * @return array Attributes
945 public function getTooltipAndAccessKey() {
946 if ( empty( $this->mParams
['tooltip'] ) ) {
952 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
956 * flatten an array of options to a single array, for instance,
957 * a set of <options> inside <optgroups>.
958 * @param $options Associative Array with values either Strings
960 * @return Array flattened input
962 public static function flattenOptions( $options ) {
965 foreach ( $options as $value ) {
966 if ( is_array( $value ) ) {
967 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
969 $flatOpts[] = $value;
977 class HTMLTextField
extends HTMLFormField
{
979 return isset( $this->mParams
['size'] )
980 ?
$this->mParams
['size']
984 function getInputHTML( $value ) {
987 'name' => $this->mName
,
988 'size' => $this->getSize(),
990 ) +
$this->getTooltipAndAccessKey();
992 if ( isset( $this->mParams
['maxlength'] ) ) {
993 $attribs['maxlength'] = $this->mParams
['maxlength'];
996 if ( !empty( $this->mParams
['disabled'] ) ) {
997 $attribs['disabled'] = 'disabled';
1000 # TODO: Enforce pattern, step, required, readonly on the server side as
1002 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1003 'placeholder' ) as $param ) {
1004 if ( isset( $this->mParams
[$param] ) ) {
1005 $attribs[$param] = $this->mParams
[$param];
1009 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1010 if ( isset( $this->mParams
[$param] ) ) {
1011 $attribs[$param] = '';
1015 # Implement tiny differences between some field variants
1016 # here, rather than creating a new class for each one which
1017 # is essentially just a clone of this one.
1018 if ( isset( $this->mParams
['type'] ) ) {
1019 switch ( $this->mParams
['type'] ) {
1021 $attribs['type'] = 'email';
1024 $attribs['type'] = 'number';
1027 $attribs['type'] = 'number';
1028 $attribs['step'] = 'any';
1033 $attribs['type'] = $this->mParams
['type'];
1038 return Html
::element( 'input', $attribs );
1041 class HTMLTextAreaField
extends HTMLFormField
{
1042 function getCols() {
1043 return isset( $this->mParams
['cols'] )
1044 ?
$this->mParams
['cols']
1048 function getRows() {
1049 return isset( $this->mParams
['rows'] )
1050 ?
$this->mParams
['rows']
1054 function getInputHTML( $value ) {
1057 'name' => $this->mName
,
1058 'cols' => $this->getCols(),
1059 'rows' => $this->getRows(),
1060 ) +
$this->getTooltipAndAccessKey();
1063 if ( !empty( $this->mParams
['disabled'] ) ) {
1064 $attribs['disabled'] = 'disabled';
1067 if ( !empty( $this->mParams
['readonly'] ) ) {
1068 $attribs['readonly'] = 'readonly';
1071 foreach ( array( 'required', 'autofocus' ) as $param ) {
1072 if ( isset( $this->mParams
[$param] ) ) {
1073 $attribs[$param] = '';
1077 return Html
::element( 'textarea', $attribs, $value );
1082 * A field that will contain a numeric value
1084 class HTMLFloatField
extends HTMLTextField
{
1085 function getSize() {
1086 return isset( $this->mParams
['size'] )
1087 ?
$this->mParams
['size']
1091 function validate( $value, $alldata ) {
1092 $p = parent
::validate( $value, $alldata );
1094 if ( $p !== true ) {
1098 $value = trim( $value );
1100 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1101 # with the addition that a leading '+' sign is ok.
1102 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1103 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1106 # The "int" part of these message names is rather confusing.
1107 # They make equal sense for all numbers.
1108 if ( isset( $this->mParams
['min'] ) ) {
1109 $min = $this->mParams
['min'];
1111 if ( $min > $value ) {
1112 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1116 if ( isset( $this->mParams
['max'] ) ) {
1117 $max = $this->mParams
['max'];
1119 if ( $max < $value ) {
1120 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1129 * A field that must contain a number
1131 class HTMLIntField
extends HTMLFloatField
{
1132 function validate( $value, $alldata ) {
1133 $p = parent
::validate( $value, $alldata );
1135 if ( $p !== true ) {
1139 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1140 # with the addition that a leading '+' sign is ok. Note that leading zeros
1141 # are fine, and will be left in the input, which is useful for things like
1142 # phone numbers when you know that they are integers (the HTML5 type=tel
1143 # input does not require its value to be numeric). If you want a tidier
1144 # value to, eg, save in the DB, clean it up with intval().
1145 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1147 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1157 class HTMLCheckField
extends HTMLFormField
{
1158 function getInputHTML( $value ) {
1159 if ( !empty( $this->mParams
['invert'] ) ) {
1163 $attr = $this->getTooltipAndAccessKey();
1164 $attr['id'] = $this->mID
;
1166 if ( !empty( $this->mParams
['disabled'] ) ) {
1167 $attr['disabled'] = 'disabled';
1170 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1171 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1175 * For a checkbox, the label goes on the right hand side, and is
1176 * added in getInputHTML(), rather than HTMLFormField::getRow()
1178 function getLabel() {
1182 function loadDataFromRequest( $request ) {
1184 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1188 // GetCheck won't work like we want for checks.
1189 if ( $request->getCheck( 'wpEditToken' ) ) {
1190 // XOR has the following truth table, which is what we want
1191 // INVERT VALUE | OUTPUT
1192 // true true | false
1193 // false true | true
1194 // false false | false
1195 // true false | true
1196 return $request->getBool( $this->mName
) xor $invert;
1198 return $this->getDefault();
1204 * A select dropdown field. Basically a wrapper for Xmlselect class
1206 class HTMLSelectField
extends HTMLFormField
{
1207 function validate( $value, $alldata ) {
1208 $p = parent
::validate( $value, $alldata );
1210 if ( $p !== true ) {
1214 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1216 if ( in_array( $value, $validOptions ) )
1219 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1222 function getInputHTML( $value ) {
1223 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1225 # If one of the options' 'name' is int(0), it is automatically selected.
1226 # because PHP sucks and things int(0) == 'some string'.
1227 # Working around this by forcing all of them to strings.
1228 foreach( $this->mParams
['options'] as $key => &$opt ){
1229 if( is_int( $opt ) ){
1230 $opt = strval( $opt );
1233 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1235 if ( !empty( $this->mParams
['disabled'] ) ) {
1236 $select->setAttribute( 'disabled', 'disabled' );
1239 $select->addOptions( $this->mParams
['options'] );
1241 return $select->getHTML();
1246 * Select dropdown field, with an additional "other" textbox.
1248 class HTMLSelectOrOtherField
extends HTMLTextField
{
1249 static $jsAdded = false;
1251 function __construct( $params ) {
1252 if ( !in_array( 'other', $params['options'], true ) ) {
1253 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1256 parent
::__construct( $params );
1259 static function forceToStringRecursive( $array ) {
1260 if ( is_array( $array ) ) {
1261 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1263 return strval( $array );
1267 function getInputHTML( $value ) {
1268 $valInSelect = false;
1270 if ( $value !== false ) {
1271 $valInSelect = in_array(
1273 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1277 $selected = $valInSelect ?
$value : 'other';
1279 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1281 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1282 $select->addOptions( $opts );
1284 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1286 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1288 if ( !empty( $this->mParams
['disabled'] ) ) {
1289 $select->setAttribute( 'disabled', 'disabled' );
1290 $tbAttribs['disabled'] = 'disabled';
1293 $select = $select->getHTML();
1295 if ( isset( $this->mParams
['maxlength'] ) ) {
1296 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1299 $textbox = Html
::input(
1300 $this->mName
. '-other',
1301 $valInSelect ?
'' : $value,
1306 return "$select<br />\n$textbox";
1309 function loadDataFromRequest( $request ) {
1310 if ( $request->getCheck( $this->mName
) ) {
1311 $val = $request->getText( $this->mName
);
1313 if ( $val == 'other' ) {
1314 $val = $request->getText( $this->mName
. '-other' );
1319 return $this->getDefault();
1325 * Multi-select field
1327 class HTMLMultiSelectField
extends HTMLFormField
{
1328 function validate( $value, $alldata ) {
1329 $p = parent
::validate( $value, $alldata );
1331 if ( $p !== true ) {
1335 if ( !is_array( $value ) ) {
1339 # If all options are valid, array_intersect of the valid options
1340 # and the provided options will return the provided options.
1341 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1343 $validValues = array_intersect( $value, $validOptions );
1344 if ( count( $validValues ) == count( $value ) ) {
1347 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1351 function getInputHTML( $value ) {
1352 $html = $this->formatOptions( $this->mParams
['options'], $value );
1357 function formatOptions( $options, $value ) {
1362 if ( !empty( $this->mParams
['disabled'] ) ) {
1363 $attribs['disabled'] = 'disabled';
1366 foreach ( $options as $label => $info ) {
1367 if ( is_array( $info ) ) {
1368 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1369 $html .= $this->formatOptions( $info, $value );
1371 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1373 $checkbox = Xml
::check(
1374 $this->mName
. '[]',
1375 in_array( $info, $value, true ),
1376 $attribs +
$thisAttribs );
1377 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1379 $html .= $checkbox . '<br />';
1386 function loadDataFromRequest( $request ) {
1387 # won't work with getCheck
1388 if ( $request->getCheck( 'wpEditToken' ) ) {
1389 $arr = $request->getArray( $this->mName
);
1397 return $this->getDefault();
1401 function getDefault() {
1402 if ( isset( $this->mDefault
) ) {
1403 return $this->mDefault
;
1409 protected function needsLabel() {
1415 * Radio checkbox fields.
1417 class HTMLRadioField
extends HTMLFormField
{
1418 function validate( $value, $alldata ) {
1419 $p = parent
::validate( $value, $alldata );
1421 if ( $p !== true ) {
1425 if ( !is_string( $value ) && !is_int( $value ) ) {
1429 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1431 if ( in_array( $value, $validOptions ) ) {
1434 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1439 * This returns a block of all the radio options, in one cell.
1440 * @see includes/HTMLFormField#getInputHTML()
1442 function getInputHTML( $value ) {
1443 $html = $this->formatOptions( $this->mParams
['options'], $value );
1448 function formatOptions( $options, $value ) {
1452 if ( !empty( $this->mParams
['disabled'] ) ) {
1453 $attribs['disabled'] = 'disabled';
1456 # TODO: should this produce an unordered list perhaps?
1457 foreach ( $options as $label => $info ) {
1458 if ( is_array( $info ) ) {
1459 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1460 $html .= $this->formatOptions( $info, $value );
1462 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1463 $html .= Xml
::radio(
1467 $attribs +
array( 'id' => $id )
1470 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1472 $html .= "<br />\n";
1479 protected function needsLabel() {
1485 * An information field (text blob), not a proper input.
1487 class HTMLInfoField
extends HTMLFormField
{
1488 function __construct( $info ) {
1489 $info['nodata'] = true;
1491 parent
::__construct( $info );
1494 function getInputHTML( $value ) {
1495 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1498 function getTableRow( $value ) {
1499 if ( !empty( $this->mParams
['rawrow'] ) ) {
1503 return parent
::getTableRow( $value );
1506 protected function needsLabel() {
1511 class HTMLHiddenField
extends HTMLFormField
{
1512 public function __construct( $params ) {
1513 parent
::__construct( $params );
1515 # Per HTML5 spec, hidden fields cannot be 'required'
1516 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1517 unset( $this->mParams
['required'] );
1520 public function getTableRow( $value ) {
1523 $params['id'] = $this->mID
;
1526 $this->mParent
->addHiddenField(
1535 public function getInputHTML( $value ) { return ''; }
1539 * Add a submit button inline in the form (as opposed to
1540 * HTMLForm::addButton(), which will add it at the end).
1542 class HTMLSubmitField
extends HTMLFormField
{
1544 function __construct( $info ) {
1545 $info['nodata'] = true;
1546 parent
::__construct( $info );
1549 function getInputHTML( $value ) {
1550 return Xml
::submitButton(
1553 'class' => 'mw-htmlform-submit',
1554 'name' => $this->mName
,
1560 protected function needsLabel() {
1565 * Button cannot be invalid
1567 public function validate( $value, $alldata ){
1572 class HTMLEditTools
extends HTMLFormField
{
1573 public function getInputHTML( $value ) {
1577 public function getTableRow( $value ) {
1578 return "<tr><td></td><td class=\"mw-input\">"
1579 . '<div class="mw-editTools">'
1580 . wfMsgExt( empty( $this->mParams
['message'] )
1581 ?
'edittools' : $this->mParams
['message'],
1582 array( 'parse', 'content' ) )
1583 . "</div></td></tr>\n";