2015-06-28 55 views
0

我有一個包含需要整數的字段的表單。這是形式的實體類型定義的字段定義:Assert Type在Symfony2表單驗證中不起作用

/** 
* @ORM\Column(type="integer", nullable=true) 
* @Assert\Type(type="integer", message="Number of pieces must be a number.") 
* @Assert\GreaterThanOrEqual(value=1, message="Number of pieces cannot be lower than 1.") 
*/ 
protected $numberOfPiecesSent; 

相關表單生成器看起來像這樣:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('numberOfPiecesSent', 'integer', array('label' => 'Number of pieces sent:', 'required' => false)); 
} 

當我提交表單與該領域的非數值(比如,'aaa'),它只是保存表單並將字段numberOfPiecesSent NULL留在數據庫中,而不是驗證失敗。我也試圖讓這個字段非NULL,但這沒有幫助。任何想法,爲什麼這不起作用,請?

+0

你可以嘗試[regex](http://symfony.com/doc/current/reference/constraints/Regex.html) – BentCoder

+0

令人驚訝的是,即使正則表達式的作品。這很奇怪,因爲GreaterThanOrEqual()聲明有效,所以一般來說,我的聲明確實有效。 – pkout

+0

簽出下面的答案。 – BentCoder

回答

0

您是否試圖使字段不爲空: @ORM\Column(type="integer", nullable=false) 還是您嘗試過使用斷言NotNull? http://symfony.com/fr/doc/current/reference/constraints/NotNull.html

+0

我試過'@ORM \ Column(type =「integer」,nullable = false)' - 這沒有幫助。我沒有嘗試NotNull,因爲我實際上需要該字段是可選的。我只需要確保如果輸入任何值,它必須是一個數字。 – pkout

+0

Peut-on voir ton controllerégalement? – Kleinast

1

我剛剛測試過,這工作正常。您可以在下面的屬性中添加約束條件。您也可以刪除NotBlank。隨意修改。

實體

/** 
* @ORM\Column(type="integer", nullable=true) 
*/ 
protected $numberOfPiecesSent; 

形式

use Symfony\Component\Validator\Constraints\NotBlank; 
use Symfony\Component\Validator\Constraints\Range; 

->add(
    'numberOfPiecesSent', 
    'integer', 
    [ 
     'constraints' => [ 
      new NotBlank(
       [ 
        'message' => 'The numberOfPiecesSent is required.' 
       ] 
      ), 
      new Range(
       [ 
        'min' => 1, 
        'minMessage' => "The numberOfPiecesSent must contain at least {{ limit }}" 
       ] 
      ) 
     ] 
    ] 
) 

UPDATE

​​

OR

use Symfony\Component\Validator\Constraints\Regex; 

->add(
    'name', 
    'integer', 
    [ 
     'constraints' => [ 
      new Regex(
       [ 
        'pattern' => "/^[0-9]+$/" 
       ] 
      ) 
     ] 
    ] 
) 
+0

謝謝!我只是試過這個。它只適用於我使用NotBlank約束,我不想使用該約束,因爲我需要這個字段是可選的,所以這個解決方法對我來說不是一個解決方案。我真的好奇爲什麼Assert \ Type這個東西不起作用。我可能最終編寫自己的驗證器,但我更喜歡使用內置功能。 – pkout

+0

@pkout在這種情況下,使用正則表達式。見上面的更新。 – BentCoder

+0

謝謝。所以這真的適合你?我只是試過這個,它什麼都不做。當我提交'aaa'作爲字段的值時,它只是保存爲NULL。該字段上還設置了'required'=> false'。我在Symfony 2.7上。 – pkout