2014-12-08 27 views
2

無效數據我試圖完成以下任務:Symfony的2形式,包括自定義消息

$builder->add('some_field', 'some_type', array(
    // ... 
    'invalid_message'   => 'You entered an invalid value: %1%', 
    'invalid_message_parameters' => array('%1%' => ?), 
)); 

我的問題是,我想不出哪裏獲取%1%的價值。

從閱讀文檔和搜索這是我想出了。有沒有其他的方式來實現這一點?

回答

0

如果您再次查看文檔,您會看到您在此處複製的特定示例僅適用於某些formType(如整數),並非用於執行您想要實現的功能。

閱讀this first。你有很多約束的例子,以及如何設置正確的錯誤信息。

從你的代碼中,你不能猜測你想要做什麼,因爲沒有任何Contraint定義輸入值是無效的。 我建議做驗證的實體,如果你能做到這一點,這樣你就可以讓他們在資源/配置/ validation.yml

然後,你可以這樣做:

Acme\BlogBundle\Entity\Author: 
properties: 
    email: 
     - Email: 
      message: The email "{{ value }}" is not a valid email. 

價值在哪裏會打印你想要的。如果你需要的話,你可以定義一個custom Constraint

0

如果您的表單基於實體,則應使用validation.yml文件來使用約束。如果不是(或者,如果你是懶惰的),你也可以使用PHP添加約束您的形式是這樣的:

#Load the constraint you are going to use (for example length, which put min or max limits to your input length 
use Symfony\Component\Validator\Constraints\Length; 
# ... 
#then in your controller or formtype where you build your form: 
$form=$this->createFormBuilder() 
     ->add('newPassword', 'password', array(
      'required' => true, 
      'constraints' => array(
       new Length(array(
        'min' => 8, 
        'minMessage' => 'You have entered {{ value }} which is under the limit length {{ limit }}'))))) 
     ->getForm(); 

在這個例子中,我建立這必須是上面的限制密碼輸入(8)。請注意我在此輸入中如何實現length約束。然後使用{{ value }}打印該消息以訪問輸入的值。你應該找到不同的約束如何實現消息,在'長度約束'的情況下,你可以爲其他約束設置'minMessage'和'maxMessage',你只能使用'消息'。

0

如果你喜歡我正在尋找驗證信息來設置投擲TransformationFailedException,你可以簡單地使用由Symfony預先填充的{{ value }}

$builder->add('some_field', 'some_type', array(
    // ... 
    'invalid_message' => 'You entered an invalid value: {{ value }}' 
));