2010-10-30 77 views
1

後,我有一個用戶控制器,在那裏,如果我增加一個用戶我想根據用戶選擇上,他的賬戶重定向條件,保存記錄

形勢的用戶類型來重定向:

用戶表

ID

usertype_id

用戶添加表單具有用戶類型的選擇框,如果用戶選擇教師,我有兩種類型的用戶:教師和學生(每個表格,模型,控制器),我想重定向到/ teachers/add/$ id如果用戶選擇學生,我想重定向到:/學生/添加/ $ ID

這是我有個大氣壓,但並不明顯工作

<?php 
class UsersController extends AppController { 
    var $name = 'Users'; 

    function add() { 
    if (!empty($this->data)) { 
     $this->User->create(); 
     if ($this->User->save($this->data)) { 
      $id = $this->User->id; 
      if ($this->User->usertype_id=='1') 
      { 
       $this->redirect(array('students/add/'.$id)); 
      } elseif ($this->User->usertype_id=='2') { 
       $this->redirect(array('teachers/add/'.$id)); 
      } else { 
       $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); 
      } 
     } else { 
      $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); 
     } 
    } 
    $usertypes = $this->User->Usertype->find('list'); 
    $this->set(compact('usertypes')); 
} 

} 
?> 

回答

2

我敢肯定問題是假設,因爲$this->User->id存在,$this->User->usertype_id也必須存在,它不。當我第一次開始使用CakePHP時,我遇到了這個問題。 :)

如果用戶類型是通過附加的形式傳遞,您需要檢查數據數組:

變化

if ($this->User->usertype_id=='1') 

if ($this->data['User']['usertype_id'] == '1') 

如果還是不行工作(我不記得$this->data成功保存後是否清空),那麼你應該在保存之前存儲該值,如下所示:

function add() { 
    if (!empty($this->data)) { 
     $usertype_id = $this->data['User']['usertype_id']; 
     $this->User->create(); 
     if ($this->User->save($this->data)) { 
      $id = $this->User->id; 
      if ($usertype_id == '1') { 
       $this->redirect(array('students/add/'.$id)); 
      } elseif ($usertype_id == '2') { 
       // the rest remains the same 

附錄
,而不是你的重定向使用連接,這看起來更清潔對我說:

$this->redirect(array('controller' => 'teachers', 'action' => 'add', $id)); 

但我想這只是偏好。

附錄2
我對清理你的控制器和所有邏輯移動到模型的一些其他建議。這樣您就可以在將來重新使用其他控制器的代碼,並且您的當前控制器將更易於閱讀。我會改變整個方法看起來像這樣:

// this is in /controllers/users_controller.php 
function add() { 
    if (!empty($this->data)) { 
     $saved_user = $this->User->save_user($this->data); 
     if ($saved_user['success']) { 
      $this->redirect(array(
       'controller' => $saved_user['controller'], 
       'action' => 'add', 
       $this->User->id 
      )); 
     } 
    } 
    $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); 
    $usertypes = $this->User->Usertype->find('list'); 
    $this->set(compact('usertypes')); 
} 

// this is in your model, /models/user.php 
function save_user($data) { 
    $this->create; 
    $usertype_id = $data['User']['usertype_id']; 
    return array(
     'controller' => ($usertype_id == '2') ? 'teachers': 'students'; 
     'success' => $this->save($data), 
    ); 
} 
+0

謝謝,只是你必須知道我猜。我想我搜索了121324種不同的東西來找到正確的方法來做到這一點,沒有任何結果。你讓我的一天:) – Weptunus 2010-10-30 14:07:46

+0

不客氣! – Stephen 2010-10-30 23:45:20