0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3 - モデルのないフォームでカスタムバリデーションを使用する

Last updated at Posted at 2019-03-14

公式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
    }
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?