3
0

More than 3 years have passed since last update.

setErrors 上書き出来ない cakePHP

Last updated at Posted at 2021-08-09

はじめに

気力と体力がほとんどないのでちょっと乱雑な文章になりそうですが、
共有したいことは共有出来ているはずなので優しい心でお願いします!:bow:

バリデーションエラーの一部をなかったことにしたいけど少し戸惑ったのでここに残しておきます!

ちなみになぜそうしたかったかですが、Formでエラー表示しないとしてもエレメントで確認すると表示に違いがあるな〜〜〜と思い、これじゃだめだ!!!!だめなんだ!!!となりました、、

ちなみに表示させたくなかった文言は『このメールアドレスはすでに使用されています。』です。どのメールアドレスが登録されているかバレちゃうので、、:rolling_eyes:

では早速


$fix_errors = $user->getErrors();
$fix_errors['email'] = null; //キーごと無くすunsetでは上手くいかなく戸惑いました、
$user->setErrors($fix_errors, true); //メソッド確認したら上書きするかの指定しないといけなかったのね、、と

ちなみに

    /**
     * Sets error messages to the entity
     *
     * @param array $errors The array of errors to set.
     * @param bool $overwrite Whether or not to overwrite pre-existing errors for $fields
     * @return $this
     */
    public function setErrors(array $errors, bool $overwrite = false);

おまけ(エレメントの確認)

<input type="email" name="email" placeholder="メールアドレス" required="required" data-validity-message="入力してください" oninvalid="this.setCustomValidity(''); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)" oninput="this.setCustomValidity('')" id="email" value="aaab@s.com" maxlength="191"> //使用されているメールアドレスもの


<input type="email" name="email" placeholder="メールアドレス" required="required" data-validity-message="入力してください" oninvalid="this.setCustomValidity(''); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)" oninput="this.setCustomValidity('')" id="email" value="aaabaaa@s.com" maxlength="191"> //使用されていないメールアドレスもの

あと最初は以下のようにやろうとしてました、、セキュリティ的な問題等なければ以下でも問題ないかと思います!

if ($isShowEmailError === true) {
    echo $this->Form->control('email', ['placeholder'=>'メールアドレス', 'label' => '']);
} else {
    echo $this->Form->control('email', ['placeholder'=>'メールアドレス', 'label' => '', 'error' => false]);
}

最後に

そもそものメールアドレスが間違っている時等ははエラーが表示されるように、エラーを削除する前にエラー内容の確認は必須かと思います!以下のような場合のエラー表示は必要ですからね( ・ὢ・ )

3
0
1

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
3
0