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
列舉中定義的三個可能值。使用 expanded 和 multiple 選項將這些值顯示為 <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),
};
}
}
繼承的選項
這些選項繼承自 ChoiceType
choice_attr
類型:array
、callable
、string
或 PropertyPath 預設值:[]
使用此選項可將其他 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
、string
或 PropertyPath 預設值: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
、false
或 PropertyPath 預設值: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
給您(額外的 $value
與 choice_value 相關)。這會給您

如果您的選項值是物件,則 choice_label
也可以是 屬性路徑。假設您有一個具有 getDisplayName()
方法的 Status
類別
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
可以使用 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
、string
或 PropertyPath 預設值: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
、boolean
或 null
預設值:true
此選項決定是否應翻譯選項值以及在哪個翻譯網域中翻譯。
choice_translation_domain
選項的值可以是 true
(重複使用目前的翻譯網域)、false
(停用翻譯)、null
(使用父翻譯網域或預設網域)或表示要使用的確切翻譯網域的字串。
choice_translation_parameters
類型:array
、callable
、string
或 PropertyPath 預設值:[]
選項值在顯示之前會先翻譯,因此它可以包含 翻譯預留位置。此選項定義用於取代這些預留位置的值。這可以是關聯陣列,其中鍵與選項鍵匹配,而值是每個選項的屬性、可呼叫物件或屬性路徑(就像 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
、string
或 PropertyPath 預設值: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
; - 如果違規是在
array
或ArrayAccess
物件的項目上產生的,則屬性路徑為[indexName]
; - 您可以透過串連巢狀屬性路徑來建構它們,並以點分隔屬性。例如:
addresses[work].matchingCityAndZipCode
; - 右側包含表單中欄位的名稱。
預設情況下,任何未對應屬性的錯誤都會冒泡到父表單。您可以使用點 (.
) 在左側將所有未對應屬性的錯誤對應到特定欄位。例如,若要將所有這些錯誤對應到 city
欄位,請使用
1 2 3 4 5
$resolver->setDefaults([
'error_mapping' => [
'.' => 'city',
],
]);
group_by
類型:string
或 callable
或 PropertyPath 預設值: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 個類別:Upper
、Lower
和 Other
。
如果您返回 null
,則選項將不會被分組。
duplicate_preferred_choices
type: boolean
default: 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
type: string
或 TranslatableMessage
或 boolean
此選項決定是否在 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
預設值:[]
使用此選項為 placeholder 選項新增額外的 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
、string
或 PropertyPath 預設值:[]
此選項允許您在列表頂部顯示某些選項,並在它們與完整選項列表之間使用視覺分隔符號。如果您有一個語言表單,您可以將最常用的語言列在頂部,例如 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" 選項

最後,如果您的值是物件,您也可以在物件上指定一個屬性路徑字串,該字串將傳回 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」選項文件。
attr
類型:array
預設值:[]
如果您想為 HTML 欄位表示新增額外屬性,您可以使用 attr
選項。它是一個關聯陣列,其中 HTML 屬性作為鍵。當您需要為某些小工具設定自訂類別時,這會很有用
1 2 3
$builder->add('body', TextareaType::class, [
'attr' => ['class' => 'tinymce'],
]);
另請參閱
如果您想將這些屬性新增到 表單類型列 元素,請使用 row_attr
選項。
data
type: mixed
default: 預設為底層結構的欄位。
當您建立表單時,每個欄位最初都會顯示表單網域資料的相應屬性值(例如,如果您將物件繫結到表單)。如果您想覆寫表單或個別欄位的此初始值,您可以在 data 選項中設定它
1 2 3 4 5 6
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
// ...
$builder->add('token', HiddenType::class, [
'data' => 'abcdef',
]);
警告
data
選項在呈現時總是覆寫從網域資料(物件)取得的值。這表示當表單編輯已持久化的物件時,物件值也會被覆寫,導致它在表單提交時遺失其持久化的值。
empty_data
type: mixed
此選項決定當提交的值為空(或遺失)時,欄位將傳回什麼值。如果視圖中呈現表單時未提供初始值,則它不會設定初始值。
這表示它可以幫助您處理帶有空白欄位的表單提交。例如,如果您希望在未選取任何值時,將 name
欄位明確設定為 John Doe
,您可以這樣做
1 2 3 4
$builder->add('name', null, [
'required' => false,
'empty_data' => 'John Doe',
]);
這仍然會呈現一個空白文字方塊,但在提交時,將會設定 John Doe
值。使用 data
或 placeholder
選項在呈現的表單中顯示此初始值。
注意
如果表單是複合的,您可以將 empty_data
設定為陣列、物件或閉包。可以為您的整個表單類別設定此選項,請參閱 如何為表單類別設定空資料 文章以瞭解有關這些選項的更多詳細資訊。
警告
表單資料轉換器 仍將應用於 empty_data
值。這表示空字串將被轉換為 null
。如果您明確想要傳回空字串,請使用自訂資料轉換器。
help
type: string
或 TranslatableInterface
default: 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
type: string
或 TranslatableMessage
default: 標籤是從欄位名稱「猜測」而來
設定呈現欄位時將使用的標籤。設定為 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
type: string
default: null
配置用作欄位標籤的字串,以防未設定 label
選項。當使用 關鍵字翻譯訊息 時,這非常有用。
如果您使用關鍵字翻譯訊息作為標籤,您通常最終會為同一個標籤設定多個關鍵字訊息(例如 profile_address_street
、invoice_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
選項在表單主題中評估。如果您 自訂了表單主題,請務必更新您的範本。
required
type: boolean
default: true
如果為 true,將會呈現 HTML5 required 屬性。對應的 label
也會以 required
類別呈現。
這是表面現象,與驗證無關。在最好的情況下,如果您讓 Symfony 猜測您的欄位類型,那麼此選項的值將會從您的驗證資訊中猜測出來。
注意
required 選項也會影響如何處理每個欄位的空資料。有關更多詳細資訊,請參閱 empty_data 選項。