4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
7 abstract class HTMLFormField
{
10 protected $mValidationCallback;
11 protected $mFilterCallback;
13 protected $mLabel; # String label. Set on construction
15 protected $mClass = '';
17 protected $mOptions = false;
18 protected $mOptionsLabelsNotFromMessage = false;
21 * @var bool If true will generate an empty div element with no label
24 protected $mShowEmptyLabels = true;
32 * This function must be implemented to return the HTML to generate
33 * the input object itself. It should not implement the surrounding
34 * table cells/rows, or labels/help messages.
36 * @param string $value the value to set the input to; eg a default
37 * text for a text input.
39 * @return string Valid HTML.
41 abstract function getInputHTML( $value );
44 * Get a translated interface message
46 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
47 * and wfMessage() otherwise.
49 * Parameters are the same as wfMessage().
51 * @return Message object
54 $args = func_get_args();
56 if ( $this->mParent
) {
57 $callback = array( $this->mParent
, 'msg' );
59 $callback = 'wfMessage';
62 return call_user_func_array( $callback, $args );
66 * Override this function to add specific validation checks on the
67 * field input. Don't forget to call parent::validate() to ensure
68 * that the user-defined callback mValidationCallback is still run
70 * @param string $value The value the field was submitted with
71 * @param array $alldata The data collected from the form
73 * @return Mixed Bool true on success, or String error to display.
75 function validate( $value, $alldata ) {
76 if ( isset( $this->mParams
['required'] )
77 && $this->mParams
['required'] !== false
80 return $this->msg( 'htmlform-required' )->parse();
83 if ( isset( $this->mValidationCallback
) ) {
84 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
90 function filter( $value, $alldata ) {
91 if ( isset( $this->mFilterCallback
) ) {
92 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
99 * Should this field have a label, or is there no input element with the
100 * appropriate id for the label to point to?
102 * @return bool True to output a label, false to suppress
104 protected function needsLabel() {
109 * Tell the field whether to generate a separate label element if its label
114 * @param bool $show Set to false to not generate a label.
117 public function setShowEmptyLabel( $show ) {
118 $this->mShowEmptyLabels
= $show;
122 * Get the value that this input has been set to from a posted form,
123 * or the input's default value if it has not been set.
125 * @param WebRequest $request
126 * @return String the value
128 function loadDataFromRequest( $request ) {
129 if ( $request->getCheck( $this->mName
) ) {
130 return $request->getText( $this->mName
);
132 return $this->getDefault();
137 * Initialise the object
139 * @param array $params Associative Array. See HTMLForm doc for syntax.
141 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
142 * @throws MWException
144 function __construct( $params ) {
145 $this->mParams
= $params;
147 # Generate the label from a message, if possible
148 if ( isset( $params['label-message'] ) ) {
149 $msgInfo = $params['label-message'];
151 if ( is_array( $msgInfo ) ) {
152 $msg = array_shift( $msgInfo );
158 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
159 } elseif ( isset( $params['label'] ) ) {
160 if ( $params['label'] === ' ' ) {
161 // Apparently some things set   directly and in an odd format
162 $this->mLabel
= ' ';
164 $this->mLabel
= htmlspecialchars( $params['label'] );
166 } elseif ( isset( $params['label-raw'] ) ) {
167 $this->mLabel
= $params['label-raw'];
170 $this->mName
= "wp{$params['fieldname']}";
171 if ( isset( $params['name'] ) ) {
172 $this->mName
= $params['name'];
175 $validName = Sanitizer
::escapeId( $this->mName
);
176 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
177 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
180 $this->mID
= "mw-input-{$this->mName}";
182 if ( isset( $params['default'] ) ) {
183 $this->mDefault
= $params['default'];
186 if ( isset( $params['id'] ) ) {
188 $validId = Sanitizer
::escapeId( $id );
190 if ( $id != $validId ) {
191 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
197 if ( isset( $params['cssclass'] ) ) {
198 $this->mClass
= $params['cssclass'];
201 if ( isset( $params['validation-callback'] ) ) {
202 $this->mValidationCallback
= $params['validation-callback'];
205 if ( isset( $params['filter-callback'] ) ) {
206 $this->mFilterCallback
= $params['filter-callback'];
209 if ( isset( $params['flatlist'] ) ) {
210 $this->mClass
.= ' mw-htmlform-flatlist';
213 if ( isset( $params['hidelabel'] ) ) {
214 $this->mShowEmptyLabels
= false;
219 * Get the complete table row for the input, including help text,
220 * labels, and whatever.
222 * @param string $value The value to set the input to.
224 * @return string Complete HTML table row.
226 function getTableRow( $value ) {
227 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
228 $inputHtml = $this->getInputHTML( $value );
229 $fieldType = get_class( $this );
230 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
231 $cellAttributes = array();
233 if ( !empty( $this->mParams
['vertical-label'] ) ) {
234 $cellAttributes['colspan'] = 2;
235 $verticalLabel = true;
237 $verticalLabel = false;
240 $label = $this->getLabelHtml( $cellAttributes );
242 $field = Html
::rawElement(
244 array( 'class' => 'mw-input' ) +
$cellAttributes,
245 $inputHtml . "\n$errors"
248 if ( $verticalLabel ) {
249 $html = Html
::rawElement( 'tr', array( 'class' => 'mw-htmlform-vertical-label' ), $label );
250 $html .= Html
::rawElement( 'tr',
251 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
255 Html
::rawElement( 'tr',
256 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
260 return $html . $helptext;
264 * Get the complete div for the input, including help text,
265 * labels, and whatever.
268 * @param string $value The value to set the input to.
270 * @return string Complete HTML table row.
272 public function getDiv( $value ) {
273 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
274 $inputHtml = $this->getInputHTML( $value );
275 $fieldType = get_class( $this );
276 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
277 $cellAttributes = array();
278 $label = $this->getLabelHtml( $cellAttributes );
280 $outerDivClass = array(
282 'mw-htmlform-nolabel' => ( $label === '' )
285 $field = Html
::rawElement(
287 array( 'class' => $outerDivClass ) +
$cellAttributes,
288 $inputHtml . "\n$errors"
290 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
291 if ( $this->mParent
->isVForm() ) {
292 $divCssClasses[] = 'mw-ui-vform-div';
294 $html = Html
::rawElement( 'div', array( 'class' => $divCssClasses ), $label . $field );
301 * Get the complete raw fields for the input, including help text,
302 * labels, and whatever.
305 * @param string $value The value to set the input to.
307 * @return string Complete HTML table row.
309 public function getRaw( $value ) {
310 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
311 $inputHtml = $this->getInputHTML( $value );
312 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
313 $cellAttributes = array();
314 $label = $this->getLabelHtml( $cellAttributes );
325 * Generate help text HTML in table format
328 * @param string|null $helptext
331 public function getHelpTextHtmlTable( $helptext ) {
332 if ( is_null( $helptext ) ) {
336 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ), $helptext );
337 $row = Html
::rawElement( 'tr', array(), $row );
343 * Generate help text HTML in div format
346 * @param string|null $helptext
350 public function getHelpTextHtmlDiv( $helptext ) {
351 if ( is_null( $helptext ) ) {
355 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
361 * Generate help text HTML formatted for raw output
364 * @param string|null $helptext
367 public function getHelpTextHtmlRaw( $helptext ) {
368 return $this->getHelpTextHtmlDiv( $helptext );
372 * Determine the help text to display
376 public function getHelpText() {
379 if ( isset( $this->mParams
['help-message'] ) ) {
380 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
383 if ( isset( $this->mParams
['help-messages'] ) ) {
384 foreach ( $this->mParams
['help-messages'] as $name ) {
385 $helpMessage = (array)$name;
386 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
388 if ( $msg->exists() ) {
389 if ( is_null( $helptext ) ) {
392 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
394 $helptext .= $msg->parse(); // Append message
397 } elseif ( isset( $this->mParams
['help'] ) ) {
398 $helptext = $this->mParams
['help'];
405 * Determine form errors to display and their classes
408 * @param string $value The value of the input
411 public function getErrorsAndErrorClass( $value ) {
412 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
414 if ( $errors === true ||
415 ( !$this->mParent
->getRequest()->wasPosted() && $this->mParent
->getMethod() === 'post' )
420 $errors = self
::formatErrors( $errors );
421 $errorClass = 'mw-htmlform-invalid-input';
424 return array( $errors, $errorClass );
427 function getLabel() {
428 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
431 function getLabelHtml( $cellAttributes = array() ) {
432 # Don't output a for= attribute for labels with no associated input.
433 # Kind of hacky here, possibly we don't want these to be <label>s at all.
436 if ( $this->needsLabel() ) {
437 $for['for'] = $this->mID
;
440 $labelValue = trim( $this->getLabel() );
442 if ( $labelValue !== ' ' && $labelValue !== '' ) {
446 $displayFormat = $this->mParent
->getDisplayFormat();
449 if ( $displayFormat === 'table' ) {
451 Html
::rawElement( 'td',
452 array( 'class' => 'mw-label' ) +
$cellAttributes,
453 Html
::rawElement( 'label', $for, $labelValue ) );
454 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
455 if ( $displayFormat === 'div' ) {
457 Html
::rawElement( 'div',
458 array( 'class' => 'mw-label' ) +
$cellAttributes,
459 Html
::rawElement( 'label', $for, $labelValue ) );
461 $html = Html
::rawElement( 'label', $for, $labelValue );
468 function getDefault() {
469 if ( isset( $this->mDefault
) ) {
470 return $this->mDefault
;
477 * Returns the attributes required for the tooltip and accesskey.
479 * @return array Attributes
481 public function getTooltipAndAccessKey() {
482 if ( empty( $this->mParams
['tooltip'] ) ) {
486 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
490 * Returns the given attributes from the parameters
492 * @param array $list List of attributes to get
493 * @return array Attributes
495 public function getAttributes( array $list ) {
496 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
500 foreach ( $list as $key ) {
501 if ( in_array( $key, $boolAttribs ) ) {
502 if ( !empty( $this->mParams
[$key] ) ) {
505 } elseif ( isset( $this->mParams
[$key] ) ) {
506 $ret[$key] = $this->mParams
[$key];
514 * Given an array of msg-key => value mappings, returns an array with keys
515 * being the message texts. It also forces values to strings.
517 * @param array $options
520 private function lookupOptionsKeys( $options ) {
522 foreach ( $options as $key => $value ) {
523 $key = $this->msg( $key )->plain();
524 $ret[$key] = is_array( $value )
525 ?
$this->lookupOptionsKeys( $value )
532 * Recursively forces values in an array to strings, because issues arise
533 * with integer 0 as a value.
535 * @param array $array
538 static function forceToStringRecursive( $array ) {
539 if ( is_array( $array ) ) {
540 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
542 return strval( $array );
547 * Fetch the array of options from the field's parameters. In order, this
548 * checks 'options-messages', 'options', then 'options-message'.
550 * @return array|null Options array
552 public function getOptions() {
553 if ( $this->mOptions
=== false ) {
554 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
555 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
556 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
557 $this->mOptionsLabelsNotFromMessage
= true;
558 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
559 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
560 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
561 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
564 $this->mOptions
= array();
565 foreach ( explode( "\n", $message ) as $option ) {
566 $value = trim( $option );
567 if ( $value == '' ) {
569 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
570 # A new group is starting...
571 $value = trim( substr( $value, 1 ) );
573 } elseif ( substr( $value, 0, 2 ) == '**' ) {
575 $opt = trim( substr( $value, 2 ) );
576 if ( $optgroup === false ) {
577 $this->mOptions
[$opt] = $opt;
579 $this->mOptions
[$optgroup][$opt] = $opt;
582 # groupless reason list
584 $this->mOptions
[$option] = $option;
588 $this->mOptions
= null;
592 return $this->mOptions
;
596 * flatten an array of options to a single array, for instance,
597 * a set of "<options>" inside "<optgroups>".
599 * @param array $options Associative Array with values either Strings
601 * @return array Flattened input
603 public static function flattenOptions( $options ) {
606 foreach ( $options as $value ) {
607 if ( is_array( $value ) ) {
608 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
610 $flatOpts[] = $value;
618 * Formats one or more errors as accepted by field validation-callback.
620 * @param string|Message|array $errors String|Message|Array of strings or Message instances
621 * @return string HTML
624 protected static function formatErrors( $errors ) {
625 if ( is_array( $errors ) && count( $errors ) === 1 ) {
626 $errors = array_shift( $errors );
629 if ( is_array( $errors ) ) {
631 foreach ( $errors as $error ) {
632 if ( $error instanceof Message
) {
633 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
635 $lines[] = Html
::rawElement( 'li', array(), $error );
639 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
641 if ( $errors instanceof Message
) {
642 $errors = $errors->parse();
645 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );