Retrieving data for custom validation


#1

I’m trying to add an application rule that requires information from a different model/tabel
But how can i find data from within a model application rule?

    public function buildRules(RulesChecker $rules)
    {
        ...
        $rules->add(function($entity, $options) {
            $ThisModel = $this->Model->find('all')
                ->where(['key_id' => $entity->key_id ])
                ->count();
            $AccosiatedModel = $this->AccosiatedModel->find()
                ->where(['key_id' => $entity->key_id ])->count();

            if($ThisModel <= $AccosiatedModel) {
                return true;
            } else {
                return false;
            }
        },'CutomRule');
        return $rules;
    }

#2

Solved it, adding a error message helps to see if it works.

    public function buildRules(RulesChecker $rules)
    {
        ...
        $rules->add(function($entity, $options) {
            $Model = $this->find('all')
                ->where(['key_id' => $entity->key_id ])
                ->count();
            $AccosiatedModel = $this->AccosiatedModel->find()
                ->where(['key_id' => $entity->key_id ])->count();

            if($Model <= $AccosiatedModel) {
                return true;
            } else {
                return false;
            }
        },'OnlyOnce',[
            'errorField' => 'key_id',
            'message' => __(' Only One message ')
        ]);
        ...
        return $rules;
    }