簡體   English   中英

CakePhp - 如何在驗證中訪問記錄的 id?

[英]CakePhp - How to access the id of the record in validation?

要驗證 slug,我需要知道$entity->id的值。 然而,只有我們直接在$data傳遞它才能訪問它: $this->Accounts->patchEntity($entity, $data); .

public function validationDefault(Validator $validator) {
  $validator
    ->add('slug', [
      'isUnique' => [
        'rule' => function ($value, $context) {
          debug($this);
          debug($value);
          debug($context);
        }
      ]
    ]
}

我不能保證,我將始終在我的所有控制器中傳遞 id。 有什么方法可以訪問驗證規則中的$entity嗎?

無法在驗證中訪問$entity

但是,CakePhp 為這些驗證提供了一個特殊的 api - RulesChecker 它應該用於確保電子郵件的唯一性,例如。 buildRules()方法中,您可以訪問$entity

雖然基本數據驗證是在請求數據轉換為實體時完成的,但許多應用程序還有更復雜的驗證,只能在基本驗證完成后應用。 這些類型的規則通常稱為“域規則”或“應用程序規則”。 CakePHP 通過在實體持久化之前應用的“RulesCheckers”公開了這個概念。

您應該將buildRules()方法添加到您的表類中:

// Don't forget the import!
use Cake\ORM\RulesChecker;

public function buildRules(RulesChecker $rules){
    // Add a rule that is applied for create and update operations
    $rules->add(function ($entity, $options) {
        // Return a boolean to indicate pass/failure
    }, 'ruleName');

    // Add a rule for create.
    $rules->addCreate(function ($entity, $options) {
        // Return a boolean to indicate pass/failure
    }, 'ruleName');

    // Add a rule for update
    $rules->addUpdate(function ($entity, $options) {
        // Return a boolean to indicate pass/failure
    }, 'ruleName');

    // Add a rule for the deleting.
    $rules->addDelete(function ($entity, $options) {
        // Return a boolean to indicate pass/failure
    }, 'ruleName');

    return $rules;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM