繁体   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