I am learning CakePHP, my first MVC, and I have a few "best practice" questions.
This is my view for showing a news article:
<h1><?php echo h($post['Post']['title'])?></h1> <p><?php echo h($post['Post']['body'])?></p> <?php foreach ($post['Comment'] as $comment): ?> <div class="comment" style="margin-left:50px;"> <p><?php echo h($comment['body'])?></p> </div> <?php endforeach; echo $this->element('newcomment', array("post_id" => $post['Post']['id']));?>
I did not think you could use the add view to add a comment to another view, so I created an element. I hope the best practice for this.
My main “problem” was this: adding a comment. Do I add a hidden field to the field or add it to the form action?
I went with the "id in action" part because it is easier to repeat it for redirection afterwards. This is the newcomment element:
<h1>Add Comment</h1> <?php echo $this->Form->create('Comment',array('action' => 'add', 'url' => array($post_id))); echo $this->Form->input('body', array('rows' => '3')); echo $this->Form->end('Add comment'); ?>
And then this is the “add” function in the comment:
public function add($post_id = null) { if ($this->request->is('post')) { $this->Comment->set(array('post_id'=>$post_id)); if ($this->Comment->save($this->request->data)) { $this->Session->setFlash('Your comment has been added.');
How should it be?
I hope it will be good to ask such questions here. Using best practices is very important to me.
source share