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
56 class HTMLForm
extends ContextSource
{
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;
109 protected $mMethod = 'post';
112 * Form action URL. false means we will use the URL to set Title
116 protected $mAction = false;
118 protected $mUseMultipart = false;
119 protected $mHiddenFields = array();
120 protected $mButtons = array();
122 protected $mWrapperLegend = false;
125 * If true, sections that contain both fields and subsections will
126 * render their subsections before their fields.
128 * Subclasses may set this to false to render subsections after fields
131 protected $mSubSectionBeforeFields = true;
134 * Build a new HTMLForm from an array of field attributes
135 * @param $descriptor Array of Field constructs, as described above
136 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
137 * Obviates the need to call $form->setTitle()
138 * @param $messagePrefix String a prefix to go in front of default messages
140 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
141 if( $context instanceof IContextSource
){
142 $this->setContext( $context );
143 $this->mTitle
= false; // We don't need them to set a title
144 $this->mMessagePrefix
= $messagePrefix;
147 if( is_string( $context ) && $messagePrefix === '' ){
148 // it's actually $messagePrefix
149 $this->mMessagePrefix
= $context;
153 // Expand out into a tree.
154 $loadedDescriptor = array();
155 $this->mFlatFields
= array();
157 foreach ( $descriptor as $fieldname => $info ) {
158 $section = isset( $info['section'] )
162 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
163 $this->mUseMultipart
= true;
166 $field = self
::loadInputFromParameters( $fieldname, $info );
167 $field->mParent
= $this;
169 $setSection =& $loadedDescriptor;
171 $sectionParts = explode( '/', $section );
173 while ( count( $sectionParts ) ) {
174 $newName = array_shift( $sectionParts );
176 if ( !isset( $setSection[$newName] ) ) {
177 $setSection[$newName] = array();
180 $setSection =& $setSection[$newName];
184 $setSection[$fieldname] = $field;
185 $this->mFlatFields
[$fieldname] = $field;
188 $this->mFieldTree
= $loadedDescriptor;
192 * Add the HTMLForm-specific JavaScript, if it hasn't been
194 * @deprecated since 1.18 load modules with ResourceLoader instead
196 static function addJS() { wfDeprecated( __METHOD__
, '1.18' ); }
199 * Initialise a new Object for the field
200 * @param $fieldname string
201 * @param $descriptor string input Descriptor, as described above
202 * @return HTMLFormField subclass
204 static function loadInputFromParameters( $fieldname, $descriptor ) {
205 if ( isset( $descriptor['class'] ) ) {
206 $class = $descriptor['class'];
207 } elseif ( isset( $descriptor['type'] ) ) {
208 $class = self
::$typeMappings[$descriptor['type']];
209 $descriptor['class'] = $class;
215 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
218 $descriptor['fieldname'] = $fieldname;
221 # This will throw a fatal error whenever someone try to use
222 # 'class' to feed a CSS class instead of 'cssclass'. Would be
223 # great to avoid the fatal error and show a nice error.
224 $obj = new $class( $descriptor );
230 * Prepare form for submission
232 function prepareForm() {
233 # Check if we have the info we need
234 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
235 throw new MWException( "You must call setTitle() on an HTMLForm" );
238 # Load data from the request.
243 * Try submitting, with edit token check first
244 * @return Status|boolean
246 function tryAuthorizedSubmit() {
250 if ( $this->getMethod() != 'post' ) {
251 $submit = true; // no session check needed
252 } elseif ( $this->getRequest()->wasPosted() ) {
253 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
254 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
255 // Session tokens for logged-out users have no security value.
256 // However, if the user gave one, check it in order to give a nice
257 // "session expired" error instead of "permission denied" or such.
258 $submit = $this->getUser()->matchEditToken( $editToken );
265 $result = $this->trySubmit();
272 * The here's-one-I-made-earlier option: do the submission if
273 * posted, or display the form with or without funky valiation
275 * @return Bool or Status whether submission was successful.
278 $this->prepareForm();
280 $result = $this->tryAuthorizedSubmit();
281 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
285 $this->displayForm( $result );
290 * Validate all the fields, and call the submision callback
291 * function if everything is kosher.
292 * @return Mixed Bool true == Successful submission, Bool false
293 * == No submission attempted, anything else == Error to
296 function trySubmit() {
297 # Check for validation
298 foreach ( $this->mFlatFields
as $fieldname => $field ) {
299 if ( !empty( $field->mParams
['nodata'] ) ) {
302 if ( $field->validate(
303 $this->mFieldData
[$fieldname],
307 return isset( $this->mValidationErrorMessage
)
308 ?
$this->mValidationErrorMessage
309 : array( 'htmlform-invalid-input' );
313 $callback = $this->mSubmitCallback
;
315 $data = $this->filterDataForSubmit( $this->mFieldData
);
317 $res = call_user_func( $callback, $data, $this );
323 * Set a callback to a function to do something with the form
324 * once it's been successfully validated.
325 * @param $cb String function name. The function will be passed
326 * the output from HTMLForm::filterDataForSubmit, and must
327 * return Bool true on success, Bool false if no submission
328 * was attempted, or String HTML output to display on error.
330 function setSubmitCallback( $cb ) {
331 $this->mSubmitCallback
= $cb;
335 * Set a message to display on a validation error.
336 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
337 * (so each entry can be either a String or Array)
339 function setValidationErrorMessage( $msg ) {
340 $this->mValidationErrorMessage
= $msg;
344 * Set the introductory message, overwriting any existing message.
345 * @param $msg String complete text of message to display
347 function setIntro( $msg ) {
348 $this->setPreText( $msg );
352 * Set the introductory message, overwriting any existing message.
354 * @param $msg String complete text of message to display
356 function setPreText( $msg ) { $this->mPre
= $msg; }
359 * Add introductory text.
360 * @param $msg String complete text of message to display
362 function addPreText( $msg ) { $this->mPre
.= $msg; }
365 * Add header text, inside the form.
366 * @param $msg String complete text of message to display
367 * @param $section string The section to add the header to
369 function addHeaderText( $msg, $section = null ) {
370 if ( is_null( $section ) ) {
371 $this->mHeader
.= $msg;
373 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
374 $this->mSectionHeaders
[$section] = '';
376 $this->mSectionHeaders
[$section] .= $msg;
381 * Set header text, inside the form.
383 * @param $msg String complete text of message to display
384 * @param $section The section to add the header to
386 function setHeaderText( $msg, $section = null ) {
387 if ( is_null( $section ) ) {
388 $this->mHeader
= $msg;
390 $this->mSectionHeaders
[$section] = $msg;
395 * Add footer text, inside the form.
396 * @param $msg String complete text of message to display
397 * @param $section string The section to add the footer text to
399 function addFooterText( $msg, $section = null ) {
400 if ( is_null( $section ) ) {
401 $this->mFooter
.= $msg;
403 if ( !isset( $this->mSectionFooters
[$section] ) ) {
404 $this->mSectionFooters
[$section] = '';
406 $this->mSectionFooters
[$section] .= $msg;
411 * Set footer text, inside the form.
413 * @param $msg String complete text of message to display
414 * @param $section string The section to add the footer text to
416 function setFooterText( $msg, $section = null ) {
417 if ( is_null( $section ) ) {
418 $this->mFooter
= $msg;
420 $this->mSectionFooters
[$section] = $msg;
425 * Add text to the end of the display.
426 * @param $msg String complete text of message to display
428 function addPostText( $msg ) { $this->mPost
.= $msg; }
431 * Set text at the end of the display.
432 * @param $msg String complete text of message to display
434 function setPostText( $msg ) { $this->mPost
= $msg; }
437 * Add a hidden field to the output
438 * @param $name String field name. This will be used exactly as entered
439 * @param $value String field value
440 * @param $attribs Array
442 public function addHiddenField( $name, $value, $attribs = array() ) {
443 $attribs +
= array( 'name' => $name );
444 $this->mHiddenFields
[] = array( $value, $attribs );
447 public function addButton( $name, $value, $id = null, $attribs = null ) {
448 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
452 * Display the form (sending to $wgOut), with an appropriate error
453 * message or stack of messages, and any validation errors, etc.
454 * @param $submitResult Mixed output from HTMLForm::trySubmit()
456 function displayForm( $submitResult ) {
457 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
461 * Returns the raw HTML generated by the form
462 * @param $submitResult Mixed output from HTMLForm::trySubmit()
465 function getHTML( $submitResult ) {
466 # For good measure (it is the default)
467 $this->getOutput()->preventClickjacking();
468 $this->getOutput()->addModules( 'mediawiki.htmlform' );
471 . $this->getErrors( $submitResult )
474 . $this->getHiddenFields()
475 . $this->getButtons()
479 $html = $this->wrapForm( $html );
481 return '' . $this->mPre
. $html . $this->mPost
;
485 * Wrap the form innards in an actual <form> element
486 * @param $html String HTML contents to wrap.
487 * @return String wrapped HTML.
489 function wrapForm( $html ) {
491 # Include a <fieldset> wrapper for style, if requested.
492 if ( $this->mWrapperLegend
!== false ) {
493 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
495 # Use multipart/form-data
496 $encType = $this->mUseMultipart
497 ?
'multipart/form-data'
498 : 'application/x-www-form-urlencoded';
501 'action' => $this->mAction
=== false ?
$this->getTitle()->getFullURL() : $this->mAction
,
502 'method' => $this->mMethod
,
503 'class' => 'visualClear',
504 'enctype' => $encType,
506 if ( !empty( $this->mId
) ) {
507 $attribs['id'] = $this->mId
;
510 return Html
::rawElement( 'form', $attribs, $html );
514 * Get the hidden fields that should go inside the form.
515 * @return String HTML.
517 function getHiddenFields() {
518 global $wgUsePathInfo;
521 if( $this->getMethod() == 'post' ){
522 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
523 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
526 if ( !$wgUsePathInfo && $this->getMethod() == 'get' ) {
527 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
530 foreach ( $this->mHiddenFields
as $data ) {
531 list( $value, $attribs ) = $data;
532 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
539 * Get the submit and (potentially) reset buttons.
540 * @return String HTML.
542 function getButtons() {
546 if ( isset( $this->mSubmitID
) ) {
547 $attribs['id'] = $this->mSubmitID
;
550 if ( isset( $this->mSubmitName
) ) {
551 $attribs['name'] = $this->mSubmitName
;
554 if ( isset( $this->mSubmitTooltip
) ) {
555 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
558 $attribs['class'] = 'mw-htmlform-submit';
560 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
562 if ( $this->mShowReset
) {
563 $html .= Html
::element(
567 'value' => wfMsg( 'htmlform-reset' )
572 foreach ( $this->mButtons
as $button ) {
575 'name' => $button['name'],
576 'value' => $button['value']
579 if ( $button['attribs'] ) {
580 $attrs +
= $button['attribs'];
583 if ( isset( $button['id'] ) ) {
584 $attrs['id'] = $button['id'];
587 $html .= Html
::element( 'input', $attrs );
594 * Get the whole body of the form.
598 return $this->displaySection( $this->mFieldTree
);
602 * Format and display an error message stack.
603 * @param $errors String|Array|Status
606 function getErrors( $errors ) {
607 if ( $errors instanceof Status
) {
608 if ( $errors->isOK() ) {
611 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
613 } elseif ( is_array( $errors ) ) {
614 $errorstr = $this->formatErrors( $errors );
620 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
625 * Format a stack of error messages into a single HTML string
626 * @param $errors Array of message keys/values
627 * @return String HTML, a <ul> list of errors
629 public static function formatErrors( $errors ) {
632 foreach ( $errors as $error ) {
633 if ( is_array( $error ) ) {
634 $msg = array_shift( $error );
640 $errorstr .= Html
::rawElement(
643 wfMsgExt( $msg, array( 'parseinline' ), $error )
647 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
653 * Set the text for the submit button
654 * @param $t String plaintext.
656 function setSubmitText( $t ) {
657 $this->mSubmitText
= $t;
661 * Set the text for the submit button to a message
663 * @param $msg String message key
665 public function setSubmitTextMsg( $msg ) {
666 return $this->setSubmitText( $this->msg( $msg )->escaped() );
670 * Get the text for the submit button, either customised or a default.
673 function getSubmitText() {
674 return $this->mSubmitText
676 : wfMsg( 'htmlform-submit' );
679 public function setSubmitName( $name ) {
680 $this->mSubmitName
= $name;
683 public function setSubmitTooltip( $name ) {
684 $this->mSubmitTooltip
= $name;
688 * Set the id for the submit button.
690 * @todo FIXME: Integrity of $t is *not* validated
692 function setSubmitID( $t ) {
693 $this->mSubmitID
= $t;
696 public function setId( $id ) {
700 * Prompt the whole form to be wrapped in a <fieldset>, with
701 * this text as its <legend> element.
702 * @param $legend String HTML to go inside the <legend> element.
705 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
708 * Prompt the whole form to be wrapped in a <fieldset>, with
709 * this message as its <legend> element.
711 * @param $msg String message key
713 public function setWrapperLegendMsg( $msg ) {
714 return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
718 * Set the prefix for various default messages
719 * TODO: currently only used for the <fieldset> legend on forms
720 * with multiple sections; should be used elsewhre?
723 function setMessagePrefix( $p ) {
724 $this->mMessagePrefix
= $p;
728 * Set the title for form submission
729 * @param $t Title of page the form is on/should be posted to
731 function setTitle( $t ) {
739 function getTitle() {
740 return $this->mTitle
=== false
741 ?
$this->getContext()->getTitle()
746 * Set the method used to submit the form
747 * @param $method String
749 public function setMethod( $method = 'post' ) {
750 $this->mMethod
= $method;
753 public function getMethod() {
754 return $this->mMethod
;
759 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
760 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
761 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
764 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
766 $subsectionHtml = '';
767 $hasLeftColumn = false;
769 foreach ( $fields as $key => $value ) {
770 if ( is_object( $value ) ) {
771 $v = empty( $value->mParams
['nodata'] )
772 ?
$this->mFieldData
[$key]
773 : $value->getDefault();
774 $tableHtml .= $value->getTableRow( $v );
776 if ( $value->getLabel() != ' ' ) {
777 $hasLeftColumn = true;
779 } elseif ( is_array( $value ) ) {
780 $section = $this->displaySection( $value, $key );
781 $legend = $this->getLegend( $key );
782 if ( isset( $this->mSectionHeaders
[$key] ) ) {
783 $section = $this->mSectionHeaders
[$key] . $section;
785 if ( isset( $this->mSectionFooters
[$key] ) ) {
786 $section .= $this->mSectionFooters
[$key];
788 $attributes = array();
789 if ( $fieldsetIDPrefix ) {
790 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
792 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
798 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
799 $classes[] = 'mw-htmlform-nolabel';
803 'class' => implode( ' ', $classes ),
806 if ( $sectionName ) {
807 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
810 $tableHtml = Html
::rawElement( 'table', $attribs,
811 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
813 if ( $this->mSubSectionBeforeFields
) {
814 return $subsectionHtml . "\n" . $tableHtml;
816 return $tableHtml . "\n" . $subsectionHtml;
821 * Construct the form fields from the Descriptor array
823 function loadData() {
824 $fieldData = array();
826 foreach ( $this->mFlatFields
as $fieldname => $field ) {
827 if ( !empty( $field->mParams
['nodata'] ) ) {
829 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
830 $fieldData[$fieldname] = $field->getDefault();
832 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
837 foreach ( $fieldData as $name => &$value ) {
838 $field = $this->mFlatFields
[$name];
839 $value = $field->filter( $value, $this->mFlatFields
);
842 $this->mFieldData
= $fieldData;
846 * Stop a reset button being shown for this form
847 * @param $suppressReset Bool set to false to re-enable the
850 function suppressReset( $suppressReset = true ) {
851 $this->mShowReset
= !$suppressReset;
855 * Overload this if you want to apply special filtration routines
856 * to the form as a whole, after it's submitted but before it's
861 function filterDataForSubmit( $data ) {
866 * Get a string to go in the <legend> of a section fieldset. Override this if you
867 * want something more complicated
871 public function getLegend( $key ) {
872 return wfMsg( "{$this->mMessagePrefix}-$key" );
876 * Set the value for the action attribute of the form.
877 * When set to false (which is the default state), the set title is used.
881 * @param string|bool $action
883 public function setAction( $action ) {
884 $this->mAction
= $action;
890 * The parent class to generate form fields. Any field type should
891 * be a subclass of this.
893 abstract class HTMLFormField
{
895 protected $mValidationCallback;
896 protected $mFilterCallback;
899 protected $mLabel; # String label. Set on construction
901 protected $mClass = '';
910 * This function must be implemented to return the HTML to generate
911 * the input object itself. It should not implement the surrounding
912 * table cells/rows, or labels/help messages.
913 * @param $value String the value to set the input to; eg a default
914 * text for a text input.
915 * @return String valid HTML.
917 abstract function getInputHTML( $value );
920 * Override this function to add specific validation checks on the
921 * field input. Don't forget to call parent::validate() to ensure
922 * that the user-defined callback mValidationCallback is still run
923 * @param $value String the value the field was submitted with
924 * @param $alldata Array the data collected from the form
925 * @return Mixed Bool true on success, or String error to display.
927 function validate( $value, $alldata ) {
928 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
929 return wfMsgExt( 'htmlform-required', 'parseinline' );
932 if ( isset( $this->mValidationCallback
) ) {
933 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
939 function filter( $value, $alldata ) {
940 if ( isset( $this->mFilterCallback
) ) {
941 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
948 * Should this field have a label, or is there no input element with the
949 * appropriate id for the label to point to?
951 * @return bool True to output a label, false to suppress
953 protected function needsLabel() {
958 * Get the value that this input has been set to from a posted form,
959 * or the input's default value if it has not been set.
960 * @param $request WebRequest
961 * @return String the value
963 function loadDataFromRequest( $request ) {
964 if ( $request->getCheck( $this->mName
) ) {
965 return $request->getText( $this->mName
);
967 return $this->getDefault();
972 * Initialise the object
973 * @param $params array Associative Array. See HTMLForm doc for syntax.
975 function __construct( $params ) {
976 $this->mParams
= $params;
978 # Generate the label from a message, if possible
979 if ( isset( $params['label-message'] ) ) {
980 $msgInfo = $params['label-message'];
982 if ( is_array( $msgInfo ) ) {
983 $msg = array_shift( $msgInfo );
989 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
990 } elseif ( isset( $params['label'] ) ) {
991 $this->mLabel
= $params['label'];
994 $this->mName
= "wp{$params['fieldname']}";
995 if ( isset( $params['name'] ) ) {
996 $this->mName
= $params['name'];
999 $validName = Sanitizer
::escapeId( $this->mName
);
1000 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1001 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1004 $this->mID
= "mw-input-{$this->mName}";
1006 if ( isset( $params['default'] ) ) {
1007 $this->mDefault
= $params['default'];
1010 if ( isset( $params['id'] ) ) {
1011 $id = $params['id'];
1012 $validId = Sanitizer
::escapeId( $id );
1014 if ( $id != $validId ) {
1015 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1021 if ( isset( $params['cssclass'] ) ) {
1022 $this->mClass
= $params['cssclass'];
1025 if ( isset( $params['validation-callback'] ) ) {
1026 $this->mValidationCallback
= $params['validation-callback'];
1029 if ( isset( $params['filter-callback'] ) ) {
1030 $this->mFilterCallback
= $params['filter-callback'];
1033 if ( isset( $params['flatlist'] ) ){
1034 $this->mClass
.= ' mw-htmlform-flatlist';
1039 * Get the complete table row for the input, including help text,
1040 * labels, and whatever.
1041 * @param $value String the value to set the input to.
1042 * @return String complete HTML table row.
1044 function getTableRow( $value ) {
1045 # Check for invalid data.
1047 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1049 $cellAttributes = array();
1050 $verticalLabel = false;
1052 if ( !empty($this->mParams
['vertical-label']) ) {
1053 $cellAttributes['colspan'] = 2;
1054 $verticalLabel = true;
1057 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1061 $errors = self
::formatErrors( $errors );
1062 $errorClass = 'mw-htmlform-invalid-input';
1065 $label = $this->getLabelHtml( $cellAttributes );
1066 $field = Html
::rawElement(
1068 array( 'class' => 'mw-input' ) +
$cellAttributes,
1069 $this->getInputHTML( $value ) . "\n$errors"
1072 $fieldType = get_class( $this );
1074 if ( $verticalLabel ) {
1075 $html = Html
::rawElement( 'tr',
1076 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1077 $html .= Html
::rawElement( 'tr',
1078 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1081 $html = Html
::rawElement( 'tr',
1082 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1088 if ( isset( $this->mParams
['help-message'] ) ) {
1089 $msg = wfMessage( $this->mParams
['help-message'] );
1090 if ( $msg->exists() ) {
1091 $helptext = $msg->parse();
1093 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
1094 # help-message can be passed a message key (string) or an array containing
1095 # a message key and additional parameters. This makes it impossible to pass
1096 # an array of message key
1097 foreach( $this->mParams
['help-messages'] as $name ) {
1098 $msg = wfMessage( $name );
1099 if( $msg->exists() ) {
1100 $helptext .= $msg->parse(); // append message
1103 } elseif ( isset( $this->mParams
['help'] ) ) {
1104 $helptext = $this->mParams
['help'];
1107 if ( !is_null( $helptext ) ) {
1108 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1110 $row = Html
::rawElement( 'tr', array(), $row );
1117 function getLabel() {
1118 return $this->mLabel
;
1120 function getLabelHtml( $cellAttributes = array() ) {
1121 # Don't output a for= attribute for labels with no associated input.
1122 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1125 if ( $this->needsLabel() ) {
1126 $for['for'] = $this->mID
;
1129 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1130 Html
::rawElement( 'label', $for, $this->getLabel() )
1134 function getDefault() {
1135 if ( isset( $this->mDefault
) ) {
1136 return $this->mDefault
;
1143 * Returns the attributes required for the tooltip and accesskey.
1145 * @return array Attributes
1147 public function getTooltipAndAccessKey() {
1148 if ( empty( $this->mParams
['tooltip'] ) ) {
1151 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1155 * flatten an array of options to a single array, for instance,
1156 * a set of <options> inside <optgroups>.
1157 * @param $options array Associative Array with values either Strings
1159 * @return Array flattened input
1161 public static function flattenOptions( $options ) {
1162 $flatOpts = array();
1164 foreach ( $options as $value ) {
1165 if ( is_array( $value ) ) {
1166 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1168 $flatOpts[] = $value;
1176 * Formats one or more errors as accepted by field validation-callback.
1177 * @param $errors String|Message|Array of strings or Message instances
1178 * @return String html
1181 protected static function formatErrors( $errors ) {
1182 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1183 $errors = array_shift( $errors );
1186 if ( is_array( $errors ) ) {
1188 foreach ( $errors as $error ) {
1189 if ( $error instanceof Message
) {
1190 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1192 $lines[] = Html
::rawElement( 'li', array(), $error );
1195 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1197 if ( $errors instanceof Message
) {
1198 $errors = $errors->parse();
1200 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1205 class HTMLTextField
extends HTMLFormField
{
1206 function getSize() {
1207 return isset( $this->mParams
['size'] )
1208 ?
$this->mParams
['size']
1212 function getInputHTML( $value ) {
1215 'name' => $this->mName
,
1216 'size' => $this->getSize(),
1218 ) +
$this->getTooltipAndAccessKey();
1220 if ( $this->mClass
!== '' ) {
1221 $attribs['class'] = $this->mClass
;
1224 if ( isset( $this->mParams
['maxlength'] ) ) {
1225 $attribs['maxlength'] = $this->mParams
['maxlength'];
1228 if ( !empty( $this->mParams
['disabled'] ) ) {
1229 $attribs['disabled'] = 'disabled';
1232 # TODO: Enforce pattern, step, required, readonly on the server side as
1234 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1235 'placeholder' ) as $param ) {
1236 if ( isset( $this->mParams
[$param] ) ) {
1237 $attribs[$param] = $this->mParams
[$param];
1241 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1242 if ( isset( $this->mParams
[$param] ) ) {
1243 $attribs[$param] = '';
1247 # Implement tiny differences between some field variants
1248 # here, rather than creating a new class for each one which
1249 # is essentially just a clone of this one.
1250 if ( isset( $this->mParams
['type'] ) ) {
1251 switch ( $this->mParams
['type'] ) {
1253 $attribs['type'] = 'email';
1256 $attribs['type'] = 'number';
1259 $attribs['type'] = 'number';
1260 $attribs['step'] = 'any';
1265 $attribs['type'] = $this->mParams
['type'];
1270 return Html
::element( 'input', $attribs );
1273 class HTMLTextAreaField
extends HTMLFormField
{
1274 function getCols() {
1275 return isset( $this->mParams
['cols'] )
1276 ?
$this->mParams
['cols']
1280 function getRows() {
1281 return isset( $this->mParams
['rows'] )
1282 ?
$this->mParams
['rows']
1286 function getInputHTML( $value ) {
1289 'name' => $this->mName
,
1290 'cols' => $this->getCols(),
1291 'rows' => $this->getRows(),
1292 ) +
$this->getTooltipAndAccessKey();
1294 if ( $this->mClass
!== '' ) {
1295 $attribs['class'] = $this->mClass
;
1298 if ( !empty( $this->mParams
['disabled'] ) ) {
1299 $attribs['disabled'] = 'disabled';
1302 if ( !empty( $this->mParams
['readonly'] ) ) {
1303 $attribs['readonly'] = 'readonly';
1306 foreach ( array( 'required', 'autofocus' ) as $param ) {
1307 if ( isset( $this->mParams
[$param] ) ) {
1308 $attribs[$param] = '';
1312 return Html
::element( 'textarea', $attribs, $value );
1317 * A field that will contain a numeric value
1319 class HTMLFloatField
extends HTMLTextField
{
1320 function getSize() {
1321 return isset( $this->mParams
['size'] )
1322 ?
$this->mParams
['size']
1326 function validate( $value, $alldata ) {
1327 $p = parent
::validate( $value, $alldata );
1329 if ( $p !== true ) {
1333 $value = trim( $value );
1335 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1336 # with the addition that a leading '+' sign is ok.
1337 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1338 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1341 # The "int" part of these message names is rather confusing.
1342 # They make equal sense for all numbers.
1343 if ( isset( $this->mParams
['min'] ) ) {
1344 $min = $this->mParams
['min'];
1346 if ( $min > $value ) {
1347 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1351 if ( isset( $this->mParams
['max'] ) ) {
1352 $max = $this->mParams
['max'];
1354 if ( $max < $value ) {
1355 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1364 * A field that must contain a number
1366 class HTMLIntField
extends HTMLFloatField
{
1367 function validate( $value, $alldata ) {
1368 $p = parent
::validate( $value, $alldata );
1370 if ( $p !== true ) {
1374 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1375 # with the addition that a leading '+' sign is ok. Note that leading zeros
1376 # are fine, and will be left in the input, which is useful for things like
1377 # phone numbers when you know that they are integers (the HTML5 type=tel
1378 # input does not require its value to be numeric). If you want a tidier
1379 # value to, eg, save in the DB, clean it up with intval().
1380 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1382 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1392 class HTMLCheckField
extends HTMLFormField
{
1393 function getInputHTML( $value ) {
1394 if ( !empty( $this->mParams
['invert'] ) ) {
1398 $attr = $this->getTooltipAndAccessKey();
1399 $attr['id'] = $this->mID
;
1401 if ( !empty( $this->mParams
['disabled'] ) ) {
1402 $attr['disabled'] = 'disabled';
1405 if ( $this->mClass
!== '' ) {
1406 $attr['class'] = $this->mClass
;
1409 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1410 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1414 * For a checkbox, the label goes on the right hand side, and is
1415 * added in getInputHTML(), rather than HTMLFormField::getRow()
1418 function getLabel() {
1423 * @param $request WebRequest
1426 function loadDataFromRequest( $request ) {
1428 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1432 // GetCheck won't work like we want for checks.
1433 // Fetch the value in either one of the two following case:
1434 // - we have a valid token (form got posted or GET forged by the user)
1435 // - checkbox name has a value (false or true), ie is not null
1436 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
)!== null ) {
1437 // XOR has the following truth table, which is what we want
1438 // INVERT VALUE | OUTPUT
1439 // true true | false
1440 // false true | true
1441 // false false | false
1442 // true false | true
1443 return $request->getBool( $this->mName
) xor $invert;
1445 return $this->getDefault();
1451 * A select dropdown field. Basically a wrapper for Xmlselect class
1453 class HTMLSelectField
extends HTMLFormField
{
1454 function validate( $value, $alldata ) {
1455 $p = parent
::validate( $value, $alldata );
1457 if ( $p !== true ) {
1461 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1463 if ( in_array( $value, $validOptions ) )
1466 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1469 function getInputHTML( $value ) {
1470 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1472 # If one of the options' 'name' is int(0), it is automatically selected.
1473 # because PHP sucks and thinks int(0) == 'some string'.
1474 # Working around this by forcing all of them to strings.
1475 foreach( $this->mParams
['options'] as &$opt ){
1476 if( is_int( $opt ) ){
1477 $opt = strval( $opt );
1480 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1482 if ( !empty( $this->mParams
['disabled'] ) ) {
1483 $select->setAttribute( 'disabled', 'disabled' );
1486 if ( $this->mClass
!== '' ) {
1487 $select->setAttribute( 'class', $this->mClass
);
1490 $select->addOptions( $this->mParams
['options'] );
1492 return $select->getHTML();
1497 * Select dropdown field, with an additional "other" textbox.
1499 class HTMLSelectOrOtherField
extends HTMLTextField
{
1500 static $jsAdded = false;
1502 function __construct( $params ) {
1503 if ( !in_array( 'other', $params['options'], true ) ) {
1504 $msg = isset( $params['other'] ) ?
$params['other'] : wfMsg( 'htmlform-selectorother-other' );
1505 $params['options'][$msg] = 'other';
1508 parent
::__construct( $params );
1511 static function forceToStringRecursive( $array ) {
1512 if ( is_array( $array ) ) {
1513 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1515 return strval( $array );
1519 function getInputHTML( $value ) {
1520 $valInSelect = false;
1522 if ( $value !== false ) {
1523 $valInSelect = in_array(
1525 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1529 $selected = $valInSelect ?
$value : 'other';
1531 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1533 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1534 $select->addOptions( $opts );
1536 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1538 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1540 if ( !empty( $this->mParams
['disabled'] ) ) {
1541 $select->setAttribute( 'disabled', 'disabled' );
1542 $tbAttribs['disabled'] = 'disabled';
1545 $select = $select->getHTML();
1547 if ( isset( $this->mParams
['maxlength'] ) ) {
1548 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1551 if ( $this->mClass
!== '' ) {
1552 $tbAttribs['class'] = $this->mClass
;
1555 $textbox = Html
::input(
1556 $this->mName
. '-other',
1557 $valInSelect ?
'' : $value,
1562 return "$select<br />\n$textbox";
1566 * @param $request WebRequest
1569 function loadDataFromRequest( $request ) {
1570 if ( $request->getCheck( $this->mName
) ) {
1571 $val = $request->getText( $this->mName
);
1573 if ( $val == 'other' ) {
1574 $val = $request->getText( $this->mName
. '-other' );
1579 return $this->getDefault();
1585 * Multi-select field
1587 class HTMLMultiSelectField
extends HTMLFormField
{
1589 function validate( $value, $alldata ) {
1590 $p = parent
::validate( $value, $alldata );
1592 if ( $p !== true ) {
1596 if ( !is_array( $value ) ) {
1600 # If all options are valid, array_intersect of the valid options
1601 # and the provided options will return the provided options.
1602 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1604 $validValues = array_intersect( $value, $validOptions );
1605 if ( count( $validValues ) == count( $value ) ) {
1608 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1612 function getInputHTML( $value ) {
1613 $html = $this->formatOptions( $this->mParams
['options'], $value );
1618 function formatOptions( $options, $value ) {
1623 if ( !empty( $this->mParams
['disabled'] ) ) {
1624 $attribs['disabled'] = 'disabled';
1627 foreach ( $options as $label => $info ) {
1628 if ( is_array( $info ) ) {
1629 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1630 $html .= $this->formatOptions( $info, $value );
1632 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1634 $checkbox = Xml
::check(
1635 $this->mName
. '[]',
1636 in_array( $info, $value, true ),
1637 $attribs +
$thisAttribs );
1638 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1640 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1648 * @param $request WebRequest
1651 function loadDataFromRequest( $request ) {
1652 if ( $this->mParent
->getMethod() == 'post' ) {
1653 if( $request->wasPosted() ){
1654 # Checkboxes are just not added to the request arrays if they're not checked,
1655 # so it's perfectly possible for there not to be an entry at all
1656 return $request->getArray( $this->mName
, array() );
1658 # That's ok, the user has not yet submitted the form, so show the defaults
1659 return $this->getDefault();
1662 # This is the impossible case: if we look at $_GET and see no data for our
1663 # field, is it because the user has not yet submitted the form, or that they
1664 # have submitted it with all the options unchecked? We will have to assume the
1665 # latter, which basically means that you can't specify 'positive' defaults
1668 return $request->getArray( $this->mName
, array() );
1672 function getDefault() {
1673 if ( isset( $this->mDefault
) ) {
1674 return $this->mDefault
;
1680 protected function needsLabel() {
1686 * Double field with a dropdown list constructed from a system message in the format
1689 * * New Optgroup header
1690 * Plus a text field underneath for an additional reason. The 'value' of the field is
1691 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1693 * @todo FIXME: If made 'required', only the text field should be compulsory.
1695 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1697 function __construct( $params ) {
1698 if ( array_key_exists( 'other', $params ) ) {
1699 } elseif( array_key_exists( 'other-message', $params ) ){
1700 $params['other'] = wfMessage( $params['other-message'] )->plain();
1702 $params['other'] = null;
1705 if ( array_key_exists( 'options', $params ) ) {
1706 # Options array already specified
1707 } elseif( array_key_exists( 'options-message', $params ) ){
1708 # Generate options array from a system message
1709 $params['options'] = self
::parseMessage(
1710 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1715 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1717 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1719 parent
::__construct( $params );
1723 * Build a drop-down box from a textual list.
1724 * @param $string String message text
1725 * @param $otherName String name of "other reason" option
1727 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1729 public static function parseMessage( $string, $otherName=null ) {
1730 if( $otherName === null ){
1731 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1735 $options = array( $otherName => 'other' );
1737 foreach ( explode( "\n", $string ) as $option ) {
1738 $value = trim( $option );
1739 if ( $value == '' ) {
1741 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1742 # A new group is starting...
1743 $value = trim( substr( $value, 1 ) );
1745 } elseif ( substr( $value, 0, 2) == '**' ) {
1747 $opt = trim( substr( $value, 2 ) );
1748 if( $optgroup === false ){
1749 $options[$opt] = $opt;
1751 $options[$optgroup][$opt] = $opt;
1754 # groupless reason list
1756 $options[$option] = $option;
1763 function getInputHTML( $value ) {
1764 $select = parent
::getInputHTML( $value[1] );
1766 $textAttribs = array(
1767 'id' => $this->mID
. '-other',
1768 'size' => $this->getSize(),
1771 if ( $this->mClass
!== '' ) {
1772 $textAttribs['class'] = $this->mClass
;
1775 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1776 if ( isset( $this->mParams
[$param] ) ) {
1777 $textAttribs[$param] = '';
1781 $textbox = Html
::input(
1782 $this->mName
. '-other',
1788 return "$select<br />\n$textbox";
1792 * @param $request WebRequest
1793 * @return Array( <overall message>, <select value>, <text field value> )
1795 function loadDataFromRequest( $request ) {
1796 if ( $request->getCheck( $this->mName
) ) {
1798 $list = $request->getText( $this->mName
);
1799 $text = $request->getText( $this->mName
. '-other' );
1801 if ( $list == 'other' ) {
1803 } elseif( !in_array( $list, $this->mFlatOptions
) ){
1804 # User has spoofed the select form to give an option which wasn't
1805 # in the original offer. Sulk...
1807 } elseif( $text == '' ) {
1810 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1814 $final = $this->getDefault();
1818 foreach ( $this->mFlatOptions
as $option ) {
1819 $match = $option . wfMsgForContent( 'colon-separator' );
1820 if( strpos( $text, $match ) === 0 ) {
1822 $text = substr( $text, strlen( $match ) );
1827 return array( $final, $list, $text );
1830 function getSize() {
1831 return isset( $this->mParams
['size'] )
1832 ?
$this->mParams
['size']
1836 function validate( $value, $alldata ) {
1837 # HTMLSelectField forces $value to be one of the options in the select
1838 # field, which is not useful here. But we do want the validation further up
1840 $p = parent
::validate( $value[1], $alldata );
1842 if ( $p !== true ) {
1846 if( isset( $this->mParams
['required'] ) && $value[1] === '' ){
1847 return wfMsgExt( 'htmlform-required', 'parseinline' );
1855 * Radio checkbox fields.
1857 class HTMLRadioField
extends HTMLFormField
{
1860 function validate( $value, $alldata ) {
1861 $p = parent
::validate( $value, $alldata );
1863 if ( $p !== true ) {
1867 if ( !is_string( $value ) && !is_int( $value ) ) {
1871 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1873 if ( in_array( $value, $validOptions ) ) {
1876 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1881 * This returns a block of all the radio options, in one cell.
1882 * @see includes/HTMLFormField#getInputHTML()
1883 * @param $value String
1886 function getInputHTML( $value ) {
1887 $html = $this->formatOptions( $this->mParams
['options'], $value );
1892 function formatOptions( $options, $value ) {
1896 if ( !empty( $this->mParams
['disabled'] ) ) {
1897 $attribs['disabled'] = 'disabled';
1900 # TODO: should this produce an unordered list perhaps?
1901 foreach ( $options as $label => $info ) {
1902 if ( is_array( $info ) ) {
1903 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1904 $html .= $this->formatOptions( $info, $value );
1906 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1907 $radio = Xml
::radio(
1911 $attribs +
array( 'id' => $id )
1913 $radio .= ' ' .
1914 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1916 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
1923 protected function needsLabel() {
1929 * An information field (text blob), not a proper input.
1931 class HTMLInfoField
extends HTMLFormField
{
1932 function __construct( $info ) {
1933 $info['nodata'] = true;
1935 parent
::__construct( $info );
1938 function getInputHTML( $value ) {
1939 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1942 function getTableRow( $value ) {
1943 if ( !empty( $this->mParams
['rawrow'] ) ) {
1947 return parent
::getTableRow( $value );
1950 protected function needsLabel() {
1955 class HTMLHiddenField
extends HTMLFormField
{
1956 public function __construct( $params ) {
1957 parent
::__construct( $params );
1959 # Per HTML5 spec, hidden fields cannot be 'required'
1960 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1961 unset( $this->mParams
['required'] );
1964 public function getTableRow( $value ) {
1967 $params['id'] = $this->mID
;
1970 $this->mParent
->addHiddenField(
1979 public function getInputHTML( $value ) { return ''; }
1983 * Add a submit button inline in the form (as opposed to
1984 * HTMLForm::addButton(), which will add it at the end).
1986 class HTMLSubmitField
extends HTMLFormField
{
1988 function __construct( $info ) {
1989 $info['nodata'] = true;
1990 parent
::__construct( $info );
1993 function getInputHTML( $value ) {
1994 return Xml
::submitButton(
1997 'class' => 'mw-htmlform-submit ' . $this->mClass
,
1998 'name' => $this->mName
,
2004 protected function needsLabel() {
2009 * Button cannot be invalid
2010 * @param $value String
2011 * @param $alldata Array
2014 public function validate( $value, $alldata ){
2019 class HTMLEditTools
extends HTMLFormField
{
2020 public function getInputHTML( $value ) {
2024 public function getTableRow( $value ) {
2025 if ( empty( $this->mParams
['message'] ) ) {
2026 $msg = wfMessage( 'edittools' );
2028 $msg = wfMessage( $this->mParams
['message'] );
2029 if ( $msg->isDisabled() ) {
2030 $msg = wfMessage( 'edittools' );
2033 $msg->inContentLanguage();
2036 return '<tr><td></td><td class="mw-input">'
2037 . '<div class="mw-editTools">'
2038 . $msg->parseAsBlock()
2039 . "</div></td></tr>\n";