CakePHP – 2 controllers, 1 form

Posted by user1327 on Stack Overflow See other posts from Stack Overflow or by user1327
Published on 2012-11-21T22:56:15Z Indexed on 2012/11/21 22:59 UTC
Read the original article Hit count: 185

Filed under:
|

I need to create a review form. I have 2 models and 2 controllers – Products and Reviews with 'Products' hasMany 'Reviews' relationship, the review form will be displayed on the current product page (Products controller, 'view' action), and this form will be use another controller (Reviews).

Also I need validation with validation errors being displayed for this form.

In my Products controller view.ctp I have:

// product page stuff...

echo $this->Form->create($model = 'Review', array('url' => '/reviews/add'));
echo $this->Form->input('name', array('label' => 'Your name:'));
echo $this->Form->input('email', array('label' => 'Your e-mail:'));
echo $this->Form->input('message', array('rows' => '6', 'label' => 'Your message:'));
echo $this->Form->end('Send');

echo $this->Session->flash();

ReviewsController -> add:

public function add() {
if ($this->request->is('post')) {
    $this->Review->save($this->request->data); 
    $this->redirect(array('controller' => 'products', 'action' => 'view', $this->request->data['Review']['product_id'], '#' => 'reviews'));
    }
}

Somehow this horrible code works.. in part. Review saves, but I don't get validation errors, and I can't add

'if ($this->Review->save($this->request->data);) {
    //...
}

because it will break this action (missed view error).

My question is how to properly deal with this situation to achieve functionality that I need? Should I use elements with request action or I should move adding reviews to the ProductsController?

© Stack Overflow or respective owner

Related posts about cakephp

Related posts about formhelper