Monday, February 8, 2010

Linking models in a CakePHP plugin

Last weekend I finally found the solution to a problem I was facing for a couple of days. I was trying to add data to a model in my plugin from the main app. The problem was that the data validation of that model did not work in the main app, while it worked from within the plugin.

After looking at this problem and asking on #cakephp on Freenode, the user rich97 eventually figured out what my problem was.

In my plugin I have two models which have a relationship, one for Articles and one for the Comments on that article. The problem was the definition of the relationships. I was refering to the correct className but without a refering to the plugin it is in, like this: 'className'=> 'SystemComment' while I ofcourse should mention the plugin too, like this: 'className'=> 'System.SystemComment' (with System being the name of my plugin).

Below you see the models with the correct className references.

Articles Model
<?php
class SystemArticle extends SystemAppModel {
   /* ... */
   var $hasMany = array(
       'SystemComment' => array(
           'className'     => 'System.SystemComment',
           'foreignKey'    => 'article_id',
           'dependent'=>true
       )
   );
}
?>
Comments Model
<?php
class SystemComment extends SystemAppModel {
   /* ... */
   var $validate = array(
       'email' => array(
           'rule' => array('email', true),
           'message' => 'Please supply a valid email address.'
       ),
       'comment' => array('notempty')
   );

   var $belongsTo = array(
       'SystemArticle' => array(
           'className' => 'System.SystemArticle',
           'foreignKey' => 'article_id'
       )
   );
}
?>
Thanks rich97! :)

2 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Unknown said...

In ones cherished career as a possible facts safety professional, sole of your principal steps regarding validating your current skills is actually to get Security+ Certified. Passing the exam with this certification is not therefore difficult. Nothing will probably replace your value connected with real time experience anyone gain on the arena.