LoginSignup
2
2

More than 5 years have passed since last update.

Entityに設定したValidationを直接使う

Posted at

CSVファイルもバリデーションしたい

通常のformからの入力だけではなく、CSVで一括入力などを実装する場合、Entityに設定したAnnotationなどで記載したValidationを流用したい場合があると思います。

実装例

controllerで、以下の通りに書くことができます。

controller
$user = new user(); // Entity
$user->setName($row[0]); // $rowは、csvの値が詰まった配列

$validator = $this->get('validator');
$error = $validator->validate($user);
if ($error->count()) {
    // error発生
}

ちょっと解説

ちょっと解説すると、一旦、userというEntityに、対象のCSVの値を詰めます。
そのご、validatorサービスを呼び出して、validateメソッドにCSVの値を詰めたEntityを渡すと、validationが実行され、結果が返されます。

その結果を、ユーザーに通知してあげれば、いいのです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2