Поле ChoiceType (выпадающие списки, селективные кнопки, кнопки-флажки)

Поле ChoiceType (выпадающие списки, селективные кнопки, кнопки-флажки)

Многоцелевое поле, используемое для позволения пользователю "выбирать" одну или больше опций. Может быть отображено как тег select, селективные кнопки или кнопки-флажки.

Чтобы использовать это поле, вы должны указать либо опцию choices, либо choice_loader.

Отображается как может быть разными тегами (см. ниже)
Опции
Переопределённые опции
Наследуемые опции
Родительский тип FormType
Класс ChoiceType

Пример применения

Простейший путь использования этого поля - указать варианты выбора напрямую через опцию choices:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('isAttending', ChoiceType::class, array(
    'choices'  => array(
        'Maybe' => null,
        'Yes' => true,
        'No' => false,
    ),
));

Это создаст выпадающий список select:

../../../_images/choice-example1.png

Если пользователь выбирает No, то форма вернёт false для этого поля. Таким же образом, если начальные данные для этого поля - true, то будет автоматически выбран Yes. Другими словами, значение каждого объекта - это значение, которое вы хотите получить / установить в PHP-коде, в то время, как ключ - это то, что будет показано пользователю.

Продвинутый пример (с Объектами!)

Это поле имеет много опций и большинство контролируют то, как отображается поле. В этом примере, основоположные данные - некоторый объект Category, имеющий метод getName():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use AppBundle\Entity\Category;
// ...

$builder->add('category', ChoiceType::class, [
    'choices' => [
        new Category('Cat1'),
        new Category('Cat2'),
        new Category('Cat3'),
        new Category('Cat4'),
    ],
    'choice_label' => function($category, $key, $index) {
        /** @var Category $category */
        return strtoupper($category->getName());
    },
    'choice_attr' => function($category, $key, $index) {
        return ['class' => 'category_'.strtolower($category->getName())];
    },
    'group_by' => function($category, $key, $index) {
        // рандомно разделить всё на 2 группы
        return rand(0, 1) == 1 ? 'Group A' : 'Group B';
    },
    'preferred_choices' => function($category, $key, $index) {
        return $category->getName() == 'Cat2' || $category->getName() == 'Cat3';
    },
]);

Вы также можете настроить choice_name и choice_value каждого варианта, если вам нужна дальнейшая HTML-настройка.

Select Tag, Checkboxes or Radio Buttons

This field may be rendered as one of several different 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

Настраивание текста каждой опции (ярлык)

Обычно, ключ массива каждого объекта в опции choices используется в качестве текста, отображаемого пользователю. Но это можно полностью настроить через опцию choice_label. Посмотрите её, чтобы узнать больше.

Группирование опций

Вы можете легко "группировать" опции, передавая массив многомерных вариантов:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('stockStatus', ChoiceType::class, array(
    'choices' => array(
        'Main Statuses' => array(
            'Yes' => 'stock_yes',
            'No' => 'stock_no',
        ),
        'Out of Stock Statuses' => array(
            'Backordered' => 'stock_backordered',
            'Discontinued' => 'stock_discontinued',
        ),
    ),
));
../../../_images/choice-example4.png

Чтобы сделать всё красивее, используйте опцию group_by.

Опции поля

choices

тип: array по умолчанию: array()

Это самый базовый способ указать варианты, которые должны быть использованы этим полем. Опция choices - это массив, где ключ массива - это ярлык объёкта, а значение массива - это значение объекта:

1
2
3
4
5
6
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('inStock', ChoiceType::class, array(
    'choices' => array('In Stock' => true, 'Out of Stock' => false),
));

choice_attr

type: array, callable or string default: array()

Use this to add additional HTML attributes to each choice. This can be an array of attributes (if they are the same 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('attending', ChoiceType::class, array(
    'choices' => array(
        'Yes' => true,
        'No' => false,
        'Maybe' => null,
    ),
    'choice_attr' => function($val, $key, $index) {
        // adds a class like attending_yes, attending_no, etc
        return ['class' => 'attending_'.strtolower($key)];
    },
));

choice_label

type: string, callable or false default: null

Normally, the array key of each item in the choices option is used as the text that's shown to the user. The choice_label option allows you to take more control:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('attending', ChoiceType::class, array(
    'choices' => array(
        'yes' => true,
        'no' => false,
        'maybe' => null,
    ),
    'choice_label' => function ($value, $key, $index) {
        if ($value == true) {
            return 'Definitely!';
        }
        return strtoupper($key);

        // or if you want to translate some key
        //return 'form.choice.'.$key;
    },
));

This method is called for each choice, passing you the choice $value and the $key from the choices array ($index is related to choice_value). This will give you:

../../../_images/choice-example2.png

If your choice values are objects, then choice_label can also be a property path. Imagine you have some Status class with a getDisplayName() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('attending', ChoiceType::class, array(
    'choices' => array(
        new Status(Status::YES),
        new Status(Status::NO),
        new Status(Status::MAYBE),
    ),
    'choice_label' => 'displayName',
));

If set to false, all the tag labels will be discarded for radio or checkbox inputs. You can also return false from the callable to discard certain labels.

choice_loader

тип: ChoiceLoaderInterface

choice_loader может быть использован только для частичной загрузки вариантов в случаях, когда загруженный полностью список не нужен. Это необходимо только в продвинутых случаях и заменяет опцию choices.

New in version 3.2: CallbackChoiceLoader был представлен в Symfony 3.2.

Вы можете использовать экземпляр CallbackChoiceLoader, если вы хотите воспользоваться преимуществами ленивой загрузки:

1
2
3
4
5
6
7
8
9
use Symfony\Component\Form\ChoiceList\Loader\CallbackChoiceLoader;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('constants', ChoiceType::class, array(
    'choice_loader' => new CallbackChoiceLoader(function() {
        return StaticClass::getConstants();
    },
));

Это приведёт к отмене вызова StaticClass::getConstants(), если запрос перенаправлен и если нет предварительно установленных или отправленных данных. В других случаях, опции вариантов должны быть разрешены, запуская обратный вызов.

choice_name

type: callable or string 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.

This can be a callable or a property path. See choice_label for similar usage. If null is used, an incrementing integer is used as the name.

choice_translation_domain

type: string, boolean or null

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.

choice_value

type: callable or string default: null

Returns the string "value" for each choice. 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. See choice_label for similar usage. If null is used, an incrementing integer is used as the name.

If you are using a callable to populate choice_value, you need to check for the case that the value of the field may be null.

Caution

In Symfony 2.7, there was a small backwards-compatibility break with how the value attribute of options is generated. This is not a problem unless you rely on the option values in JavaScript. See issue #14825 for details.

choices_as_values

Эта опция устарела и вы должны удалить её их ваших проектов 3.x (её удаление не будет иметь никакого эффекта). Чтобы узнать о её цели в 2.x, см. документацию 2.7.

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: array, callable or string default: null

You can easily "group" options in a select simply 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('publishAt', ChoiceType::class, array(
    'choices' => array(
        'now' => new \DateTime('now'),
        'tomorrow' => new \DateTime('+1 day'),
        '1 week' => new \DateTime('+1 week'),
        '1 month' => new \DateTime('+1 month')
    ),
    'group_by' => function($val, $key, $index) {
        if ($val <= new \DateTime('+3 days')) {
            return 'Soon';
        } else {
            return 'Later';
        }
    },
));

This groups the dates that are within 3 days into "Soon" and everything else into a "Later" group:

../../../_images/choice-example5.png

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.

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.

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:

    1
    2
    3
    4
    5
    6
    use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
    // ...
    
    $builder->add('states', ChoiceType::class, array(
        'placeholder' => 'Choose an option',
    ));
    
  • Guarantee that no "empty" value option is displayed:

    1
    2
    3
    4
    5
    6
    use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
    // ...
    
    $builder->add('states', ChoiceType::class, array(
        '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:

1
2
3
4
5
6
7
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

// a blank (with no text) option will be added
$builder->add('states', ChoiceType::class, array(
    'required' => false,
));

preferred_choices

type: array, callable or string default: array()

This option allows you to move certain choices to the top of your list with a visual separator between them and the rest of the options. If you have a form of languages, you can list the most popular on top, like Bork Bork and Pirate:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('language', ChoiceType::class, array(
    'choices' => array(
        'English' => 'en',
        'Spanish' => 'es',
        'Bork'   => 'muppets',
        'Pirate' => 'arr'
    ),
    'preferred_choices' => array('muppets', 'arr')
));

This options can also be a callback function to give you more flexibility. This might be especially useful if your values are objects:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('publishAt', ChoiceType::class, array(
    'choices' => array(
        'now' => new \DateTime('now'),
        'tomorrow' => new \DateTime('+1 day'),
        '1 week' => new \DateTime('+1 week'),
        '1 month' => new \DateTime('+1 month')
    ),
    'preferred_choices' => function ($val, $key) {
        // prefer options within 3 days
        return $val <= new \DateTime('+3 days');
    },
));

This will "prefer" the "now" and "tomorrow" choices only:

../../../_images/choice-example3.png

Finally, if your values are objects, you can also specify a property path string on the object that will return true or false.

The preferred choices are only meaningful when rendering a select element (i.e. expanded false). The preferred choices and normal choices are separated visually by a set of dotted lines (i.e. -------------------). This can be customized when rendering the field:

  • Twig
    1
    {{ form_widget(form.publishAt, { 'separator': '=====' }) }}
    
  • PHP
    1
    2
    3
    <?php echo $view['form']->widget($form['publishAt'], array(
              'separator' => '====='
    )) ?>
    

Переопределённые опции

compound

тип: boolean по умолчанию: то же значение, что и опция expanded

Эта опция указывает, является ли форма составной. Значение по умолчанию переопределяется значением опции expanded.

empty_data

type: mixed

Настоящее значение этой опции по умолчанию зависит от других опций поля:

  • Если multiple - false, а expanded - false, то '' (пустая строка);
  • Иначе - array() (пустой массив).

This option determines what value the field will return when the submitted value is empty (or missing). It does not set an initial value if none is provided when the form is rendered in a view.

This means it helps you handling form submission with blank fields. For example, if you want the name field to be explicitly set to John Doe when no value is selected, you can do it like this:

1
2
3
4
$builder->add('name', null, array(
    'required'   => false,
    'empty_data' => 'John Doe',
));

This will still render an empty text box, but upon submission the John Doe value will be set. Use the data or placeholder options to show this initial value in the rendered form.

If a form is compound, you can set empty_data as an array, object or closure. See the How to Configure empty Data for a Form Class article for more details about these options.

Note

If you want to set the empty_data option for your entire form class, see the How to Configure empty Data for a Form Class article.

Caution

Form data transformers will still be applied to the empty_data value. This means that an empty string will be cast to null. Use a custom data transformer if you explicitly want to return the empty string.

error_bubbling

тип: boolean по умолчанию: false

Настройте так, чтобы ошибка в этом поле была присоединена к полю, а не к родительскому полю (в большинстве случаев - форме).

Наследуемые опции

Эти опции наследуются из FormType:

by_reference

type: boolean default: true

In most cases, if you have an author field, then you expect setAuthor() to be called on the underlying object. In some cases, however, setAuthor() may not be called. Setting by_reference to false ensures that the setter is called in all cases.

To explain this further, here's a simple example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
// ...

$builder = $this->createFormBuilder($article);
$builder
    ->add('title', TextType::class)
    ->add(
        $builder->create('author', FormType::class, array('by_reference' => ?))
            ->add('name', TextType::class)
            ->add('email', EmailType::class)
    )

If by_reference is true, the following takes place behind the scenes when you call submit() (or handleRequest()) on the form:

1
2
3
$article->setTitle('...');
$article->getAuthor()->setName('...');
$article->getAuthor()->setEmail('...');

Notice that setAuthor() is not called. The author is modified by reference.

If you set by_reference to false, submitting looks like this:

1
2
3
4
5
$article->setTitle('...');
$author = clone $article->getAuthor();
$author->setName('...');
$author->setEmail('...');
$article->setAuthor($author);

So, all that by_reference=false really does is force the framework to call the setter on the parent object.

Similarly, if you're using the CollectionType field where your underlying collection data is an object (like with Doctrine's ArrayCollection), then by_reference must be set to false if you need the adder and remover (e.g. addAuthor() and removeAuthor()) to be called.

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:

1
2
3
4
5
6
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
// ...

$builder->add('token', HiddenType::class, array(
    '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 overriden when the form edits an already persisted object, causing it to lose it's 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.

error_mapping

type: array default: array()

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:

1
2
3
4
5
6
7
8
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'error_mapping' => array(
            '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 simply propertyName;
  • If the violation is generated on an entry of an array or ArrayAccess 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 simply 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:

1
2
3
4
5
$resolver->setDefaults(array(
    'error_mapping' => array(
        '.' => 'city',
    ),
));

inherit_data

type: boolean default: false

This option determines if the form will inherit data from its parent form. This can be useful if you have a set of fields that are duplicated across multiple forms. See How to Reduce Code Duplication with "inherit_data".

Caution

When a field has the inherit_data option set, it uses the data of the parent form as is. This means that Data Transformers won't be applied to that field.

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 directly set inside 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: array()

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',
        array('label_attr' => array('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 build for each "path" to a field. To avoid duplicated keyword messages, you can configure the label format to a static value, like:

1
2
3
4
5
6
7
8
// ...
$profileFormBuilder->add('address', new AddressType(), array(
    'label_format' => 'form.address.%name%',
));

$invoiceFormBuilder->add('invoice', new AddressType(), array(
    '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 from 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.

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

Переменные поля

Переменная Тип Использование
multiple boolean Значение опции multiple.
expanded boolean Значение опции expanded.
preferred_choices array Вложенный массив, содержащий объекты ChoiceView вариантов, которые должны быть представлены пользователю с приоритетом.
choices array Вложенный массив, содержащий объекты ChoiceView оставшихся вариантов.
separator string Разделитель между группами вариантов.
placeholder mixed Пустое значение, если его ещё нет в списке, иначе - null.
choice_translation_domain mixed boolean, null или string, чтобы определить значение для перевода.
is_selected callable Вызываемое, которое берёт ChoiceView и выбранное знечение(я) и возвращает выбор выбранного значения(ий).
placeholder_in_choices boolean Есть ли пустое значение в списке вариантов.

Tip

Вместо этого намного быстрее использовать тест selectedchoice(selected_value) при использовании Twig.

Эта документация является переводом официальной документации Symfony и предоставляется по свободной лицензии CC BY-SA 3.0.