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',
75 'namespaces' => 'HTMLNamespacesField',
76 'restrictionlevels' => 'HTMLRestrictionLevelsField',
78 # HTMLTextField will output the correct type="" attribute automagically.
79 # There are about four zillion other HTML5 input types, like url, but
80 # we don't use those at the moment, so no point in adding all of them.
81 'email' => 'HTMLTextField',
82 'password' => 'HTMLTextField',
85 protected $mMessagePrefix;
87 /** @var HTMLFormField[] */
88 protected $mFlatFields;
90 protected $mFieldTree;
91 protected $mShowReset = false;
94 protected $mSubmitCallback;
95 protected $mValidationErrorMessage;
98 protected $mHeader = '';
99 protected $mFooter = '';
100 protected $mSectionHeaders = array();
101 protected $mSectionFooters = array();
102 protected $mPost = '';
105 protected $mSubmitID;
106 protected $mSubmitName;
107 protected $mSubmitText;
108 protected $mSubmitTooltip;
111 protected $mMethod = 'post';
113 protected $mUseMultipart = false;
114 protected $mHiddenFields = array();
115 protected $mButtons = array();
117 protected $mWrapperLegend = false;
120 * If true, sections that contain both fields and subsections will
121 * render their subsections before their fields.
123 * Subclasses may set this to false to render subsections after fields
126 protected $mSubSectionBeforeFields = true;
129 * Build a new HTMLForm from an array of field attributes
130 * @param $descriptor Array of Field constructs, as described above
131 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
132 * Obviates the need to call $form->setTitle()
133 * @param $messagePrefix String a prefix to go in front of default messages
135 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
136 if( $context instanceof IContextSource
){
137 $this->setContext( $context );
138 $this->mTitle
= false; // We don't need them to set a title
139 $this->mMessagePrefix
= $messagePrefix;
142 if( is_string( $context ) && $messagePrefix === '' ){
143 // it's actually $messagePrefix
144 $this->mMessagePrefix
= $context;
148 // Expand out into a tree.
149 $loadedDescriptor = array();
150 $this->mFlatFields
= array();
152 foreach ( $descriptor as $fieldname => $info ) {
153 $section = isset( $info['section'] )
157 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
158 $this->mUseMultipart
= true;
161 $field = self
::loadInputFromParameters( $fieldname, $info );
162 $field->mParent
= $this;
164 $setSection =& $loadedDescriptor;
166 $sectionParts = explode( '/', $section );
168 while ( count( $sectionParts ) ) {
169 $newName = array_shift( $sectionParts );
171 if ( !isset( $setSection[$newName] ) ) {
172 $setSection[$newName] = array();
175 $setSection =& $setSection[$newName];
179 $setSection[$fieldname] = $field;
180 $this->mFlatFields
[$fieldname] = $field;
183 $this->mFieldTree
= $loadedDescriptor;
187 * Add the HTMLForm-specific JavaScript, if it hasn't been
189 * @deprecated since 1.18 load modules with ResourceLoader instead
191 static function addJS() { }
194 * Initialise a new Object for the field
195 * @param $fieldname string
196 * @param $descriptor string input Descriptor, as described above
197 * @return HTMLFormField subclass
199 static function loadInputFromParameters( $fieldname, $descriptor ) {
200 if ( isset( $descriptor['class'] ) ) {
201 $class = $descriptor['class'];
202 } elseif ( isset( $descriptor['type'] ) ) {
203 $class = self
::$typeMappings[$descriptor['type']];
204 $descriptor['class'] = $class;
210 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
213 $descriptor['fieldname'] = $fieldname;
215 $obj = new $class( $descriptor );
221 * Prepare form for submission
223 function prepareForm() {
224 # Check if we have the info we need
225 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
226 throw new MWException( "You must call setTitle() on an HTMLForm" );
229 # Load data from the request.
234 * Try submitting, with edit token check first
235 * @return Status|boolean
237 function tryAuthorizedSubmit() {
238 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
241 if ( $this->getMethod() != 'post' ||
$this->getUser()->matchEditToken( $editToken ) ) {
242 $result = $this->trySubmit();
248 * The here's-one-I-made-earlier option: do the submission if
249 * posted, or display the form with or without funky valiation
251 * @return Bool or Status whether submission was successful.
254 $this->prepareForm();
256 $result = $this->tryAuthorizedSubmit();
257 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
261 $this->displayForm( $result );
266 * Validate all the fields, and call the submision callback
267 * function if everything is kosher.
268 * @return Mixed Bool true == Successful submission, Bool false
269 * == No submission attempted, anything else == Error to
272 function trySubmit() {
273 # Check for validation
274 foreach ( $this->mFlatFields
as $fieldname => $field ) {
275 if ( !empty( $field->mParams
['nodata'] ) ) {
278 if ( $field->validate(
279 $this->mFieldData
[$fieldname],
283 return isset( $this->mValidationErrorMessage
)
284 ?
$this->mValidationErrorMessage
285 : array( 'htmlform-invalid-input' );
289 $callback = $this->mSubmitCallback
;
291 $data = $this->filterDataForSubmit( $this->mFieldData
);
293 $res = call_user_func( $callback, $data, $this );
299 * Set a callback to a function to do something with the form
300 * once it's been successfully validated.
301 * @param $cb String function name. The function will be passed
302 * the output from HTMLForm::filterDataForSubmit, and must
303 * return Bool true on success, Bool false if no submission
304 * was attempted, or String HTML output to display on error.
306 function setSubmitCallback( $cb ) {
307 $this->mSubmitCallback
= $cb;
311 * Set a message to display on a validation error.
312 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
313 * (so each entry can be either a String or Array)
315 function setValidationErrorMessage( $msg ) {
316 $this->mValidationErrorMessage
= $msg;
320 * Set the introductory message, overwriting any existing message.
321 * @param $msg String complete text of message to display
323 function setIntro( $msg ) {
324 $this->setPreText( $msg );
328 * Set the introductory message, overwriting any existing message.
330 * @param $msg String complete text of message to display
332 function setPreText( $msg ) { $this->mPre
= $msg; }
335 * Add introductory text.
336 * @param $msg String complete text of message to display
338 function addPreText( $msg ) { $this->mPre
.= $msg; }
341 * Add header text, inside the form.
342 * @param $msg String complete text of message to display
343 * @param $section The section to add the header to
345 function addHeaderText( $msg, $section = null ) {
346 if ( is_null( $section ) ) {
347 $this->mHeader
.= $msg;
349 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
350 $this->mSectionHeaders
[$section] = '';
352 $this->mSectionHeaders
[$section] .= $msg;
357 * Set header text, inside the form.
359 * @param $msg String complete text of message to display
360 * @param $section The section to add the header to
362 function setHeaderText( $msg, $section = null ) {
363 if ( is_null( $section ) ) {
364 $this->mHeader
= $msg;
366 $this->mSectionHeaders
[$section] = $msg;
371 * Add footer text, inside the form.
372 * @param $msg String complete text of message to display
373 * @param $section string The section to add the footer text to
375 function addFooterText( $msg, $section = null ) {
376 if ( is_null( $section ) ) {
377 $this->mFooter
.= $msg;
379 if ( !isset( $this->mSectionFooters
[$section] ) ) {
380 $this->mSectionFooters
[$section] = '';
382 $this->mSectionFooters
[$section] .= $msg;
387 * Set footer text, inside the form.
389 * @param $msg String complete text of message to display
390 * @param $section string The section to add the footer text to
392 function setFooterText( $msg, $section = null ) {
393 if ( is_null( $section ) ) {
394 $this->mFooter
= $msg;
396 $this->mSectionFooters
[$section] = $msg;
401 * Add text to the end of the display.
402 * @param $msg String complete text of message to display
404 function addPostText( $msg ) { $this->mPost
.= $msg; }
407 * Set text at the end of the display.
408 * @param $msg String complete text of message to display
410 function setPostText( $msg ) { $this->mPost
= $msg; }
413 * Add a hidden field to the output
414 * @param $name String field name. This will be used exactly as entered
415 * @param $value String field value
416 * @param $attribs Array
418 public function addHiddenField( $name, $value, $attribs = array() ) {
419 $attribs +
= array( 'name' => $name );
420 $this->mHiddenFields
[] = array( $value, $attribs );
423 public function addButton( $name, $value, $id = null, $attribs = null ) {
424 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
428 * Display the form (sending to wgOut), with an appropriate error
429 * message or stack of messages, and any validation errors, etc.
430 * @param $submitResult Mixed output from HTMLForm::trySubmit()
432 function displayForm( $submitResult ) {
433 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
437 * Returns the raw HTML generated by the form
438 * @param $submitResult Mixed output from HTMLForm::trySubmit()
441 function getHTML( $submitResult ) {
442 # For good measure (it is the default)
443 $this->getOutput()->preventClickjacking();
444 $this->getOutput()->addModules( 'mediawiki.htmlform' );
447 . $this->getErrors( $submitResult )
450 . $this->getHiddenFields()
451 . $this->getButtons()
455 $html = $this->wrapForm( $html );
457 return '' . $this->mPre
. $html . $this->mPost
;
461 * Wrap the form innards in an actual <form> element
462 * @param $html String HTML contents to wrap.
463 * @return String wrapped HTML.
465 function wrapForm( $html ) {
467 # Include a <fieldset> wrapper for style, if requested.
468 if ( $this->mWrapperLegend
!== false ) {
469 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
471 # Use multipart/form-data
472 $encType = $this->mUseMultipart
473 ?
'multipart/form-data'
474 : 'application/x-www-form-urlencoded';
477 'action' => $this->getTitle()->getFullURL(),
478 'method' => $this->mMethod
,
479 'class' => 'visualClear',
480 'enctype' => $encType,
482 if ( !empty( $this->mId
) ) {
483 $attribs['id'] = $this->mId
;
486 return Html
::rawElement( 'form', $attribs, $html );
490 * Get the hidden fields that should go inside the form.
491 * @return String HTML.
493 function getHiddenFields() {
494 global $wgUsePathInfo;
497 if( $this->getMethod() == 'post' ){
498 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
499 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
502 if ( !$wgUsePathInfo && $this->getMethod() == 'get' ) {
503 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
506 foreach ( $this->mHiddenFields
as $data ) {
507 list( $value, $attribs ) = $data;
508 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
515 * Get the submit and (potentially) reset buttons.
516 * @return String HTML.
518 function getButtons() {
522 if ( isset( $this->mSubmitID
) ) {
523 $attribs['id'] = $this->mSubmitID
;
526 if ( isset( $this->mSubmitName
) ) {
527 $attribs['name'] = $this->mSubmitName
;
530 if ( isset( $this->mSubmitTooltip
) ) {
531 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
534 $attribs['class'] = 'mw-htmlform-submit';
536 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
538 if ( $this->mShowReset
) {
539 $html .= Html
::element(
543 'value' => wfMsg( 'htmlform-reset' )
548 foreach ( $this->mButtons
as $button ) {
551 'name' => $button['name'],
552 'value' => $button['value']
555 if ( $button['attribs'] ) {
556 $attrs +
= $button['attribs'];
559 if ( isset( $button['id'] ) ) {
560 $attrs['id'] = $button['id'];
563 $html .= Html
::element( 'input', $attrs );
570 * Get the whole body of the form.
574 return $this->displaySection( $this->mFieldTree
);
578 * Format and display an error message stack.
579 * @param $errors String|Array|Status
582 function getErrors( $errors ) {
583 if ( $errors instanceof Status
) {
584 if ( $errors->isOK() ) {
587 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
589 } elseif ( is_array( $errors ) ) {
590 $errorstr = $this->formatErrors( $errors );
596 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
601 * Format a stack of error messages into a single HTML string
602 * @param $errors Array of message keys/values
603 * @return String HTML, a <ul> list of errors
605 public static function formatErrors( $errors ) {
608 foreach ( $errors as $error ) {
609 if ( is_array( $error ) ) {
610 $msg = array_shift( $error );
616 $errorstr .= Html
::rawElement(
619 wfMsgExt( $msg, array( 'parseinline' ), $error )
623 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
629 * Set the text for the submit button
630 * @param $t String plaintext.
632 function setSubmitText( $t ) {
633 $this->mSubmitText
= $t;
637 * Set the text for the submit button to a message
639 * @param $msg String message key
641 public function setSubmitTextMsg( $msg ) {
642 return $this->setSubmitText( $this->msg( $msg )->escaped() );
646 * Get the text for the submit button, either customised or a default.
647 * @return unknown_type
649 function getSubmitText() {
650 return $this->mSubmitText
652 : wfMsg( 'htmlform-submit' );
655 public function setSubmitName( $name ) {
656 $this->mSubmitName
= $name;
659 public function setSubmitTooltip( $name ) {
660 $this->mSubmitTooltip
= $name;
664 * Set the id for the submit button.
666 * @todo FIXME: Integrity of $t is *not* validated
668 function setSubmitID( $t ) {
669 $this->mSubmitID
= $t;
672 public function setId( $id ) {
676 * Prompt the whole form to be wrapped in a <fieldset>, with
677 * this text as its <legend> element.
678 * @param $legend String HTML to go inside the <legend> element.
681 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
684 * Prompt the whole form to be wrapped in a <fieldset>, with
685 * this message as its <legend> element.
687 * @param $msg String message key
689 public function setWrapperLegendMsg( $msg ) {
690 return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
694 * Set the prefix for various default messages
695 * TODO: currently only used for the <fieldset> legend on forms
696 * with multiple sections; should be used elsewhre?
699 function setMessagePrefix( $p ) {
700 $this->mMessagePrefix
= $p;
704 * Set the title for form submission
705 * @param $t Title of page the form is on/should be posted to
707 function setTitle( $t ) {
715 function getTitle() {
716 return $this->mTitle
=== false
717 ?
$this->getContext()->getTitle()
722 * Set the method used to submit the form
723 * @param $method String
725 public function setMethod( $method='post' ){
726 $this->mMethod
= $method;
729 public function getMethod(){
730 return $this->mMethod
;
735 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
736 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
737 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
740 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
742 $subsectionHtml = '';
743 $hasLeftColumn = false;
745 foreach ( $fields as $key => $value ) {
746 if ( is_object( $value ) ) {
747 $v = empty( $value->mParams
['nodata'] )
748 ?
$this->mFieldData
[$key]
749 : $value->getDefault();
750 $tableHtml .= $value->getTableRow( $v );
752 if ( $value->getLabel() != ' ' ) {
753 $hasLeftColumn = true;
755 } elseif ( is_array( $value ) ) {
756 $section = $this->displaySection( $value, $key );
757 $legend = $this->getLegend( $key );
758 if ( isset( $this->mSectionHeaders
[$key] ) ) {
759 $section = $this->mSectionHeaders
[$key] . $section;
761 if ( isset( $this->mSectionFooters
[$key] ) ) {
762 $section .= $this->mSectionFooters
[$key];
764 $attributes = array();
765 if ( $fieldsetIDPrefix ) {
766 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
768 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
774 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
775 $classes[] = 'mw-htmlform-nolabel';
779 'class' => implode( ' ', $classes ),
782 if ( $sectionName ) {
783 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
786 $tableHtml = Html
::rawElement( 'table', $attribs,
787 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
789 if ( $this->mSubSectionBeforeFields
) {
790 return $subsectionHtml . "\n" . $tableHtml;
792 return $tableHtml . "\n" . $subsectionHtml;
797 * Construct the form fields from the Descriptor array
799 function loadData() {
800 $fieldData = array();
802 foreach ( $this->mFlatFields
as $fieldname => $field ) {
803 if ( !empty( $field->mParams
['nodata'] ) ) {
805 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
806 $fieldData[$fieldname] = $field->getDefault();
808 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
813 foreach ( $fieldData as $name => &$value ) {
814 $field = $this->mFlatFields
[$name];
815 $value = $field->filter( $value, $this->mFlatFields
);
818 $this->mFieldData
= $fieldData;
822 * Stop a reset button being shown for this form
823 * @param $suppressReset Bool set to false to re-enable the
826 function suppressReset( $suppressReset = true ) {
827 $this->mShowReset
= !$suppressReset;
831 * Overload this if you want to apply special filtration routines
832 * to the form as a whole, after it's submitted but before it's
835 * @return unknown_type
837 function filterDataForSubmit( $data ) {
842 * Get a string to go in the <legend> of a section fieldset. Override this if you
843 * want something more complicated
847 public function getLegend( $key ) {
848 return wfMsg( "{$this->mMessagePrefix}-$key" );
852 * Returns an array of fields in the form
854 * @return HTMLFormField[]
856 public function getFlatFields() {
857 return $this->mFlatFields
;
861 * Returns a value of a field
863 * @param $field string Field name
866 public function getVal( $field ) {
867 return $this->mFieldData
[$field];
872 * The parent class to generate form fields. Any field type should
873 * be a subclass of this.
875 abstract class HTMLFormField
{
877 protected $mValidationCallback;
878 protected $mFilterCallback;
881 protected $mLabel; # String label. Set on construction
883 protected $mClass = '';
892 * This function must be implemented to return the HTML to generate
893 * the input object itself. It should not implement the surrounding
894 * table cells/rows, or labels/help messages.
895 * @param $value String the value to set the input to; eg a default
896 * text for a text input.
897 * @return String valid HTML.
899 abstract function getInputHTML( $value );
902 * Override this function to add specific validation checks on the
903 * field input. Don't forget to call parent::validate() to ensure
904 * that the user-defined callback mValidationCallback is still run
905 * @param $value String the value the field was submitted with
906 * @param $alldata Array the data collected from the form
907 * @return Mixed Bool true on success, or String error to display.
909 function validate( $value, $alldata ) {
910 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
911 return wfMsgExt( 'htmlform-required', 'parseinline' );
914 if ( isset( $this->mValidationCallback
) ) {
915 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
921 function filter( $value, $alldata ) {
922 if ( isset( $this->mFilterCallback
) ) {
923 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
930 * Should this field have a label, or is there no input element with the
931 * appropriate id for the label to point to?
933 * @return bool True to output a label, false to suppress
935 protected function needsLabel() {
940 * Get the value that this input has been set to from a posted form,
941 * or the input's default value if it has not been set.
942 * @param $request WebRequest
943 * @return String the value
945 function loadDataFromRequest( $request ) {
946 if ( $request->getCheck( $this->mName
) ) {
947 return $request->getText( $this->mName
);
949 return $this->getDefault();
954 * Initialise the object
955 * @param $params array Associative Array. See HTMLForm doc for syntax.
957 function __construct( $params ) {
958 $this->mParams
= $params;
960 # Generate the label from a message, if possible
961 if ( isset( $params['label-message'] ) ) {
962 $msgInfo = $params['label-message'];
964 if ( is_array( $msgInfo ) ) {
965 $msg = array_shift( $msgInfo );
971 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
972 } elseif ( isset( $params['label'] ) ) {
973 $this->mLabel
= $params['label'];
976 $this->mName
= "wp{$params['fieldname']}";
977 if ( isset( $params['name'] ) ) {
978 $this->mName
= $params['name'];
981 $validName = Sanitizer
::escapeId( $this->mName
);
982 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
983 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
986 $this->mID
= "mw-input-{$this->mName}";
988 if ( isset( $params['default'] ) ) {
989 $this->mDefault
= $params['default'];
992 if ( isset( $params['id'] ) ) {
994 $validId = Sanitizer
::escapeId( $id );
996 if ( $id != $validId ) {
997 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1003 if ( isset( $params['cssclass'] ) ) {
1004 $this->mClass
= $params['cssclass'];
1007 if ( isset( $params['validation-callback'] ) ) {
1008 $this->mValidationCallback
= $params['validation-callback'];
1011 if ( isset( $params['filter-callback'] ) ) {
1012 $this->mFilterCallback
= $params['filter-callback'];
1017 * Get the complete table row for the input, including help text,
1018 * labels, and whatever.
1019 * @param $value String the value to set the input to.
1020 * @return String complete HTML table row.
1022 function getTableRow( $value ) {
1023 # Check for invalid data.
1025 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1027 $cellAttributes = array();
1028 $verticalLabel = false;
1030 if ( !empty($this->mParams
['vertical-label']) ) {
1031 $cellAttributes['colspan'] = 2;
1032 $verticalLabel = true;
1035 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1039 $errors = self
::formatErrors( $errors );
1040 $errorClass = 'mw-htmlform-invalid-input';
1043 $label = $this->getLabelHtml( $cellAttributes );
1044 $field = Html
::rawElement(
1046 array( 'class' => 'mw-input' ) +
$cellAttributes,
1047 $this->getInputHTML( $value ) . "\n$errors"
1050 $fieldType = get_class( $this );
1052 if ( $verticalLabel ) {
1053 $html = Html
::rawElement( 'tr',
1054 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1055 $html .= Html
::rawElement( 'tr',
1056 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1059 $html = Html
::rawElement( 'tr',
1060 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1066 if ( isset( $this->mParams
['help-message'] ) ) {
1067 $msg = wfMessage( $this->mParams
['help-message'] );
1068 if ( $msg->exists() ) {
1069 $helptext = $msg->parse();
1071 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
1072 # help-message can be passed a message key (string) or an array containing
1073 # a message key and additional parameters. This makes it impossible to pass
1074 # an array of message key
1075 foreach( $this->mParams
['help-messages'] as $name ) {
1076 $msg = wfMessage( $name );
1077 if( $msg->exists() ) {
1078 $helptext .= $msg->parse(); // append message
1081 } elseif ( isset( $this->mParams
['help'] ) ) {
1082 $helptext = $this->mParams
['help'];
1085 if ( !is_null( $helptext ) ) {
1086 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1088 $row = Html
::rawElement( 'tr', array(), $row );
1096 * Returns the HTML name of the Field
1100 public function getName() {
1101 return $this->mName
;
1104 function getLabel() {
1105 return $this->mLabel
;
1107 function getLabelHtml( $cellAttributes = array() ) {
1108 # Don't output a for= attribute for labels with no associated input.
1109 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1112 if ( $this->needsLabel() ) {
1113 $for['for'] = $this->mID
;
1116 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1117 Html
::rawElement( 'label', $for, $this->getLabel() )
1121 function getDefault() {
1122 if ( isset( $this->mDefault
) ) {
1123 return $this->mDefault
;
1130 * Returns the attributes required for the tooltip and accesskey.
1132 * @return array Attributes
1134 public function getTooltipAndAccessKey() {
1135 if ( empty( $this->mParams
['tooltip'] ) ) {
1138 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1142 * flatten an array of options to a single array, for instance,
1143 * a set of <options> inside <optgroups>.
1144 * @param $options Associative Array with values either Strings
1146 * @return Array flattened input
1148 public static function flattenOptions( $options ) {
1149 $flatOpts = array();
1151 foreach ( $options as $value ) {
1152 if ( is_array( $value ) ) {
1153 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1155 $flatOpts[] = $value;
1163 * Formats one or more errors as accepted by field validation-callback.
1164 * @param $errors String|Message|Array of strings or Message instances
1165 * @return String html
1168 protected static function formatErrors( $errors ) {
1169 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1170 $errors = array_shift( $errors );
1173 if ( is_array( $errors ) ) {
1175 foreach ( $errors as $error ) {
1176 if ( $error instanceof Message
) {
1177 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1179 $lines[] = Html
::rawElement( 'li', array(), $error );
1182 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1184 if ( $errors instanceof Message
) {
1185 $errors = $errors->parse();
1187 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1192 class HTMLTextField
extends HTMLFormField
{
1193 function getSize() {
1194 return isset( $this->mParams
['size'] )
1195 ?
$this->mParams
['size']
1199 function getInputHTML( $value ) {
1202 'name' => $this->mName
,
1203 'size' => $this->getSize(),
1205 ) +
$this->getTooltipAndAccessKey();
1207 if ( isset( $this->mParams
['maxlength'] ) ) {
1208 $attribs['maxlength'] = $this->mParams
['maxlength'];
1211 if ( !empty( $this->mParams
['disabled'] ) ) {
1212 $attribs['disabled'] = 'disabled';
1215 # TODO: Enforce pattern, step, required, readonly on the server side as
1217 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1218 'placeholder' ) as $param ) {
1219 if ( isset( $this->mParams
[$param] ) ) {
1220 $attribs[$param] = $this->mParams
[$param];
1224 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1225 if ( isset( $this->mParams
[$param] ) ) {
1226 $attribs[$param] = '';
1230 # Implement tiny differences between some field variants
1231 # here, rather than creating a new class for each one which
1232 # is essentially just a clone of this one.
1233 if ( isset( $this->mParams
['type'] ) ) {
1234 switch ( $this->mParams
['type'] ) {
1236 $attribs['type'] = 'email';
1239 $attribs['type'] = 'number';
1242 $attribs['type'] = 'number';
1243 $attribs['step'] = 'any';
1248 $attribs['type'] = $this->mParams
['type'];
1253 return Html
::element( 'input', $attribs );
1256 class HTMLTextAreaField
extends HTMLFormField
{
1257 function getCols() {
1258 return isset( $this->mParams
['cols'] )
1259 ?
$this->mParams
['cols']
1263 function getRows() {
1264 return isset( $this->mParams
['rows'] )
1265 ?
$this->mParams
['rows']
1269 function getInputHTML( $value ) {
1272 'name' => $this->mName
,
1273 'cols' => $this->getCols(),
1274 'rows' => $this->getRows(),
1275 ) +
$this->getTooltipAndAccessKey();
1278 if ( !empty( $this->mParams
['disabled'] ) ) {
1279 $attribs['disabled'] = 'disabled';
1282 if ( !empty( $this->mParams
['readonly'] ) ) {
1283 $attribs['readonly'] = 'readonly';
1286 foreach ( array( 'required', 'autofocus' ) as $param ) {
1287 if ( isset( $this->mParams
[$param] ) ) {
1288 $attribs[$param] = '';
1292 return Html
::element( 'textarea', $attribs, $value );
1297 * A field that will contain a numeric value
1299 class HTMLFloatField
extends HTMLTextField
{
1300 function getSize() {
1301 return isset( $this->mParams
['size'] )
1302 ?
$this->mParams
['size']
1306 function validate( $value, $alldata ) {
1307 $p = parent
::validate( $value, $alldata );
1309 if ( $p !== true ) {
1313 $value = trim( $value );
1315 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1316 # with the addition that a leading '+' sign is ok.
1317 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1318 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1321 # The "int" part of these message names is rather confusing.
1322 # They make equal sense for all numbers.
1323 if ( isset( $this->mParams
['min'] ) ) {
1324 $min = $this->mParams
['min'];
1326 if ( $min > $value ) {
1327 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1331 if ( isset( $this->mParams
['max'] ) ) {
1332 $max = $this->mParams
['max'];
1334 if ( $max < $value ) {
1335 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1344 * A field that must contain a number
1346 class HTMLIntField
extends HTMLFloatField
{
1347 function validate( $value, $alldata ) {
1348 $p = parent
::validate( $value, $alldata );
1350 if ( $p !== true ) {
1354 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1355 # with the addition that a leading '+' sign is ok. Note that leading zeros
1356 # are fine, and will be left in the input, which is useful for things like
1357 # phone numbers when you know that they are integers (the HTML5 type=tel
1358 # input does not require its value to be numeric). If you want a tidier
1359 # value to, eg, save in the DB, clean it up with intval().
1360 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1362 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1372 class HTMLCheckField
extends HTMLFormField
{
1373 function getInputHTML( $value ) {
1374 if ( !empty( $this->mParams
['invert'] ) ) {
1378 $attr = $this->getTooltipAndAccessKey();
1379 $attr['id'] = $this->mID
;
1381 if ( !empty( $this->mParams
['disabled'] ) ) {
1382 $attr['disabled'] = 'disabled';
1385 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1386 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1390 * For a checkbox, the label goes on the right hand side, and is
1391 * added in getInputHTML(), rather than HTMLFormField::getRow()
1394 function getLabel() {
1399 * @param $request WebRequest
1402 function loadDataFromRequest( $request ) {
1404 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1408 // GetCheck won't work like we want for checks.
1409 // Fetch the value in either one of the two following case:
1410 // - we have a valid token (form got posted or GET forged by the user)
1411 // - checkbox name has a value (false or true), ie is not null
1412 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
)!== null ) {
1413 // XOR has the following truth table, which is what we want
1414 // INVERT VALUE | OUTPUT
1415 // true true | false
1416 // false true | true
1417 // false false | false
1418 // true false | true
1419 return $request->getBool( $this->mName
) xor $invert;
1421 return $this->getDefault();
1427 * A select dropdown field. Basically a wrapper for Xmlselect class
1429 class HTMLSelectField
extends HTMLFormField
{
1430 function validate( $value, $alldata ) {
1431 $p = parent
::validate( $value, $alldata );
1433 if ( $p !== true ) {
1437 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1439 if ( in_array( $value, $validOptions ) )
1442 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1445 function getInputHTML( $value ) {
1446 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1448 # If one of the options' 'name' is int(0), it is automatically selected.
1449 # because PHP sucks and thinks int(0) == 'some string'.
1450 # Working around this by forcing all of them to strings.
1451 foreach( $this->mParams
['options'] as &$opt ){
1452 if( is_int( $opt ) ){
1453 $opt = strval( $opt );
1456 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1458 if ( !empty( $this->mParams
['disabled'] ) ) {
1459 $select->setAttribute( 'disabled', 'disabled' );
1462 $select->addOptions( $this->mParams
['options'] );
1464 return $select->getHTML();
1469 * Select dropdown field, with an additional "other" textbox.
1471 class HTMLSelectOrOtherField
extends HTMLTextField
{
1472 static $jsAdded = false;
1474 function __construct( $params ) {
1475 if ( !in_array( 'other', $params['options'], true ) ) {
1476 $msg = isset( $params['other'] ) ?
$params['other'] : wfMsg( 'htmlform-selectorother-other' );
1477 $params['options'][$msg] = 'other';
1480 parent
::__construct( $params );
1483 static function forceToStringRecursive( $array ) {
1484 if ( is_array( $array ) ) {
1485 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1487 return strval( $array );
1491 function getInputHTML( $value ) {
1492 $valInSelect = false;
1494 if ( $value !== false ) {
1495 $valInSelect = in_array(
1497 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1501 $selected = $valInSelect ?
$value : 'other';
1503 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1505 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1506 $select->addOptions( $opts );
1508 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1510 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1512 if ( !empty( $this->mParams
['disabled'] ) ) {
1513 $select->setAttribute( 'disabled', 'disabled' );
1514 $tbAttribs['disabled'] = 'disabled';
1517 $select = $select->getHTML();
1519 if ( isset( $this->mParams
['maxlength'] ) ) {
1520 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1523 $textbox = Html
::input(
1524 $this->mName
. '-other',
1525 $valInSelect ?
'' : $value,
1530 return "$select<br />\n$textbox";
1534 * @param $request WebRequest
1537 function loadDataFromRequest( $request ) {
1538 if ( $request->getCheck( $this->mName
) ) {
1539 $val = $request->getText( $this->mName
);
1541 if ( $val == 'other' ) {
1542 $val = $request->getText( $this->mName
. '-other' );
1547 return $this->getDefault();
1553 * Multi-select field
1555 class HTMLMultiSelectField
extends HTMLFormField
{
1557 public function __construct( $params ){
1558 parent
::__construct( $params );
1559 if( isset( $params['flatlist'] ) ){
1560 $this->mClass
.= ' mw-htmlform-multiselect-flatlist';
1564 function validate( $value, $alldata ) {
1565 $p = parent
::validate( $value, $alldata );
1567 if ( $p !== true ) {
1571 if ( !is_array( $value ) ) {
1575 # If all options are valid, array_intersect of the valid options
1576 # and the provided options will return the provided options.
1577 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1579 $validValues = array_intersect( $value, $validOptions );
1580 if ( count( $validValues ) == count( $value ) ) {
1583 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1587 function getInputHTML( $value ) {
1588 $html = $this->formatOptions( $this->mParams
['options'], $value );
1593 function formatOptions( $options, $value ) {
1598 if ( !empty( $this->mParams
['disabled'] ) ) {
1599 $attribs['disabled'] = 'disabled';
1602 foreach ( $options as $label => $info ) {
1603 if ( is_array( $info ) ) {
1604 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1605 $html .= $this->formatOptions( $info, $value );
1607 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1609 $checkbox = Xml
::check(
1610 $this->mName
. '[]',
1611 in_array( $info, $value, true ),
1612 $attribs +
$thisAttribs );
1613 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1615 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1623 * @param $request WebRequest
1626 function loadDataFromRequest( $request ) {
1627 if ( $this->mParent
->getMethod() == 'post' ) {
1628 if( $request->wasPosted() ){
1629 # Checkboxes are just not added to the request arrays if they're not checked,
1630 # so it's perfectly possible for there not to be an entry at all
1631 return $request->getArray( $this->mName
, array() );
1633 # That's ok, the user has not yet submitted the form, so show the defaults
1634 return $this->getDefault();
1637 # This is the impossible case: if we look at $_GET and see no data for our
1638 # field, is it because the user has not yet submitted the form, or that they
1639 # have submitted it with all the options unchecked? We will have to assume the
1640 # latter, which basically means that you can't specify 'positive' defaults
1643 return $request->getArray( $this->mName
, array() );
1647 function getDefault() {
1648 if ( isset( $this->mDefault
) ) {
1649 return $this->mDefault
;
1655 protected function needsLabel() {
1661 * Double field with a dropdown list constructed from a system message in the format
1664 * * New Optgroup header
1665 * Plus a text field underneath for an additional reason. The 'value' of the field is
1666 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1668 * @todo FIXME: If made 'required', only the text field should be compulsory.
1670 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1672 function __construct( $params ) {
1673 if ( array_key_exists( 'other', $params ) ) {
1674 } elseif( array_key_exists( 'other-message', $params ) ){
1675 $params['other'] = wfMessage( $params['other-message'] )->plain();
1677 $params['other'] = null;
1680 if ( array_key_exists( 'options', $params ) ) {
1681 # Options array already specified
1682 } elseif( array_key_exists( 'options-message', $params ) ){
1683 # Generate options array from a system message
1684 $params['options'] = self
::parseMessage(
1685 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1690 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1692 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1694 parent
::__construct( $params );
1698 * Build a drop-down box from a textual list.
1699 * @param $string String message text
1700 * @param $otherName String name of "other reason" option
1702 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1704 public static function parseMessage( $string, $otherName=null ) {
1705 if( $otherName === null ){
1706 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1710 $options = array( $otherName => 'other' );
1712 foreach ( explode( "\n", $string ) as $option ) {
1713 $value = trim( $option );
1714 if ( $value == '' ) {
1716 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1717 # A new group is starting...
1718 $value = trim( substr( $value, 1 ) );
1720 } elseif ( substr( $value, 0, 2) == '**' ) {
1722 $opt = trim( substr( $value, 2 ) );
1723 if( $optgroup === false ){
1724 $options[$opt] = $opt;
1726 $options[$optgroup][$opt] = $opt;
1729 # groupless reason list
1731 $options[$option] = $option;
1738 function getInputHTML( $value ) {
1739 $select = parent
::getInputHTML( $value[1] );
1741 $textAttribs = array(
1742 'id' => $this->mID
. '-other',
1743 'size' => $this->getSize(),
1746 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1747 if ( isset( $this->mParams
[$param] ) ) {
1748 $textAttribs[$param] = '';
1752 $textbox = Html
::input(
1753 $this->mName
. '-other',
1759 return "$select<br />\n$textbox";
1763 * @param $request WebRequest
1764 * @return Array( <overall message>, <select value>, <text field value> )
1766 function loadDataFromRequest( $request ) {
1767 if ( $request->getCheck( $this->mName
) ) {
1769 $list = $request->getText( $this->mName
);
1770 $text = $request->getText( $this->mName
. '-other' );
1772 if ( $list == 'other' ) {
1774 } elseif( !in_array( $list, $this->mFlatOptions
) ){
1775 # User has spoofed the select form to give an option which wasn't
1776 # in the original offer. Sulk...
1778 } elseif( $text == '' ) {
1781 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1785 $final = $this->getDefault();
1789 foreach ( $this->mFlatOptions
as $option ) {
1790 $match = $option . wfMsgForContent( 'colon-separator' );
1791 if( strpos( $text, $match ) === 0 ) {
1793 $text = substr( $text, strlen( $match ) );
1798 return array( $final, $list, $text );
1801 function getSize() {
1802 return isset( $this->mParams
['size'] )
1803 ?
$this->mParams
['size']
1807 function validate( $value, $alldata ) {
1808 # HTMLSelectField forces $value to be one of the options in the select
1809 # field, which is not useful here. But we do want the validation further up
1811 $p = parent
::validate( $value[1], $alldata );
1813 if ( $p !== true ) {
1817 if( isset( $this->mParams
['required'] ) && $value[1] === '' ){
1818 return wfMsgExt( 'htmlform-required', 'parseinline' );
1826 * Radio checkbox fields.
1828 class HTMLRadioField
extends HTMLFormField
{
1829 function __construct( $params ) {
1830 parent
::__construct( $params );
1831 if ( isset( $params['flatlist'] ) ) {
1832 $this->mClass
.= ' mw-htmlform-radio-flatlist';
1837 function validate( $value, $alldata ) {
1838 $p = parent
::validate( $value, $alldata );
1840 if ( $p !== true ) {
1844 if ( !is_string( $value ) && !is_int( $value ) ) {
1848 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1850 if ( in_array( $value, $validOptions ) ) {
1853 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1858 * This returns a block of all the radio options, in one cell.
1859 * @see includes/HTMLFormField#getInputHTML()
1860 * @param $value String
1863 function getInputHTML( $value ) {
1864 $html = $this->formatOptions( $this->mParams
['options'], $value );
1869 function formatOptions( $options, $value ) {
1873 if ( !empty( $this->mParams
['disabled'] ) ) {
1874 $attribs['disabled'] = 'disabled';
1877 # TODO: should this produce an unordered list perhaps?
1878 foreach ( $options as $label => $info ) {
1879 if ( is_array( $info ) ) {
1880 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1881 $html .= $this->formatOptions( $info, $value );
1883 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1884 $radio = Xml
::radio(
1888 $attribs +
array( 'id' => $id )
1890 $radio .= ' ' .
1891 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1893 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-radio-item' ), $radio );
1900 protected function needsLabel() {
1906 * An information field (text blob), not a proper input.
1908 class HTMLInfoField
extends HTMLFormField
{
1909 function __construct( $info ) {
1910 $info['nodata'] = true;
1912 parent
::__construct( $info );
1915 function getInputHTML( $value ) {
1916 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1919 function getTableRow( $value ) {
1920 if ( !empty( $this->mParams
['rawrow'] ) ) {
1924 return parent
::getTableRow( $value );
1927 protected function needsLabel() {
1932 class HTMLHiddenField
extends HTMLFormField
{
1933 public function __construct( $params ) {
1934 parent
::__construct( $params );
1936 # Per HTML5 spec, hidden fields cannot be 'required'
1937 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1938 unset( $this->mParams
['required'] );
1941 public function getTableRow( $value ) {
1944 $params['id'] = $this->mID
;
1947 $this->mParent
->addHiddenField(
1956 public function getInputHTML( $value ) { return ''; }
1960 * Add a submit button inline in the form (as opposed to
1961 * HTMLForm::addButton(), which will add it at the end).
1963 class HTMLSubmitField
extends HTMLFormField
{
1965 function __construct( $info ) {
1966 $info['nodata'] = true;
1967 parent
::__construct( $info );
1970 function getInputHTML( $value ) {
1971 return Xml
::submitButton(
1974 'class' => 'mw-htmlform-submit',
1975 'name' => $this->mName
,
1981 protected function needsLabel() {
1986 * Button cannot be invalid
1987 * @param $value String
1988 * @param $alldata Array
1991 public function validate( $value, $alldata ){
1996 class HTMLEditTools
extends HTMLFormField
{
1997 public function getInputHTML( $value ) {
2001 public function getTableRow( $value ) {
2002 if ( empty( $this->mParams
['message'] ) ) {
2003 $msg = wfMessage( 'edittools' );
2005 $msg = wfMessage( $this->mParams
['message'] );
2006 if ( $msg->isDisabled() ) {
2007 $msg = wfMessage( 'edittools' );
2010 $msg->inContentLanguage();
2013 return '<tr><td></td><td class="mw-input">'
2014 . '<div class="mw-editTools">'
2015 . $msg->parseAsBlock()
2016 . "</div></td></tr>\n";
2021 * Dropdown for namespaces
2023 class HTMLNamespacesField
extends HTMLSelectField
{
2024 function __construct( $params ) {
2026 parent
::__construct( $params );
2028 $namespaces = $wgContLang->getFormattedNamespaces();
2031 $options[ wfMessage( 'namespacesall' )->escaped() ] = ''; // TODO: Make an option
2033 foreach ( $namespaces as $index => $name ) {
2034 // Don't include things like SpecialPages
2035 if ( $index < NS_MAIN
) {
2039 if ( $index === 0 ) {
2040 $name = wfMessage( 'blanknamespace' )->escaped();
2043 $options[$name] = $index;
2046 $this->mParams
['options'] = $options;
2051 * Dropdown for protection levels
2053 class HTMLRestrictionLevelsField
extends HTMLSelectField
{
2056 * Should this field be displayed? If it hits a condition where it should
2057 * be hidden, set this to false.
2061 protected $enabled = true;
2063 function __construct( $params ) {
2064 global $wgRestrictionLevels;
2065 parent
::__construct( $params );
2067 $options = array( wfMsg('restriction-level-all') => 0 ); // Temporary array
2069 // First pass to load the level names
2070 foreach( $wgRestrictionLevels as $type ) {
2071 if ( $type != '' && $type != '*' ) {
2072 $text = wfMsg("restriction-level-$type");
2073 $options[$text] = $type;
2077 // Is there only one level (aside from "all")?
2078 if( count($options) <= 2 ) {
2079 $this->enabled
= false;
2083 $this->mParams
['options'] = $options;
2087 * Returns false where
2092 function getTableRow( $value ) {
2093 if ( $this->enabled
) {
2094 return parent
::getTableRow( $value );