简体   繁体   中英

CakePHP Redirecting back to the same page

I have a Model for Groups and another model for Notes (Notes and Posts are same things).

NotesController:

   public function groupnotes()
   {

    if (!empty($this->data))
     {
        $data = $this->data;
       $data['Note']['user_id'] = $this->Auth->user('id');

        if ($this->Note->save($data))
           {
             PROBLEM HERE
           } 
      }


   if(empty($this->data['Note']['notes']))
      {
        PROBLEM HERE
      } 

GroupsController: (ViewCourse is used to view each group )

public function viewcourse($id=NULL)
 {
    $this->set('viewcourse', $this->Group->read(NULL,$id));
    $this->set('course', $this->Group->find('all', array('conditions'=>array('Group.id'=>$id))));

}

Now when i create a post in a group it redirects me to "groupnotes" action and i want it to redirect me to viewcourse/id ... I am a bit confused how can i redirect the page to viewcourse/id ...

I tried doing it by adding this to groupnotes action

 $this->redirect(array('controller'=>'groups',  'action' => 'viewcourse'));

but here i do not have the id.

What do you suggest?

This question might help you: What is the equivalent to getLastInsertId() in Cakephp?

$this->redirect(array(
           'controller'=>'groups',  
           'action' => 'viewcourse/'.$this->Group->getLastInsertId())
            );

EDIT: I have only suggested that you go to the last inserted id of a group as a suggestion. Your question is a bit vague when you say "but here i do not have the id." 1. are you looking to go to any valid course id? 2. last entered course? 3. first entered course id?

Alternatively you could set a default course in your controller like so...

public function viewcourse($id=NULL)
 {
    if(!$id){
         $id = $this->Group->find('first');
         $id = $id['Group']['id'];
    } 
    $this->set('viewcourse', $this->Group->read(NULL,$id));
    $this->set('course', $this->Group->find('all', array('conditions'=>array('Group.id'=>$id))));

}

NOTE: Just a tip,

 $this->set('course', $this->Group->find('all', array('conditions'=>array('Group.id'=>$id))));

Can be substituted with

 $this->set('course', $this->Group->findById($id));

To make your code a bit leaner

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM