Дата обновления перевода 2021-06-08
Поле EntityType¶
Специальное поле ChoiceType
, которое создано для загрузки опций из сущности
Doctrine. Например, еслиу вас есть сущность Category
, то вы могли бы использовать
это поле для отображения поля select
всех или некоторых объектов Category
из DB.
Отображается как | может быть разными тегами (см. Select Tag, Checkboxes or Radio Buttons) |
Опции | |
Переопределённые опции | |
Наследуемые опции | из ChoiceType:
из FormType: |
Родительский тип | ChoiceType |
Класс | EntityType |
Tip
The full list of options defined and inherited by this form type is available running this command in your app:
1 2 | # replace 'FooType' by the class name of your form type
$ php bin/console debug:form FooType
|
Базовое применение¶
Тип entity
имеет только одну обязательную опцию: сущность, которая должна быть указана
внутри поля выбора:
use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('users', EntityType::class, [
// ищет варианты из этой записи
'class' => User::class,
// использует свойство User.username в качестве видимой строки опции
'choice_label' => 'username',
// используется для отображение поля выбора,чекбокса или селективных кнопок
// 'multiple' => true,
// 'expanded' => true,
]);
Это построит выпадающее меню select
, содержащее все объекты User
в DB.
Чтобы вмето этого отобразить селективные кнопки или кнопки-флажки, измените опции
multiple и expanded.
Использование пользовательского запроса для сущностей¶
Если вы хотите создать пользовательский запрос для использования при вызове сущностей (например, вы хотите только вернуть некоторые сущности, или вам нужно упорядочить их), используйте опцию query_builder:
use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('users', EntityType::class, [
'class' => User::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
'choice_label' => 'username',
]);
Note
Использование коллекций форм может привести к созданию слишком большого количества запросов к базе данных для извлечения связанных сущностей. Это известно как “Проблема запросов N + 1” и может быть решено путем объединения связанных записей при запросах к ассоциациям Doctrine.
Использование выборов¶
Если у вас уже есть точная коллекция сущностей, которую вы хотите включить в
элемент выбора, просто передайте её через ключ choices
.
Например, если у вас есть переменная $group
(возможно переданная в вашу форму,
как опция формы) и getUsers()
возвращает коллекцию сущностей User
, то вы
можете предоставить опцию choices
напрямую:
use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('users', EntityType::class, [
'class' => User::class,
'choices' => $group->getUsers(),
]);
Select Tag, Checkboxes or Radio Buttons¶
This field may be rendered as one of several HTML fields, depending
on the expanded
and multiple
options:
Element Type | Expanded | Multiple |
---|---|---|
select tag | false |
false |
select tag (with multiple attribute) |
false |
true |
radio buttons | true |
false |
checkboxes | true |
true |
Опции поля¶
choice_label
¶
тип: string
, callable
или PropertyPath
Это свойство, которое должно быть использовано для отображеия сущностей, как текста в HTML-элементе:
use App\Entity\Category;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'displayName',
]);
Если оставить пустым, то объект сущности будет преобразован в строку и должен иметь метод
__toString()
. Вы также можете передать функцию обратного вызова для большего контроля:
use App\Entity\Category;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => function ($category) {
return $category->getDisplayName();
}
]);
Метод вызывается для каждой сущности в списке ипередаётся функции. Чтобы узнать больше, см. главную документацию choice_label.
Note
При передаче строки, опция choice_label
- это путь свойства. Так что
вы можете использовать что угодно, поддерживаемое
компонентом PropertyAccessor
Например, если свойство переводов на самом деле - ассоциативный массив объектов, каждый с именем свойства, то вы можете сделать это:
use App\Entity\Genre;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('genre', EntityType::class, [
'class' => Genre::class,
'choice_label' => 'translations[en].name',
]);
class
¶
тип: string
обязательно
Класс вашей сущности (например, App:Category
). Может быть
полным именем класса (например, App\Entity\Category
) или
коротким дополнительным именем (как было показано ранее).
em
¶
тип: string
| Doctrine\Common\Persistence\ObjectManager
по умолчанию: менеджер сушностей по умолчанию
Если указан, этот менеджер сущностей будет использован для загрузки выборов,
вместо менеджера сущностей default
.
query_builder
¶
тип: Doctrine\ORM\QueryBuilder
или callable
по умолчанию: null
Позволяет вам создавать пользовательский запрос для ваших выборов. См. Using a Custom Query for the Entities для примера.
Значение этой опции может быть либо объектом QueryBuilder
, либо вызываемым,
либо null
(что будет загружать все сущности). При использовании вызываемого,
вам будет передан EntityRepository
сущности, как единственный аргумент, и
он должен возвращать QueryBuilder
. Возвращение null
в Закрытии приведёт
к загрузке всех сущностей.
Caution
Сущность, используемая в спецификаторе FROM
опции query_builder всегда
будет валидировано с классом, который вы указали в оцпии формы class. Если
вы вернёте другую сущность вместо использованной в вашем спецификаторе FROM
(например, если вы вернёте сущность из объёдинённой таблицы), то это нарушит
валидацию.
Переопределённые опции¶
choice_name
¶
type: callable
, string
or PropertyPath
default: null
Controls the internal field name of the choice. You normally don’t care about this, but in some advanced cases, you might. For example, this “name” becomes the index of the choice views in the template and is used as part of the field name attribute.
This can be a callable or a property path. See choice_label for similar usage.
By default, the choice key or an incrementing integer may be used (starting at 0
).
Tip
When defining a custom type, you should use the
ChoiceList
class helper:
use Symfony\Component\Form\ChoiceList\ChoiceList;
// ...
$builder->add('choices', ChoiceType::class, [
'choice_name' => ChoiceList::fieldName($this, 'name'),
]);
See the “choice_loader” option documentation.
Caution
The configured value must be a valid form name. Make sure to only return valid names when using a callable. Valid form names must be composed of letters, digits, underscores, dashes and colons and must not start with a dash or a colon.
В EntityType
, это по умолчанию приравнивается к id
сущности, если
он может быть прочитан. Иначе, используется резервный план в виде авто-приращивания
чисел.
choice_value
¶
type: callable
, string
or PropertyPath
default: null
Returns the string “value” for each choice, which must be unique across all choices.
This is used in the value
attribute in HTML and submitted in the POST/PUT requests.
You don’t normally need to worry about this, but it might be handy when processing
an API request (since you can configure the value that will be sent in the API request).
This can be a callable or a property path. By default, the choices are used if they
can be casted to strings. Otherwise an incrementing integer is used (starting at 0
).
If you pass a callable, it will receive one argument: the choice itself. When using
the EntityType Field, the argument will be the entity object
for each choice or null
in a placeholder is used, which you need to handle:
'choice_value' => function (?MyOptionEntity $entity) {
return $entity ? $entity->getId() : '';
},
Tip
When defining a custom type, you should use the
ChoiceList
class helper:
use Symfony\Component\Form\ChoiceList\ChoiceList;
// ...
$builder->add('choices', ChoiceType::class, [
'choice_value' => ChoiceList::value($this, 'uuid'),
]);
See the “choice_loader” option documentation.
В EntityType
, это переопределяется, чтобы использовать id
по умолчанию.
Когда используется id
, Doctrine только запрашивает объекты на предмет id,
которые действительно были отправлены.
choices
¶
тип: array
| \Traversable
по умолчанию: null
Вместо позволения опциям class и query_builder вызывать сущности, чтобы
включть их для вас, вы можете передвать опцию choices
напрямую. См.
Using Choices.
data_class
¶
тип: string
по умолчанию: null
Эта опция не используется,в пользу опции class
, которая обязательна для
запросов сущностей.
Наследуемые опции¶
Эти опции наследуются из ChoiceType:
choice_attr
¶
type: array
, callable
, string
or PropertyPath
default: []
Use this to add additional HTML attributes to each choice. This can be an associative array where the keys match the choice keys and the values are the attributes for each choice, a callable or a property path (just like choice_label).
If an array, the keys of the choices
array must be used as keys:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...
$builder->add('fruits', ChoiceType::class, [
'choices' => [
'Apple' => 1,
'Banana' => 2,
'Durian' => 3,
],
'choice_attr' => [
'Apple' => ['data-color' => 'Red'],
'Banana' => ['data-color' => 'Yellow'],
'Durian' => ['data-color' => 'Green'],
],
]);
// or use a callable
$builder->add('attending', ChoiceType::class, [
'choices' => [
'Yes' => true,
'No' => false,
'Maybe' => null,
],
'choice_attr' => function($choice, $key, $value) {
// adds a class like attending_yes, attending_no, etc
return ['class' => 'attending_'.strtolower($key)];
},
]);
Tip
When defining a custom type, you should use the
ChoiceList
class helper:
use App\Entity\Category;
use Symfony\Component\Form\ChoiceList\ChoiceList;
// ...
$builder->add('choices', ChoiceType::class, [
'choice_attr' => ChoiceList::attr($this, function (?Category $category) {
return $category ? ['data-uuid' => $category->getUuid()] : [];
}),
]);
See the “choice_loader” option documentation.
choice_translation_domain
¶
DEFAULT_VALUE
This option determines if the choice values should be translated and in which translation domain.
The values of the choice_translation_domain
option can be true
(reuse the current
translation domain), false
(disable translation), null
(uses the parent translation
domain or the default domain) or a string which represents the exact translation
domain to use.
expanded
¶
type: boolean
default: false
If set to true, radio buttons or checkboxes will be rendered (depending
on the multiple
value). If false, a select element will be rendered.
group_by
¶
type: string
, callable
or PropertyPath
default: null
You can group the <option>
elements of a <select>
into <optgroup>
by passing a multi-dimensional array to choices
. See the
Grouping Options section about that.
The group_by
option is an alternative way to group choices, which gives you
a bit more flexibility.
Take the following example:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...
$builder->add('publishAt', ChoiceType::class, [
'choices' => [
'now' => new \DateTime('now'),
'tomorrow' => new \DateTime('+1 day'),
'1 week' => new \DateTime('+1 week'),
'1 month' => new \DateTime('+1 month'),
],
'group_by' => function($choice, $key, $value) {
if ($choice <= new \DateTime('+3 days')) {
return 'Soon';
}
return 'Later';
},
]);
This groups the dates that are within 3 days into “Soon” and everything else into
a “Later” <optgroup>
:

If you return null
, the option won’t be grouped. You can also pass a string
“property path” that will be called to get the group. See the choice_label for
details about using a property path.
Tip
When defining a custom type, you should use the
ChoiceList
class helper:
use Symfony\Component\Form\ChoiceList\ChoiceList;
// ...
$builder->add('choices', ChoiceType::class, [
'group_by' => ChoiceList::groupBy($this, 'category'),
]);
See the “choice_loader” option documentation.
multiple
¶
type: boolean
default: false
If true, the user will be able to select multiple options (as opposed
to choosing just one option). Depending on the value of the expanded
option, this will render either a select tag or checkboxes if true and
a select tag or radio buttons if false. The returned value will be an array.
Note
Если вы работаете с коллекцией сущностей Doctrine, то будет полезно также прочитать документацию CollectionType Field. Кроме того, в статье How to Embed a Collection of Forms есть полный пример.
placeholder
¶
type: string
or boolean
This option determines whether or not a special “empty” option (e.g. “Choose
an option”) will appear at the top of a select widget. This option only
applies if the multiple
option is set to false.
Add an empty value with “Choose an option” as the text:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... $builder->add('states', ChoiceType::class, [ 'placeholder' => 'Choose an option', ]);
Guarantee that no “empty” value option is displayed:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... $builder->add('states', ChoiceType::class, [ 'placeholder' => false, ]);
If you leave the placeholder
option unset, then a blank (with no text)
option will automatically be added if and only if the required
option
is false:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...
// a blank (with no text) option will be added
$builder->add('states', ChoiceType::class, [
'required' => false,
]);
preferred_choices
¶
тип: array
или callable
по умолчанию: []
Эта опция позволяет вам перемещать определенные выборы в начало вашего списка с визуальным разделителем между ними и другими опциями. Эта опция ожидает массив объектов сущностей:
use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('users', EntityType::class, [
'class' => User::class,
// этот метод должен возвращать массив сущностей Пользователя
'preferred_choices' => $group->getPreferredUsers(),
]);
Избранные выборы имеют значение только при отображении элемента select
(т.е. expanded
как false). Избранные и обычные выборы разделены визуально
набором дефисов (т.е. -------------------
). Это можно настроить при отображении
поля:
1 | {{ form_widget(form.publishAt, { 'separator': '=====' }) }}
|
translation_domain¶
type: string
default: messages
In case choice_translation_domain is set to true
or null
, this
configures the exact translation domain that will be used for any labels or
options that are rendered for this field.
trim
¶
type: boolean
default: false
Trimming is disabled by default because the selected value or values must match the given choice values exactly (and they could contain whitespaces).
Эти опции наследуют из типа form:
attr
¶
type: array
default: []
If you want to add extra attributes to an HTML field representation
you can use the attr
option. It’s an associative array with HTML attributes
as keys. This can be useful when you need to set a custom class for some widget:
$builder->add('body', TextareaType::class, [
'attr' => ['class' => 'tinymce'],
]);
See also
Use the row_attr
option if you want to add these attributes to
the form type row element.
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.
disabled
¶
type: boolean
default: false
If you don’t want a user to modify the value of a field, you can set the disabled option to true. Any submitted value will be ignored.
Настоящее значение по умолчанию этой опции зависит от других опций поля:
- Если
multiple
-false
, аexpanded
-false
, то -''
(пустая строка); - Иначе -
array()
(пустой массив).
error_bubbling
¶
type: boolean
default: false
unless the form is compound
If true
, any errors for this field will be passed to the parent field
or form. For example, if set to true
on a normal field, any errors for
that field will be attached to the main form, not to the specific field.
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',
],
]);
help¶
type: string
or TranslatableMessage
default: null
Allows you to define a help message for the form field, which by default is rendered below the field:
use Symfony\Component\Translation\TranslatableMessage;
$builder
->add('zipCode', null, [
'help' => 'The ZIP/Postal code for your credit card\'s billing address.',
])
// ...
->add('status', null, [
'help' => new TranslatableMessage('order.status', ['%order_id%' => $order->getId()], 'store'),
])
;
help_attr¶
type: array
default: []
Sets the HTML attributes for the element used to display the help message of the form field. Its value is an associative array with HTML attribute names as keys. These attributes can also be set in the template:
1 2 3 | {{ form_help(form.name, 'Your name', {
'help_attr': {'class': 'CUSTOM_LABEL_CLASS'}
}) }}
|
help_html¶
type: boolean
default: false
By default, the contents of the help
option are escaped before rendering
them in the template. Set this option to true
to not escape them, which is
useful when the help contains HTML elements.
label
¶
type: string
default: The label is “guessed” from the field name
Sets the label that will be used when rendering the field. Setting to false
will suppress the label. The label can also be set in the template:
- Twig
1
{{ form_label(form.name, 'Your name') }}
- PHP
1 2 3 4
echo $view['form']->label( $form['name'], 'Your name' );
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.
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
.
required
¶
type: boolean
default: true
If true, an HTML5 required attribute will be rendered. The corresponding
label
will also render with a required
class.
This is superficial and independent of validation. At best, if you let Symfony guess your field type, then the value of this option will be guessed from your validation information.
Note
The required option also affects how empty data for each field is handled. For more details, see the `empty_data`_ option.
row_attr¶
type: array
default: []
An associative array of the HTML attributes added to the element which is used to render the form type row:
$builder->add('body', TextareaType::class, [
'row_attr' => ['class' => 'text-editor', 'id' => '...'],
]);
See also
Use the attr
option if you want to add these attributes to
the form type widget element.
label_translation_parameters¶
type: array
default: []
The content of the label option is translated before displaying it, so it can contain translation placeholders. This option defines the values used to replace those placeholders.
Given this translation message:
1 2 | # translations/messages.en.yaml
form.order.id: 'Identifier of the order to %company%'
|
You can specify the placeholder values as follows:
$builder->add('id', null, [
'label' => 'form.order.id',
'label_translation_parameters' => [
'%company%' => 'ACME Inc.',
],
]);
The label_translation_parameters
option of children fields is merged with
the same option of their parents, so children can reuse and/or override any of
the parent placeholders.
attr_translation_parameters¶
type: array
default: []
The content of the title
and placeholder
values defined in the attr
option is translated before displaying it, so it can contain
translation placeholders. This
option defines the values used to replace those placeholders.
Given this translation message:
1 2 3 | # translations/messages.en.yaml
form.order.id.placeholder: 'Enter unique identifier of the order to %company%'
form.order.id.title: 'This will be the reference in communications with %company%'
|
You can specify the placeholder values as follows:
$builder->add('id', null, [
'attr' => [
'placeholder' => 'form.order.id.placeholder',
'title' => 'form.order.id.title',
],
'attr_translation_parameters' => [
'%company%' => 'ACME Inc.',
],
]);
The attr_translation_parameters
option of children fields is merged with the
same option of their parents, so children can reuse and/or override any of the
parent placeholders.
help_translation_parameters¶
type: array
default: []
The content of the help option is translated before displaying it, so it can contain translation placeholders. This option defines the values used to replace those placeholders.
Given this translation message:
1 2 | # translations/messages.en.yaml
form.order.id.help: 'This will be the reference in communications with %company%'
|
You can specify the placeholder values as follows:
$builder->add('id', null, [
'help' => 'form.order.id.help',
'help_translation_parameters' => [
'%company%' => 'ACME Inc.',
],
]);
The help_translation_parameters
option of children fields is merged with the
same option of their parents, so children can reuse and/or override any of the
parent placeholders.
Эта документация является переводом официальной документации Symfony и предоставляется по свободной лицензии CC BY-SA 3.0.