【问题标题】:Symfony how to validate EntityType fieldSymfony 如何验证 EntityType 字段
【发布时间】:2018-05-05 14:34:01
【问题描述】:

我的 UserType 表单上有这个 EntityType 字段:

public function buildForm(FormBuilderInterface $builder, array $options)
{
        $builder->add('country', EntityType::class, array(
             'class' => Country::class,
             'choice_label' => 'nicename'
        ));
}

如何使用验证约束来验证此类字段,因为用户只能在国家/地区表的所有行范围内选择一个值?我认为我应该使用带有回调的选择约束,并在我的 CountryRepository 类中调用 getAllCountries 函数。那么管理这种情况的最佳方法是什么?

类似这样的:

// UserEntity.php

class User {

     /**
     * @Assert\Choice(callback="App\Repository\CountryRepository", "getAllCountries")
     * @ORM\ManyToOne(targetEntity="App\Entity\Country", inversedBy="users")
     */
    protected $country;
}

但 CountryRepository 不是静态函数!!

【问题讨论】:

    标签: php forms symfony validation orm


    【解决方案1】:

    实体字段不允许选择无效值(如果您有无效值,它将找不到实体 -> 将无法发送表单)。这也是选择类型的行为。

    但是对于回调,有一个特殊的回调约束——https://symfony.com/doc/current/reference/constraints/Callback.html,可以用来调用约束函数。

    【讨论】:

    • 那么如果用户操作 dom 并向实体选择框添加另一个元素,表单验证会自动发送错误吗?
    • 是的,您可以在thread 中看到,如果您想根据发送表单动态地为您的选择列表添加价值,您需要采取额外的步骤。
    猜你喜欢
    • 2020-10-22
    • 2016-03-21
    • 2011-06-27
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2021-11-30
    • 2014-03-04
    相关资源
    最近更新 更多