2014-02-06 138 views
1

學生HasMany支付和支付屬於學生。在創建付款時,我必須指明我爲此付款創建的學生。我希望能夠在創建付款時訪問學生的ID,以便操作add()方法中的某些內容。訪問控制器方法變量CAKEPHP

我在我的控制器中有一個add()方法。這是add()的當前代碼。

public function add() {  
    if ($this->request->is('post')) { 
     $this->Payment->create(); 
     if ($this->Payment->save($this->request->data)) { 
      $this->Session->setFlash(__('The payment has been saved.')); 
      return $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The payment could not be saved. Please, try again.')); 
     } 
    } 
    $students = $this->Payment->Student->find('list'); 
    $this->set(compact('students')); 
} 

付款形式代碼

<?php echo $this->Form->create('Payment'); ?> 
<fieldset> 
    <legend><?php echo __('Add Payment'); ?></legend> 
<?php 
    echo $this->Form->input('student_id'); 
    echo $this->Form->input('date'); 
    echo $this->Form->input('total', array('default' => '0.0')); 
    echo $this->Form->input('notes'); 
?> 
</fieldset> 
<?php echo $this->Form->end(__('Submit')); ?> 
+0

您可以添加代碼,在視圖中的付款形式?如果你選擇的是這種形式的學生,那麼它應該包含在'$ this-> request-> data'中 –

回答

2

您應該能夠訪問ID爲

$this->request->data['Payment']['student_id'] 

因此,像這樣:

public function add() {  
    if ($this->request->is('post')) { 
     $this->Payment->create(); 
     $student_id = $this->request->data['Payment']['student_id']; 
     // Do something with student ID here... 
     if ($this->Payment->save($this->request->data)) { 
      $this->Session->setFlash(__('The payment has been saved.')); 
      return $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The payment could not be saved. Please, try again.')); 
     } 
    } 
    $students = $this->Payment->Student->find('list'); 
    $this->set(compact('students')); 
} 
+0

謝謝!很有幫助 –

1

一個策略,我找到導航CakePHP的大型多維數組非常有用的是在發展中經常使用的debug()功能。

例如,在add()方法我會做這樣的事情:

if ($this->request->is('post')) { 
    debug($this->request->data); 
    die; 
} 

然後你就可以看到該學生的ID被隱藏,並使用它,但是你在加之前需要( )方法結束。我不知道確切的結構的陣列將在,但最有可能,你應該能夠做這樣的事情:

$student_id = $this->request->data['Payment']['Student']['id']; 

只是檢查調試輸出()第(提交表單之後)確定數組中您要放置的數據在哪裏。

+0

謝謝!我一定會在將來使用它。現在得到它的工作 –