Saving information in “sub” model in CakePHP
-
02-07-2019 - |
Question
I've got a simple CakePHP site (1.2)
. I've got a page where you can edit and save a Person. So I have a Person model and controller.
Each Person has none or more comments, in the comment table. So I have a Comment model, and I have a hasMany association on my Person model to the Comment model. View is working great.
My question is, on the view Person page, I have an add comment button. How should this work? Should I expect the Person controller to include a save for the comment record, or create a comment controller and save it outside of it's association for a person?
I'm experienced with PHP, but brand new to Cake.
Any ideas? I think I'm just missing something obvious, but I'm not sure what to do. I feel like if this was PHP
I would reference the Person_id in my add comment form, and thus use a separate controller, but I feel like having a controller for a simple Model is useless, since Comments are only edited in the context of a Person record.
Ideas?
Solution
I'm not a CakePHP expert, but I still think it would make sense to have your own controller. From what I remember from doing one of those CakePHP blog tutorials is, that you need to link the comments and the post in the comment model. This is some of the code I have from it:
class Comment extends AppModel
{
var $name = ‘Comment’;
var $belongsTo = array(‘Person’);
}
And then you need a controller (comments_controller.php):
class CommentsController extends AppController
{
var $name = ‘Comments’;
var $scaffold;
}
Some SQL:
CREATE TABLE comments (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
author VARCHAR(50),
comment TEXT,
person_id INT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
The $scaffold
creates a CRUD application for you, so when you go to /comments in your browser you can create, read, update and delete comments. So, as you see, there is not much involved here. All you need is your database tables and a little logic to provide person_id.
To save a comment (in your Person/view):
<h2>Add comment</h2>
<?php
echo $form->create(‘Comment’, array(‘action’=>‘add/’.$person[‘Person’][‘id’]);
echo $form->input(‘author’);
echo $form->input(‘content’);
echo $form->submit(‘Add comment’);
echo $form->end();
?>
And in your CommentsController:
function add($id = NULL) {
if (!empty($this->data)) {
$this->data['Comment']['person_id'] = $id;
$this->data['Comment']['id'] = '';
if ($this->Comment->save($this->data)) {
$this->Session->setFlash('Commented added');
$this->redirect($this->referer());
}
}
}
So you basically overwrite the standard add action, which Cake adds by itself. Hope that makes sense now. Also, you might need a route so it picks up /comments/add/ID. I don't know about this part. :)