[英]Symfony how to validate EntityType field
我在UserType的表單上有這個EntityType字段:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('country', EntityType::class, array(
'class' => Country::class,
'choice_label' => 'nicename'
));
}
如何使用驗證約束來驗證此類型的字段,方式是用戶只能選擇country表的所有行范圍內的值? 我認為我應該使用Choice約束和回調,並在我的CountryRepository類中調用getAllCountries函數。 那么管理這種情況的最佳方法是什么?
像這樣的東西:
// UserEntity.php
class User {
/**
* @Assert\Choice(callback="App\Repository\CountryRepository", "getAllCountries")
* @ORM\ManyToOne(targetEntity="App\Entity\Country", inversedBy="users")
*/
protected $country;
}
但是CountryRepository不是靜態函數!!
實體字段不允許選擇無效值(如果您有無效值,它將找不到實體 - >將無法發送表單)。 這也是選擇類型的行為。
但是對於回調,有一個特殊的回調約束 - https://symfony.com/doc/current/reference/constraints/Callback.html ,它可以用來調用約束函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.