Поле RepeatedType¶
Это специальная “группа” полей, которая создаёт два идентичных поля, значения которых должны совпадать (иначе выдаётся ошибка валидации). Наиболее часто используется, когда вам нужно, чтобы пользователь повторял свой пароль или электронный адрес для точности.
Отображается как | поле ввода text по умолчанию, но см. опцию type |
Опции | |
Переопределённые опуии | |
Наследуемые опции | |
Родительский тип | FormType |
Класс | RepeatedType |
Пример использования¶
1 2 3 4 5 6 7 8 9 10 11 12 | use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
// ...
$builder->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'Поля паролей должны совпадать.',
'options' => array('attr' => array('class' => 'password-field')),
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
));
|
При успешной отправке формы, значение, введенное в оба поля “пароль” становится
данными ключа password
. Другими словами, хотя отображаются два поля, конечные
данные формы - одно значение (обычно строка), которое вам нужно.
Наиболее важная опция - type
, которая можетбыть любым типом поля и определяет
настоящий тип двух основоположных полей. Опция options
передаётся каждому из
этих индивидуальных полей, что означает (в этом примере), что любая опция, поддерживаемая
PasswordType
может быть передана в этот массив.
Отображение¶
Повторямый тип поляна самом деле - два лежащих в основе поля, которые вы можете отображать одновременно или по очереди. Чтобы отобразить их одновременно, используйте что-то вроде:
- Twig
1
{{ form_row(form.password) }}
- PHP
1
<?php echo $view['form']->row($form['password']) ?>
Чтобы отобразить каждое поле индивидуально, используйте что-то вроде:
- Twig
1 2 3
{# .first и .second у вас могут отличаться - см. примечание ниже #} {{ form_row(form.password.first) }} {{ form_row(form.password.second) }}
- PHP
1 2
<?php echo $view['form']->row($form['password']['first']) ?> <?php echo $view['form']->row($form['password']['second']) ?>
Note
Имена first
и second
- это имена по умолчанию для двух подполей.
Однако, эти имена можно контролировать через опции first_name и second_name.
Если вы установили эти опции, то используйте эти значения вместо first
и
second
при отображении.
Валидация¶
Одной из основных функций поля repeated
является внутренняя валидация
(вам не нужно ничего делать, чтобы установить это), которая заставляет два
поля иметь совпадающее значение. Если два поля не совпадают, то пользователю
будет отображена ошибка.
invalid_message
используется для настройки ошибки, которая будет отображена,
когда два поля не будут совпадать.
Опции поля¶
first_name¶
тип: string
по умолчанию: first
Это настоящее имяполя, которое будет использовано для первого поля. В основном
это бесполезно, однако, данные, введенные в оба поля, будут доступны под ключом,
назначенным самому полю RepeatedType
(например, password
). Однако, если вы
не укажете ярлык, имя этого поля будет использовано для “определения” ярлыка для вас.
first_options¶
тип: array
по умолчанию: array()
Дополнительные опции (будут объединны в options ниже), которые должны быть переданы только первому полю. Это очень полезно для настройки ярлыка:
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
// ...
$builder->add('password', RepeatedType::class, array(
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
));
options¶
тип: array
по умолчанию: array()
Этот массив опцийбудет передан каждому из двух лежащих в основе полей.
Другимисловами, это те опции, которые настраивают индивидуальные типы полей.
Например, если опция type
установлена,как password
, то этот массив
может содержать опции always_empty
или required
- обе опции, которые
поддерживаются полем PasswordType
field.
second_options¶
тип: array
по умолчанию: array()
Дополнительные опции (будут объединны в options ниже), которые должны быть переданы только второму полю. Это очень полезно для настройки ярлыка (см. first_options).
type¶
тип: string
по умолчанию: Symfony\Component\Form\Extension\Core\Type\TextType
Два основоположных поля будут этим типом поля. Например, передача PasswordType::class
отобразит два поля пароля.
Наследуемые опции¶
Эти опции наследуются из FormType:
data
¶
type: mixed
default: Defaults to field of the underlying structure.
When you create a form, each field initially displays the value of the corresponding property of the form’s domain data (e.g. if you bind an object to the form). If you want to override this initial value for the form or an individual field, you can set it in the data option:
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
// ...
$builder->add('token', HiddenType::class, [
'data' => 'abcdef',
]);
Caution
The data
option always overrides the value taken from the domain data
(object) when rendering. This means the object value is also overridden when
the form edits an already persisted object, causing it to lose its
persisted value when the form is submitted.
error_mapping
¶
type: array
default: []
This option allows you to modify the target of a validation error.
Imagine you have a custom method named matchingCityAndZipCode()
that validates
whether the city and zip code match. Unfortunately, there is no matchingCityAndZipCode
field in your form, so all that Symfony can do is display the error on top
of the form.
With customized error mapping, you can do better: map the error to the city field so that it displays above it:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'error_mapping' => [
'matchingCityAndZipCode' => 'city',
],
]);
}
Here are the rules for the left and the right side of the mapping:
- The left side contains property paths;
- If the violation is generated on a property or method of a class, its
path is the
propertyName
; - If the violation is generated on an entry of an
array
orArrayAccess
object, the property path is[indexName]
; - You can construct nested property paths by concatenating them, separating
properties by dots. For example:
addresses[work].matchingCityAndZipCode
; - The right side contains the names of fields in the form.
By default, errors for any property that is not mapped will bubble up to the
parent form. You can use the dot (.
) on the left side to map errors of all
unmapped properties to a particular field. For instance, to map all these
errors to the city
field, use:
$resolver->setDefaults([
'error_mapping' => [
'.' => 'city',
],
]);
invalid_message
¶
type: string
default: This value is not valid
This is the validation error message that’s used if the data entered into this field doesn’t make sense (i.e. fails validation).
This might happen, for example, if the user enters a nonsense string into
a TimeType field that cannot be converted
into a real time or if the user enters a string (e.g. apple
) into a
number field.
Normal (business logic) validation (such as when setting a minimum length for a field) should be set using validation messages with your validation rules (reference).
invalid_message_parameters
¶
type: array
default: []
When setting the invalid_message
option, you may need to
include some variables in the string. This can be done by adding placeholders
to that option and including the variables in this option:
$builder->add('someField', SomeFormType::class, [
// ...
'invalid_message' => 'You entered an invalid value, it should include %num% letters',
'invalid_message_parameters' => ['%num%' => 6],
]);
mapped
¶
type: boolean
default: true
If you wish the field to be ignored when reading or writing to the object,
you can set the mapped
option to false
.
Эта документация является переводом официальной документации Symfony и предоставляется по свободной лицензии CC BY-SA 3.0.