2014-02-06 135 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

谢谢!我一定会在将来使用它。现在得到它的工作 –