CakePHP: Access Model in other Model / in app_model.php for Validation of Banknumber

Bob picture Bob · May 7, 2011 · Viewed 8k times · Source

I am wondering how I could use data from a Model B while I am validating Model A, here to check if an entered Banknumber is a correct one:

My Users specify their bankaccount during the registration. E.g. the "banknumber". I am validating this the normal way in my user.php model

var $validate = array(
    'banknumber' => array(
        'minLength' => array(
            'rule' => array('minLength', 8),
            'message' => '...',
            'required' => true,
        ),

Now I want to know if the entered Banknumber is a real one, so I got a table "Banks" in my DB with all real Banknumbers, and I am using some own validation functions which I specify in app_model.php.

function checkBankExists($data) {
    if (!$this->Bank->findByBanknumber($data)) {
        return false;
    } else {
        return true;
    }       
}

But this is never working, because while I am validating the User-Model, I can only use this one in an app_model - function, accessing it with $this->name or so... a $this->Bank is NOT possible, I get:

Undefined property: User::$Bank [APP\app_model.php

Call to a member function findByBanknumber() on a non-object

Is there ANY way to import/access other models in a function in app_model.php?

Thank you!

Answer

Oli Stockman picture Oli Stockman · Jan 7, 2012

ClassRegistry should generally be used instead of AppImport as AppImport only loads the file, rather than registering it properly, cake style.

Using the example above.

$bnk = ClassRegistry::init('Bank');
$bnk->findByBanknumber($data);