跳到内容

EnumType 字段

编辑此页

一个多用途字段,用于允许用户“选择”在 PHP 枚举 中定义的一个或多个选项。它扩展了 ChoiceType 字段,并定义了相同的选项。

渲染为 可以是各种标签 (见下文)
默认无效消息 所选选项无效。
父类型 ChoiceType
EnumType

提示

可以通过在你的应用中运行此命令来查看此表单类型定义和继承的完整选项列表

1
2
# replace 'FooType' by the class name of your form type
$ php bin/console debug:form FooType

用法示例

在使用此字段之前,你需要先在你的应用程序中的某个位置定义一些 PHP 枚举(或简称“enum”)。此枚举必须是“backed enum”类型,其中每个关键字定义一个标量值,例如字符串

1
2
3
4
5
6
7
8
9
// src/Config/TextAlign.php
namespace App\Config;

enum TextAlign: string
{
    case Left = 'Left aligned';
    case Center = 'Center aligned';
    case Right = 'Right aligned';
}

与在 choices 选项中使用枚举值不同,EnumType 只需要定义指向枚举的 class 选项

1
2
3
4
5
use App\Config\TextAlign;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
// ...

$builder->add('alignment', EnumType::class, ['class' => TextAlign::class]);

这将显示一个 <select> 标签,其中包含 TextAlign 枚举中定义的三个可能的值。使用 expandedmultiple 选项将这些值显示为 <input type="checkbox"><input type="radio">

<select> 元素的 <option> 中显示的标签是枚举名称。PHP 为这些名称定义了一些严格的规则(例如,它们不能包含点或空格)。如果你需要这些标签具有更高的灵活性,你的枚举可以实现 TranslatableInterface 来翻译或显示自定义标签

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
// src/Config/TextAlign.php
namespace App\Config;

use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

enum TextAlign: string implements TranslatableInterface
{
    case Left = 'Left aligned';
    case Center = 'Center aligned';
    case Right = 'Right aligned';

    public function trans(TranslatorInterface $translator, ?string $locale = null): string
    {
        // Translate enum from name (Left, Center or Right)
        return $translator->trans($this->name, locale: $locale);

        // Translate enum using custom labels
        return match ($this) {
            self::Left  => $translator->trans('text_align.left.label', locale: $locale),
            self::Center => $translator->trans('text_align.center.label', locale: $locale),
            self::Right  => $translator->trans('text_align.right.label', locale: $locale),
        };
    }
}

字段选项

class

类型: string 默认值: (没有默认值)

PHP 枚举的完全限定类名 (FQCN),用于获取此表单字段显示的选项值。

继承的选项

这些选项继承自 ChoiceType

choice_attr

类型: array, callable, stringPropertyPath 默认值: []

使用此选项为每个选项添加额外的 HTML 属性。这可以是一个关联数组,其中键与选项键匹配,值是每个选项的属性;也可以是一个可调用对象或属性路径(就像 choice_label 一样)。

如果是一个数组,则 choices 数组的键必须用作键

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
27
28
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, string $key, mixed $value) {
        // adds a class like attending_yes, attending_no, etc
        return ['class' => 'attending_'.strtolower($key)];
    },
]);

提示

当定义自定义类型时,你应该使用 ChoiceList 类助手

1
2
3
4
5
6
7
8
9
use App\Entity\Category;
use Symfony\Component\Form\ChoiceList\ChoiceList;

// ...
$builder->add('choices', ChoiceType::class, [
    'choice_attr' => ChoiceList::attr($this, function (?Category $category): array {
        return $category ? ['data-uuid' => $category->getUuid()] : [];
    }),
]);

请参阅 "choice_loader" 选项文档

choice_filter

类型: callable, stringPropertyPath 默认值: null

当使用来自 Symfony 核心或供应商库的预定义选项类型(即 CountryType)时,此选项允许你定义一个可调用对象,该对象将每个选项作为唯一参数,并且必须返回 true 以保留该选项,或返回 false 以丢弃该选项

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
27
28
29
30
31
32
33
34
35
36
// src/Form/Type/AddressType.php
namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AddressType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                // enable this type to accept a limited set of countries
                'allowed_countries' => null,
            ])
        ;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $allowedCountries = $options['allowed_countries'];

        $builder
            // ...
            ->add('country', CountryType::class, [
                // if the AddressType "allowed_countries" option is passed,
                // use it to create a filter
                'choice_filter' => $allowedCountries ? function ($countryCode) use ($allowedCountries): bool {
                    return in_array($countryCode, $allowedCountries, true);
                } : null,

            ])
        ;
    }

当选项是对象时,该选项可以是可调用对象或属性路径

1
2
3
4
5
6
7
// ...
$builder
    ->add('category', ChoiceType::class, [
        // ...
        'choice_filter' => 'isSelectable',
    ])
;

提示

考虑到此 AddressType 可能是 CollectionType 的一个条目,你应该使用 ChoiceList 类助手来启用缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Form/Type/AddressType.php
// ...
use Symfony\Component\Form\ChoiceList\ChoiceList;

// ...
'choice_filter' => $allowedCountries ? ChoiceList::filter(
    // pass the type as first argument
    $this,
    function (string $countryCode) use ($allowedCountries): bool {
        return in_array($countryCode, $allowedCountries, true);
    },
    // pass the option that makes the filter "vary" to compute a unique hash
    $allowedCountries
) : null,
// ...

choice_label

类型: string, callable, falsePropertyPath 默认值: null

默认情况下,choices 选项中每个项目的数组键用作向用户显示的文本。choice_label 选项允许你进行更多控制

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

$builder->add('attending', ChoiceType::class, [
    'choices' => [
        'yes' => true,
        'no' => false,
        'maybe' => null,
    ],
    'choice_label' => function ($choice, string $key, mixed $value): TranslatableMessage|string {
        if (true === $choice) {
            return 'Definitely!';
        }

        return strtoupper($key);

        // or if you want to translate some key
        //return 'form.choice.'.$key;
        //return new TranslatableMessage($key, false === $choice ? [] : ['%status%' => $value], 'store');
    },
]);

此方法为每个选项调用,并将 $choice$key 从 choices 数组传递给你(附加的 $valuechoice_value 相关)。这将给你提供

A choice list with the options "Definitely!", "NO" and "MAYBE".

如果你的选项值是对象,则 choice_label 也可以是 属性路径。假设你有一个 Status 类,其中包含一个 getDisplayName() 方法

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

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

如果设置为 false,则所有标签标签将为单选按钮或复选框输入而被丢弃。你也可以从可调用对象返回 false 以丢弃某些标签。

提示

当定义自定义类型时,你应该使用 ChoiceList 类助手

1
2
3
4
5
6
use Symfony\Component\Form\ChoiceList\ChoiceList;

// ...
$builder->add('choices', ChoiceType::class, [
    'choice_label' => ChoiceList::label($this, 'displayName'),
]);

请参阅 "choice_loader" 选项文档

choice_loader

类型: ChoiceLoaderInterface

choice_loader 选项可以代替 choices 选项使用。它允许在仅获取一组提交值的选项时,延迟或部分地创建列表(即,查询像 ElasticSearch 这样的搜索引擎可能是一个繁重的过程)。

如果你想利用延迟加载,可以使用 CallbackChoiceLoader 的实例

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

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

如果请求被重定向并且没有预设或提交的数据,这将导致 StaticClass::getConstants() 的调用不会发生。否则,选项选项将需要被解析,从而触发回调。

如果内置的 CallbackChoiceLoader 不符合你的需求,你可以通过实现 ChoiceLoaderInterface 或扩展 AbstractChoiceLoader 来创建你自己的加载器。这个抽象类通过实现接口的一些方法来为你节省一些样板代码,因此你只需实现 loadChoices() 方法即可获得一个功能齐全的选项加载器。

当你定义一个自定义选项类型,该类型可能在许多字段(如集合的条目)中重复使用,或者在多个表单中一次重复使用时,你应该使用 ChoiceList 静态方法来包装加载器,并使选项列表可缓存以获得更好的性能

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use App\Form\ChoiceList\CustomChoiceLoader;
use App\StaticClass;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\ChoiceList\ChoiceList;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ConstantsType extends AbstractType
{
    public function getParent(): string
    {
        return ChoiceType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            // the example below will create a CallbackChoiceLoader from the callable
            'choice_loader' => ChoiceList::lazy($this, function () {
                return StaticClass::getConstants();
            }),

            // you can pass your own loader as well, depending on other options
            'some_key' => null,
            'choice_loader' => function (Options $options): ChoiceLoaderInterface {
                return ChoiceList::loader(
                    // pass the instance of the type or type extension which is
                    // currently configuring the choice list as first argument
                    $this,
                    // pass the other option to the loader
                    new CustomChoiceLoader($options['some_key']),
                    // ensure the type stores a loader per key
                    // by using the special third argument "$vary"
                    // an array containing anything that "changes" the loader
                    [$options['some_key']]
                );
            },
        ]);
    }
}

choice_name

类型: callable, stringPropertyPath 默认值: null

控制选项的内部字段名称。你通常不必关心这个,但在某些高级情况下,你可能会用到。例如,此“名称”将成为模板中选项视图的索引,并用作字段名称属性的一部分。

这可以是可调用对象或属性路径。有关类似用法,请参阅 choice_label。默认情况下,可以使用选项键或递增的整数(从 0 开始)。

提示

当定义自定义类型时,你应该使用 ChoiceList 类助手

1
2
3
4
5
6
use Symfony\Component\Form\ChoiceList\ChoiceList;

// ...
$builder->add('choices', ChoiceType::class, [
    'choice_name' => ChoiceList::fieldName($this, 'name'),
]);

请参阅 "choice_loader" 选项文档

警告

配置的值必须是有效的表单名称。使用可调用对象时,请确保仅返回有效名称。有效的表单名称必须由字母、数字、下划线、破折号和冒号组成,并且不能以破折号或冒号开头。

choice_translation_domain

类型: string, booleannull 默认值: true

此选项确定是否应翻译选项值以及在哪个翻译域中翻译。

choice_translation_domain 选项的值可以是 true (重用当前翻译域)、false (禁用翻译)、null (使用父翻译域或默认域)或表示要使用的确切翻译域的字符串。

choice_translation_parameters

类型: array, callable, stringPropertyPath 默认值: []

选项值在显示之前会被翻译,因此它可以包含 翻译占位符。此选项定义用于替换这些占位符的值。这可以是一个关联数组,其中键与选项键匹配,值是每个选项的属性;也可以是一个可调用对象或属性路径(就像 choice_label 一样)。

给定此翻译消息

1
2
3
# translations/messages.en.yaml
form.order.yes: 'I confirm my order to the company %company%'
form.order.no: 'I cancel my order'

你可以按如下方式指定占位符值

1
2
3
4
5
6
7
8
9
10
11
12
13
$builder->add('id', null, [
    'choices' => [
        'form.order.yes' => true,
        'form.order.no' => false,
    ],
    'choice_translation_parameters' => function ($choice, string $key, mixed $value): array {
        if (false === $choice) {
            return [];
        }

        return ['%company%' => 'ACME Inc.'];
    },
]);

如果是一个数组,则 choices 数组的键必须用作键

1
2
3
4
5
6
7
8
9
10
$builder->add('id', null, [
    'choices' => [
        'form.order.yes' => true,
        'form.order.no' => false,
    ],
    'choice_translation_parameters' => [
        'form.order.yes' => ['%company%' => 'ACME Inc.'],
        'form.order.no' => [],
    ],
]);

子字段的翻译参数与其父字段的相同选项合并,因此子字段可以重用和/或覆盖任何父占位符。

choice_value

类型: callable, stringPropertyPath 默认值: null

为每个选项返回字符串“value”,该字符串在所有选项中必须是唯一的。这在 HTML 的 value 属性中使用,并在 POST/PUT 请求中提交。你通常不必担心这个,但在处理 API 请求时可能会很方便(因为你可以配置将在 API 请求中发送的值)。

这可以是可调用对象或属性路径。默认情况下,如果选项可以转换为字符串,则会使用选项。否则,将使用递增的整数(从 0 开始)。

如果你传递一个可调用对象,它将接收一个参数:选项本身。当使用 EntityType 字段 时,参数将是每个选项的实体对象,或者如果使用占位符,则为 null,你需要处理这种情况

1
2
3
'choice_value' => function (?MyOptionEntity $entity): string {
    return $entity ? $entity->getId() : '';
},

提示

当定义自定义类型时,你应该使用 ChoiceList 类助手

1
2
3
4
5
6
use Symfony\Component\Form\ChoiceList\ChoiceList;

// ...
$builder->add('choices', ChoiceType::class, [
    'choice_value' => ChoiceList::value($this, 'uuid'),
]);

请参阅 "choice_loader" 选项文档

error_bubbling

类型: boolean 默认值: false,除非表单是 compound

如果为 true,则此字段的任何错误都将传递给父字段或表单。例如,如果在普通字段上设置为 true,则该字段的任何错误都将附加到主表单,而不是特定的字段。

error_mapping

类型: array 默认值: []

此选项允许你修改验证错误的目标。

假设你有一个名为 matchingCityAndZipCode() 的自定义方法,该方法验证城市和邮政编码是否匹配。不幸的是,你的表单中没有 matchingCityAndZipCode 字段,因此 Symfony 所能做的只是在表单顶部显示错误。

通过自定义错误映射,你可以做得更好:将错误映射到城市字段,以便它显示在该字段上方

1
2
3
4
5
6
7
8
public function configureOptions(OptionsResolver $resolver): void
{
    $resolver->setDefaults([
        'error_mapping' => [
            'matchingCityAndZipCode' => 'city',
        ],
    ]);
}

以下是映射的左侧和右侧的规则

  • 左侧包含属性路径;
  • 如果违规是在类的属性或方法上生成的,则其路径为 propertyName
  • 如果违规是在 arrayArrayAccess 对象的条目上生成的,则属性路径为 [indexName]
  • 你可以通过连接嵌套属性路径来构造它们,用点分隔属性。例如:addresses[work].matchingCityAndZipCode
  • 右侧包含表单中字段的名称。

默认情况下,任何未映射属性的错误都将冒泡到父表单。你可以在左侧使用点(.)将所有未映射属性的错误映射到特定字段。例如,要将所有这些错误映射到 city 字段,请使用

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

expanded

类型: boolean 默认值: false

如果设置为 true,则将渲染单选按钮或复选框(取决于 multiple 值)。如果为 false,则将渲染 select 元素。

group_by

类型: stringcallablePropertyPath 默认值: null

你可以通过将多维数组传递给 choices,将 <select> 元素的 <option> 分组到 <optgroup> 中。请参阅关于此的 分组选项 部分。

group_by 选项是分组选项的另一种方法,它可以为你提供更大的灵活性。

让我们在 TextAlign 枚举中添加一些用例

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/Config/TextAlign.php
namespace App\Config;

enum TextAlign: string
{
    case UpperLeft = 'Upper Left aligned';
    case LowerLeft = 'Lower Left aligned';

    case Center = 'Center aligned';

    case UpperRight = 'Upper Right aligned';
    case LowerRight = 'Lower Right aligned';
}

我们现在可以按枚举用例值对选项进行分组

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

$builder->add('alignment', EnumType::class, [
    'class' => TextAlign::class,
    'group_by' => function(TextAlign $choice, int $key, string $value): ?string {
        if (str_starts_with($value, 'Upper')) {
            return 'Upper';
        }

        if (str_starts_with($value, 'Lower')) {
            return 'Lower';
        }

        return 'Other';
    }
]);

此回调将在 3 个类别中对选项进行分组:UpperLowerOther

如果返回 null,则该选项将不会被分组。

duplicate_preferred_choices

类型: boolean 默认值: true

当使用 preferred_choices 选项时,这些首选选项默认显示两次:在列表顶部和下面的完整列表中。将此选项设置为 false,以仅在列表顶部显示首选选项

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

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

multiple

类型: boolean 默认值: false

如果为 true,用户将能够选择多个选项(而不是仅选择一个选项)。根据 expanded 选项的值,如果为 true,这将渲染一个 select 标签或复选框,如果为 false,则渲染一个 select 标签或单选按钮。返回的值将是一个数组。

placeholder

类型: stringTranslatableMessageboolean

此选项确定是否在 select 小部件的顶部显示特殊的“空”选项(例如“选择一个选项”)。此选项仅在 multiple 选项设置为 false 时适用。

  • 添加一个空值,文本为“选择一个选项”

    1
    2
    3
    4
    5
    6
    7
    8
    9
    use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
    // ...
    
    $builder->add('states', ChoiceType::class, [
        'placeholder' => 'Choose an option',
    
        // or if you want to translate the text
        'placeholder' => new TranslatableMessage('form.placeholder.select_option', [], 'form'),
    ]);
  • 保证不显示“空”值选项

    1
    2
    3
    4
    5
    6
    use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
    // ...
    
    $builder->add('states', ChoiceType::class, [
        'placeholder' => false,
    ]);

如果你将 placeholder 选项保持未设置状态,则仅当 required 选项为 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, [
    'required' => false,
]);

placeholder_attr

类型: array 默认值: []

使用此选项为占位符选项添加额外的 HTML 属性

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

$builder->add('fruits', ChoiceType::class, [
    // ...
    'placeholder' => '...',
    'placeholder_attr' => [
        ['title' => 'Choose an option'],
    ],
]);

preferred_choices

类型: array, callable, stringPropertyPath 默认值: []

此选项允许你在列表顶部显示某些选项,并在它们与完整的选项列表之间使用可视分隔符。如果你有一个语言表单,你可以在顶部列出最流行的语言,例如 Bork 和 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, [
    'choices' => [
        'English' => 'en',
        'Spanish' => 'es',
        'Bork' => 'muppets',
        'Pirate' => 'arr',
    ],
    'preferred_choices' => ['muppets', 'arr'],
]);

此选项也可以是回调函数,以提供更大的灵活性。如果你的值是对象,这可能特别有用

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, [
    'choices' => [
        'now' => new \DateTime('now'),
        'tomorrow' => new \DateTime('+1 day'),
        '1 week' => new \DateTime('+1 week'),
        '1 month' => new \DateTime('+1 month'),
    ],
    'preferred_choices' => function ($choice, $key, $value): bool {
        // prefer options within 3 days
        return $choice <= new \DateTime('+3 days');
    },
]);

这将仅“首选” “now” 和 “tomorrow” 选项

A choice list with "now" and "tomorrow" on top, separated by a line from "1 week" and "1 month".

最后,如果你的值是对象,你还可以在对象上指定一个属性路径字符串,该字符串将返回 true 或 false。

首选选项仅在渲染 select 元素时才有意义(即 expanded 为 false)。首选选项和普通选项在视觉上用一组虚线分隔(即 -------------------)。这可以在渲染字段时进行自定义

1
{{ form_widget(form.publishAt, { 'separator': '=====' }) }}

提示

当定义自定义类型时,你应该使用 ChoiceList 类助手

1
2
3
4
5
6
use Symfony\Component\Form\ChoiceList\ChoiceList;

// ...
$builder->add('choices', ChoiceType::class, [
    'preferred_choices' => ChoiceList::preferred($this, 'taggedAsFavorite'),
]);

请参阅 "choice_loader" 选项文档

trim

类型: boolean 默认值: false

默认情况下禁用 Trim,因为所选值或值必须与给定的选项值完全匹配(并且它们可能包含空格)。

这些选项继承自 FormType

attr

类型: array 默认值: []

如果你想向 HTML 字段表示添加额外的属性,你可以使用 attr 选项。它是一个关联数组,其中 HTML 属性作为键。当你需要为某些小部件设置自定义类时,这可能很有用

1
2
3
$builder->add('body', TextareaType::class, [
    'attr' => ['class' => 'tinymce'],
]);

另请参阅

如果你想将这些属性添加到 表单类型行 元素,请使用 row_attr 选项。

data

类型: mixed 默认值: 默认为底层结构的字段。

当你创建一个表单时,每个字段最初显示表单域数据的相应属性的值(例如,如果你将对象绑定到表单)。如果你想覆盖表单或单个字段的此初始值,你可以在 data 选项中设置它

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

$builder->add('token', HiddenType::class, [
    'data' => 'abcdef',
]);

警告

data 选项在渲染时始终覆盖从域数据(对象)中获取的值。这意味着当表单编辑已持久化的对象时,对象值也会被覆盖,导致它在表单提交时丢失其持久化的值。

disabled

类型: boolean 默认值: false

如果你不希望用户修改字段的值,你可以将 disabled 选项设置为 true。任何提交的值都将被忽略。

empty_data

类型: mixed

此选项决定了当提交的值为空(或缺失)时,字段将返回什么值。如果表单在视图中渲染时没有提供初始值,则此选项不会设置初始值。

这意味着它可以帮助您处理带有空白字段的表单提交。例如,如果您希望在未选择任何值时将 name 字段显式设置为 John Doe,您可以这样做

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

这仍然会渲染一个空的文本框,但在提交时,John Doe 值将被设置。使用 dataplaceholder 选项可以在渲染的表单中显示此初始值。

注意

如果表单是复合表单,您可以将 empty_data 设置为数组、对象或闭包。此选项可以为您的整个表单类设置,有关这些选项的更多详细信息,请参阅“如何为表单类配置空数据”文章。

警告

表单数据转换器仍将应用于 empty_data 值。这意味着空字符串将被转换为 null。如果您明确想要返回空字符串,请使用自定义数据转换器。

help

类型: stringTranslatableInterface 默认值: null

允许您为表单字段定义帮助消息,默认情况下,该消息在字段下方呈现

1
2
3
4
5
6
7
8
9
10
11
12
13
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

类型: array 默认值: []

设置用于显示表单字段帮助消息的元素的 HTML 属性。其值是一个关联数组,其中 HTML 属性名称作为键。这些属性也可以在模板中设置

1
2
3
{{ form_help(form.name, 'Your name', {
    'help_attr': {'class': 'CUSTOM_LABEL_CLASS'}
}) }}

help_html

类型: boolean 默认值: false

默认情况下,help 选项的内容在模板中呈现之前会被转义。将此选项设置为 true 可以不转义它们,这在帮助内容包含 HTML 元素时非常有用。

label

类型: stringTranslatableMessage 默认值: 标签从字段名称中“猜测”

设置渲染字段时将使用的标签。设置为 false 将抑制标签

1
2
3
4
5
6
7
8
use Symfony\Component\Translation\TranslatableMessage;

$builder
    ->add('zipCode', null, [
        'label' => 'The ZIP/Postal code',
        // optionally, you can use TranslatableMessage objects as the label content
        'label' => new TranslatableMessage('address.zipCode', ['%country%' => $country], 'address'),
    ])

标签也可以在模板中设置

1
{{ form_label(form.name, 'Your name') }}

label_attr

类型: array 默认值: []

设置 <label> 元素的 HTML 属性,该属性将在渲染字段标签时使用。它是一个关联数组,其中 HTML 属性作为键。这些属性也可以直接在模板内部设置

1
2
3
{{ form_label(form.name, 'Your name', {
    'label_attr': {'class': 'CUSTOM_LABEL_CLASS'}
}) }}

label_html

类型: boolean 默认值: false

默认情况下,label 选项的内容在模板中呈现之前会被转义。将此选项设置为 true 可以不转义它们,这在标签内容包含 HTML 元素时非常有用。

label_format

类型: string 默认值: null

配置用作字段标签的字符串,以防未设置 label 选项。这在使用关键字翻译消息时非常有用。

如果您使用关键字翻译消息作为标签,您通常会为同一标签设置多个关键字消息(例如 profile_address_streetinvoice_address_street)。这是因为标签是为字段的每个“路径”构建的。为了避免重复的关键字消息,您可以将标签格式配置为静态值,例如

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

$invoiceFormBuilder->add('invoice', AddressType::class, [
    'label_format' => 'form.address.%name%',
]);

此选项由子类型继承。使用上面的代码,两个表单的 street 字段的标签都将使用 form.address.street 关键字消息。

标签格式中可以使用两个变量

%id%
字段的唯一标识符,由字段的完整路径和字段名称组成(例如 profile_address_street);
%name%
字段名称(例如 street)。

默认值 (null) 会生成字段名称的“人性化”版本

注意

label_format 选项在表单主题中评估。如果您自定义了表单主题,请确保更新您的模板。

mapped

类型: boolean 默认值: true

如果您希望在读取或写入对象时忽略该字段,可以将 mapped 选项设置为 false

required

类型: boolean 默认值: true

如果为 true,将渲染 HTML5 required 属性。相应的 label 也将使用 required 类进行渲染。

这是表面的,与验证无关。在最好的情况下,如果您让 Symfony 猜测您的字段类型,那么此选项的值将从您的验证信息中猜测出来。

注意

required 选项还会影响如何处理每个字段的空数据。有关更多详细信息,请参阅 empty_data 选项。

row_attr

类型: array 默认值: []

添加到用于渲染表单类型行的元素的 HTML 属性的关联数组

1
2
3
$builder->add('body', TextareaType::class, [
    'row_attr' => ['class' => 'text-editor', 'id' => '...'],
]);

另请参阅

如果您想将这些属性添加到表单类型 widget 元素,请使用 attr 选项。

本作品,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本