2016-08-08 1 views
4

Symfony2フォーム用の独自のバリデーターを作成しました。これはValidDateValidatorと呼ばれ、2015-02-31などの無効な日付を除外することになっています。私はこのように私のバリデータでこれにアクセスしようとした場合Symfony2:バリデーターの生のフォームデータにアクセス

->add(
     'thedate', 
     DateType::class, 
     array(
      'widget' => 'single_text', 
      'format' => 'yyyy-MM-dd', 
      'constraints' => array(
       new ValidDate() 
      ) 
     ) 
) 

は今:

public function validate($value, Constraint $constraint){ 
    //this returns 2015-03-03 
    echo $value->format('Y-m-d'); 
} 

私は、結果として、「2015年3月3日」を得るフォームタイプは、次のようになります。処理されていない生のフォームデータにアクセスする方法はありますか?

答えて

2

残念ながら、これは不可能です。検証ツールはdata transformationの後にデータを受け取ります。

あなたができることは、独自のビュートランスを作成し、標準のトランスフォーマの代わりに使用することです。ビュートランスフォーマは入力データを受け取り、これをノルムデータに変換します。 DateFieldの場合、これは単なるDateTime-Objectです。

この変換中に例外が発生すると、フォームエラーが発生する可能性があります。具体的には、DateFieldinvalid_messageが表示されます。

私はあなたに例をあげてみましょう:

トランス:フォームビルダーで

namespace AppBundle\Form\DataTransformer; 

use Doctrine\Common\Persistence\ObjectManager; 
use Symfony\Component\Form\DataTransformerInterface; 
use Symfony\Component\Form\Exception\TransformationFailedException; 

class StringToDateTransformer implements DataTransformerInterface 
{ 
    /** 
    * Transforms a DateTime object to a string . 
    * 
    * @param DateTime|null $date 
    * @return string 
    */ 
    public function transform($date) 
    { 
     if (null === $date) { 
      return ''; 
     } 

     return $date->format('Y-m-d'); 
    } 

    /** 
    * Transforms a string to a DateTime object. 
    * 
    * @param string $dateString 
    * @return DateTime|null 
    * @throws TransformationFailedException if invalid format/date. 
    */ 
    public function reverseTransform($dateString) 
    { 
     //Here do what ever you would like to do to transform the string to 
     //a DateType object 
     //The important thing is to throw an TransformationFailedException 
     //if something goes wrong (such as wrong format, or invalid date): 

     throw new TransformationFailedException('The date is incorrect!'); 

     return $dateTime; 
    } 
} 

$builder->get('thedate') 
      //Important! 
      ->resetViewTransformers() 
      ->addViewTransformer(new StringToDateTransformer()); 

resetViewTransformers()コールに注意してください。 DateTypeなどのフィールドには、すでにビュートランスフォーマーがあります。このメソッドを呼び出すと、このデフォルトのトランスフォーマーが取り除かれ、Transfomrerだけが呼び出されます。

+0

ありがとうございました。 – Chi

1

追加日を新しい日付に変換する\ DateTime ::形式。フォームからのデータではありません。

checkdateを使用すると、このような有効なコンポーネントがあるかどうかを確認できます。

$dateString = '2015-2-31'; 

$bits = explode('-', $dateString); // split the string 
list($y, $m, $d) = $bits; // variablise the parts 

if(checkdate($m, $d, $y)) { 
    // do something 
} else { 
    // do something else 
} 

example

関連する問題