【问题标题】:Symfony 3 form assigns error to the FormType instead of the actual fieldSymfony 3 表单将错误分配给 FormType 而不是实际字段
【发布时间】:2016-07-11 15:43:27
【问题描述】:

我用这个设置在 Symfony 中创建了一个表单:

#\src\AppBundle\Entity\Order.php

class Order
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string $orderID
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    protected $orderID;

    /**
     * @var string $email
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    protected $email;

    ...

在我的表单类型中:

# \src\AppBundle\Form\OrderType.php

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('order_id', TextType::class, [
                    'label' => 'index.order_id',
                    'attr' => array(
                        'placeholder' => 'index.order_id.placeholder'
                    )
                ])
                ->add('email', EmailType::class, [
                    'label' => 'index.email',
                    'attr' => array(
                        'placeholder' => 'index.email.placeholder'
                    )
                ]);
        }

        ...

因此,如果我提交带有空字段的表单,Symfony 会检测到这两个错误,但订单 ID 错误被分配给类而不是实际字段。

有什么想法吗?

更新

我将protected $orderID;重命名为protected $orderid;,问题就解决了!那么为什么会这样呢?在属性名称中使用 ID 时是否有任何保留名称?

【问题讨论】:

    标签: forms validation doctrine-orm symfony assert


    【解决方案1】:

    我认为你应该有这个,因为这是你在 buildForm 中指定的:

    /**
      * @var string $order_id
      *
      * @ORM\Column(type="string")
      * @Assert\NotBlank()
      */
    protected $order_id;
    

    你可以试试吗?

    【讨论】:

    • 这与教义如何生成/解析实体属性有关。根据 Symfony 最佳实践,我们应该对变量、函数和方法名称、参数使用驼峰命名法,而不是下划线,参见 Naming Conventions
    猜你喜欢
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    相关资源
    最近更新 更多