Jump to content

HTMLForm

From mediawiki.org
This page is a translated version of the page HTMLForm and the translation is 24% complete.

HtmlForm - класс для обработки всего, что связано с формами пользовательского интерфейса. MediaWiki 1.16 и новее включают HtmlForm в HTMLForm.php.

Руководство по HtmlForm содержит основные сведения о HtmlForm.

Параметры

Точная спецификация для:

Параметр Тип Описание
type string Тип содержимого формы для создания. Например: text, radio, или multiselect. Они отображаются в конкретных подклассах в HtmlForm.

Это примерно переводится в атрибут типа ‎<select>. If 'class' is not specified, this is used as a map through HTMLForm::$typeMappings to get the class name.

class string PHP Subclass to use for this form content. This accomplishes the same thing as the type parameter, but more directly. This is NOT the CSS class!
size integer Устанавливает длину текстовых полей
maxlength integer Устанавливает максимальную длину текстовых полей
min integer Минимальная сумма для значения
max integer Максимальная сумма для значения
invert boolean Set inputs of type toggle to checked by default
options array The options to present in a multiselect, radio, or select form element. Maps raw text labels to values. Some field types support multi-level arrays. Overwrites 'options-message'.
rows array The rows to present in a checkmatrix form element or the number of rows shown for textarea form element
columns array The columns to present in a checkmatrix form element
force-options-off array Options to set unchecked and disabled in a checkmatrix form element
force-options-on array Options to set checked and enabled in a checkmatrix form element
section string Key for an i18n message to display as a section or subsection header. Subsections should make use of '/' character e.g. foo/bar/baz creates a preference 'baz' inside the section 'bar' which is inside the section 'foo'
label-message,

buttonlabel-message

string Key for an i18n message to display as a label for a form input/button. Message key or object for a message to use as the label. Can be an array of msg key and then parameters to the message.
label,

label-raw, buttonlabel

string Label for a form input/button. Overridden by label-message.
vertical-label boolean Set to true if you want the label to appear above the options rather than to the left of the options
id string ID attribute to assign to the input
cssclass string Class attribute to assign to the input
csshelpclass string CSS class used to style help text
validation-callback array Class and function to use for input validation. See HTMLFormField::validate()
filter-callback array Class and function to use for input filtering. It gives you the chance to massage the inputted value before it's processed. See HTMLFormField::filter()
help-message string Key for an i18n message to display directly below the form element. Overwrites 'help-messages' and 'help'. Can be an array of msg key and then parameters to the message.
help string Message to display directly below the form element to use as a help text.
tooltip string Key suffix for i18n messages to use for title and/or accesskey attributes (tooltip-YOURVALUE and accesskey-YOURVALUE)
placeholder string Value to use for the HTML5 placeholder attribute
placeholder-message string Key for an i18n message to display as a placeholder
disabled boolean Disable editing and submission of the form input
readonly boolean Disable editing of the form input
required boolean If true, the input cannot be left blank. It is passed through to the object, indicating that it is a required field.
name string Override the name of the input (default is wp{$fieldname}).

If you want a different name (eg one without the "wp" prefix), specify it here and it will be used without modification.

dir string Direction of the element.
'options-messages' array associative array mapping message keys to values. Some field types support multi-level arrays.

Overwrites 'options' and 'options-message'.

'options-message' array message key or object to be parsed to extract the list of options (like 'ipbreason-dropdown').
'help-messages' array array of message keys/objects. As above, each item can be an array of msg key and then parameters. Overwrites 'help'.
'help-inline' array Whether help text (defined using options above) will be shown inline after the input field, rather than in a popup.

Defaults to true. Only used by OOUI form fields.

'hide-if' array expression given as an array stating when the field should be hidden. The first array value has to be the expression's logic operator.

Suppo

[ 'NOT', array $expression ] To hide a field if a given expression is not true.

'==='

[ '===', string $fieldName, string $value ]

To hide a field if another field identified by $field has the value $value.

'!==' [ '!==', string $fieldName, string $value ]

Same as [ 'NOT', [ '===', $fieldName, $value ]

'OR', 'AND', 'NOR', 'NAND'

[ 'XXX', array $expression1, ..., array $expressionN ]

To hide a field if one or more (OR), all (AND), neither (NOR) or not all (NAND) given expressions are evaluated as true.


The expressions will be given to a JavaScript frontend module which will continually update the field's visibility.

nodata boolean if set (to any value, which casts to true), the data for this field will not be loaded from the actual request. Instead, always the default data is set as the value of this field.
default string (or array) Default value(s) for the field (not to be confused with $wgDefaultUserOptions ). Note extensions/skins adding preferences via hook must make use of UserGetDefaultOptions to set default value.

Пример использования

class SpecialTestForm

<?php

class SpecialTestForm extends SpecialPage {
	public function __construct() {
		parent::__construct( 'TestForm' );
	}

	public function execute( $par ) {
		$this->getOutput()->setPageTitle( 'Test form' );

		$formDescriptor = [
			'myfield1' => [
				'section' => 'section1/subsection',
				'label-message' => 'testform-myfield1',
				'type' => 'text',
				'default' => 'Meep',
			],
			'myfield2' => [
				'section' => 'section1',
				'class' => 'HTMLTextField', // HTMLTextField same as type 'text'
				'label-message' => 'testform-myfield2',
			],
			'myfield3' => [
				'class' => 'HTMLTextField',
				'label' => 'Foo bar baz',
			],
			'myfield4' => [
				'class' => 'HTMLCheckField',
				'label' => 'This be a pirate checkbox',
				'default' => true,
			],
			'omgaselectbox' => [
				'class' => 'HTMLSelectField',
				'label' => 'Select an oooption',
				'options' => [
					'Pirates' => 'pirate',
					'Ninjas' => 'ninja',
					'Back to the NINJAR!' => 'ninjars',
				],
			],
			'omgmultiselect' => [
				'class' => 'HTMLMultiSelectField',
				'label' => 'Weapons to use',
				'options' => [
					'Cannons' => 'cannon',
					'Swords' => 'sword',
				],
				'default' => [ 'sword' ],
			],
			'radiolol' => [
				'class' => 'HTMLRadioField',
				'label' => 'Who do you like?',
				'options' => [
					'Pirates' => 'pirates',
					'Ninjas' => 'ninjas',
					'Both' => 'both',
				],
				'default' => 'pirates',
			],
		];

		$htmlForm = new HTMLForm( $formDescriptor, $this->getContext() );
		$htmlForm
			->setSubmitText( 'Foo submit' )
			->setSubmitCallback( [ $this, 'trySubmit' ] )
			->show();
	}

	public function trySubmit( $formData ) {
		if ( $formData[ 'myfield1' ] === 'Fleep' ) {
			return true;
		}

		return 'Fail';
	}
}

$wgSpecialPages['TestForm'] = 'SpecialTestForm';

i18n/en.json

{
	"@metadata": {
		"authors": [
			"MW_Kappa"
		]
	},
	"testform-desc": "some informative text for page Special:Version",
	"section1": "display text for section1",
	"subsection": "display text for subsection"
}

Отображаемые форматы

The default display format for HTMLForm is a table layout, with labels in the left column and inputs in the right column. It is possible to select a few different formats e.g. $htmlForm->setDisplayFormat( 'div' ); will use a div-based layout, the others more rare ones are raw and inline.

Версия MediaWiki:
1.26

To change the form to use the OOUI toolkit for HTMLform elements, starting with MediaWiki 1.26, you'll need to use 'ooui' as display format in HTMLForm::factory:

$htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );

Historical notes

HTMLForm was introduced by Werdna in r48740 as a part of his preferences system rewrite. Historically MediaWikis from version 1.4.0 to version 1.11.0 included a different HTMLForm class, written by Hashar and JeLuF. This HTMLForm was removed in r29245.