公式Cookbook
バリデーション
カスタムフォームを作成する
ここではmaxAmountというメソッドを定義して、$validatorに追加
class CustomForm extends Form
{
protected function _buildSchema(Schema $schema)
{
return $schema
->addField('amount', ['type' => 'integer'])
}
protected function _buildValidator(Validator $validator)
{
$validator
->integer('amount')
->greaterThan('amount', 0, __('金額を入力してください'))
->naturalNumber('amount', true, __('整数を入力してください'))
->add('amount', 'custom', [
'rule' => [$this, 'maxAmount'],
'message' => __('金額の上限を超えています')
]);
return $validator;
}
protected function _execute(array $data)
{
return true;
}
public function maxAmount($check, array $context)
{
if ($check > $context['providers']['hoge']['balance']) {
return false;
}
return true;
}
}
コントローラでバリデーションをする
カスタムフォームに定義したバリデーションメソッドの引数の$contextにバリデーションで使用する値を設定できる。
if ($this->request->is(['post'])) {
$form = new CustomForm();
$form->getValidator('default')->setProvider('hoge', ['balance' => 10000]);
if ($form->validate($this->request->getData())) {
// ok
} else {
// ng
}
}