Поле SubmitType¶
Кнопка отправки.
Отображается как | тег button submit |
Наследуемые Опции | |
Родительский тип | ButtonType |
Класс | SubmitType |
Кнопка отправки имеет дополнительный метод
isClicked()
, который
позволяет вам проверять, была ли использована эта кнопка для отправки формы.
Это особенно полезно, когда форма имеет несколько кнопок отправки:
if ($form->get('save')->isClicked()) {
// ...
}
Наследуемые опции¶
attr¶
тип: array
по умолчанию: array()
Есди вы хотите добавить дополнительные атрибуты к HTML-представлению кнопки, то
вы можете использовать опцию attr
. Это ассоциативный массив с HTML-атрибутом
в качестве ключа. Это может быть полезно, когда вам нужно установить для кнопки
пользовательский класс:
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
// ...
$builder->add('save', SubmitType::class, array(
'attr' => array('class' => 'save'),
));
disabled
¶
type: boolean
default: false
If you don’t want a user to be able to click a button, you can set the disabled option to true. It will not be possible to submit the form with this button, not even when bypassing the browser and sending a request manually, for example with cURL.
label
¶
type: string
default: The label is “guessed” from the field name
Sets the label that will be displayed on the button. The label can also be directly set inside the template:
- Twig
1
{{ form_widget(form.save, { 'label': 'Click me' }) }}
- PHP
1
<?= $view['form']->widget($form['save'], ['label' => 'Click me']) ?>
label_attr
¶
type: array
default: []
Sets the HTML attributes for the <label>
element, which will be used
when rendering the label for the field. It’s an associative array with HTML
attribute as a key. This attributes can also be directly set inside the
template:
- Twig
1 2 3
{{ form_label(form.name, 'Your name', { 'label_attr': {'class': 'CUSTOM_LABEL_CLASS'} }) }}
- PHP
1 2 3 4 5
echo $view['form']->label( $form['name'], 'Your name', ['label_attr' => ['class' => 'CUSTOM_LABEL_CLASS']] );
label_format
¶
type: string
default: null
Configures the string used as the label of the field, in case the label
option was not set. This is useful when using
keyword translation messages.
If you’re using keyword translation messages as labels, you often end up having
multiple keyword messages for the same label (e.g. profile_address_street
,
invoice_address_street
). This is because the label is built for each “path”
to a field. To avoid duplicated keyword messages, you can configure the label
format to a static value, like:
// ...
$profileFormBuilder->add('address', AddressType::class, [
'label_format' => 'form.address.%name%',
]);
$invoiceFormBuilder->add('invoice', AddressType::class, [
'label_format' => 'form.address.%name%',
]);
This option is inherited by the child types. With the code above, the label of
the street
field of both forms will use the form.address.street
keyword
message.
Two variables are available in the label format:
%id%
- A unique identifier for the field, consisting of the complete path to the
field and the field name (e.g.
profile_address_street
); %name%
- The field name (e.g.
street
).
The default value (null
) results in a
“humanized” version of the field name.
Note
The label_format
option is evaluated in the form theme. Make sure to
update your templates in case you
customized form theming.
translation_domain
¶
type: string
default: messages
This is the translation domain that will be used for any labels or options that are rendered for this button.
validation_groups¶
тип: array
по умолчанию: null
Когда ваша форма содержит несколько кнопок отправки, вы можете менять группу валидации, взависимости от того, какая кнопка была использована для отправки. Представьте себе мастера формы регистрации с кнопками, чтобы переходить на следующий или предыдущий шаг:
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
// ...
$form = $this->createFormBuilder($user)
->add('previousStep', SubmitType::class, array(
'validation_groups' => false,
))
->add('nextStep', SubmitType::class, array(
'validation_groups' => array('Registration'),
))
->getForm();
Специальный false
гарантирует, что при нажатии кнопки предыдущего шага не
выполняется валидация. Когда нажимается вторая кнопка, валидируются все ограничения
из “Registration”.
See also
Вы можете прочитьать больше об этом в How to Choose Validation Groups Based on the Submitted Data.
Переменные формы¶
Переменная | Тип | Применение |
---|---|---|
clicked | boolean |
Была ли нажата кнопка. |
Эта документация является переводом официальной документации Symfony и предоставляется по свободной лицензии CC BY-SA 3.0.