Wow!! CakePHP is great!! Now I've even got my own behavior working. This is the latest models/behaviors/comment.php which I have come up with.
<?php
class CommentBehavior extends ModelBehavior
{
var $settings=array();
var $runtime=array();
var $Comment;
function __construct(){
$this->Comment=ClassRegistry::init('Comment','model');
}
function setup(&$model,$config = array()){
$this->settings[$model->alias]['assocAlias'] = $model->alias.'Comment';
return true;
}
public function beforeFind(&$model, $query){
$commentcond['Comment.model']=$model->alias;
if(!empty($query['conditions']) && is_array($query['conditions'])) {
foreach($query['conditions'] as $fieldName => $constraint) {
if(!strstr($fieldName,'Comment.')) {
continue;
}
$commentcond[$fieldName] = $constraint;
unset($query['conditions'][$fieldName]);
}
}
$this->runtime[$model->alias]['query']['conditions'] = $commentcond;
return $query;
}
public function afterFind(&$model,$results,$primary){
extract($this->settings[$model->alias]);
foreach($results as &$result){
if(!isset($result[$model->alias][$model->primaryKey])){
continue(1);
}
$commentcond=$this->runtime[$model->alias]['query']['conditions'];
$commentcond['Comment.foreign_key']=$result[$model->alias][$model->primaryKey];
$comment=$this->Comment->findAll($commentcond);
if(empty($comment)){
continue(1);
}
$result[$assocAlias]=$comment;
}
return $results;
}
public function beforeSave(&$model)
{
extract($this->settings[$model->alias]);
$this->runtime[$model->alias]['beforeSave'][$assocAlias] = $model->data[$assocAlias];
return true;
}
public function afterSave(&$model,$created)
{
extract($this->settings[$model->alias]);
$data=$this->runtime[$model->alias]['beforeSave'];
unset($this->runtime[$model->alias]['beforeSave']);
foreach($data[$assocAlias] as &$comment) {
if($created) {
$comment['foreign_key'] = $model->getLastInsertID();
} else {
$comment['foreign_key'] = $model->id;
}
if(!isset($comment['id'])) {
$this->Comment->create();
}
$comment['model'] = $model->alias;
$this->Comment->save($comment,false);
}
return true;
}
}
class Comment extends AppModel
{
var $name="Comment";
var $useTable="comments";
}
?>
And so to use it in the the model declaration you have to have the line:
var $actsAs=array('Comment');
And that's all set. You will receive the Comment parts too if you do a findAll() on it. To save Comment you'd have to do something like this:
$dcomment['Comment']['id']=1;
$dcomment['Comment']['description']="is it have funny cartooniiist dileb";
$this->data['MeetingComment'][]=$dcomment;
Saving that meeting would also save the meeting comment. Note the first line is if you are editing the comment. If you exclude it then you will actually save a new comment. Cool stuff. Now off to creating the controls for it.
