How to send a form for one model to another controller?

Say I have a message table and a comment table. I want my / posts / view / page to display a form on one page to post a comment, like any regular blog. I'm not sure where I am going wrong, but this is what I tried:

class PostsController extends AppController { var $name = 'Posts'; var $uses = array('Post', 'Cmt'); function view($id = null) { ... if (!empty($this->data)) { $this->Cmt->create(); if ($this->Cmt->save($this->data)) { $this->Session->setFlash(__('The cmt has been saved', true)); } } $this->set('post', $this->Post->read(null, $id)); } 

and in view

 <?php echo $this->Form->create('Cmt');?> <fieldset> <?php echo $this->Form->input('name'); echo $this->Form->input('email'); echo $this->Form->input('title'); echo $this->Form->input('content'); ?> <div class="input select required"><label for="CmtStpageId">Post</label> <select id="CmtPostId" name="data[Cmt][post_id]"> <option value="1">postname</option> </select> </div> </fieldset> <?php echo $this->Form->end(__('Submit', true));?> 

What is wrong here that the log entry will not be sent to the cmts table?

In addition, I have a message identifier hardcoded into this form, as you can see, because the select box does not populate the mail id for any reason. Any help with this would also be appreciated.

+3
source share
4 answers

When creating a form, you can explicitly specify which form action the url parameter uses:

 $this->Form->create('Cmt', array('url'=>$this->Html->url(array('controller'=>'cmts', 'action'=>'add')))); 

Regarding the Post ID, I assume that you have a 1-to-many relationship between posts and comments. If so, you should simply do the following in your view: echo $this->Form->input('post_id', array('type'=>'hidden')); Then in your view function set $this->data['Cmt']['post_id'] = $post['Post']['id']; so that it automatically fills up.

+6
source

I think it's better to do it like this ...

 $this->Form->create('Cmt', array('url'=>array('controller'=>'cmts', 'action'=>'add'))); 

option ['url'] already processes arrays with controller and action.

You will find it here: http://book.cakephp.org/view/1384/Creating-Forms#options-url-1387

+4
source

You can also use

 $this->Form->create('Cmt', array( 'action' => 'add' )); 

as this will lead you to the cmts controller and the action add is called.

+1
source

If you want to send data for comments, it is best to handle this in CmtsController.

Your view file in PostsController is fine

 <?php echo $this->Form->create('Cmt');?> 

will generate an action of the form "/ autogenerated_cake_base_url / cmts / view", and you process this on your CmtsController, and not on your PostsController.

0
source

All Articles