【问题标题】:Accessing variable in controller method CAKEPHP在控制器方法 CAKEPHP 中访问变量
【发布时间】:2014-02-06 04:13:53
【问题描述】:

学生有许多付款和付款属于学生。创建付款时,我必须指出我正在为哪个学生创建此付款。我希望能够在创建付款时访问学生的 id,以便在 add() 方法中操作某些内容。

我的控制器中有一个 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')); ?>

【问题讨论】:

  • 您可以在视图中添加支付表单的代码吗?如果您以该形式选择学生,则应将其包含在$this-&gt;request-&gt;data

标签: cakephp


【解决方案1】:

您应该能够以身份访问 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'));
}

【讨论】:

    【解决方案2】:

    我发现对于导航 CakePHP 的大型多维数组非常有用的一个策略是在开发中经常使用 debug() 函数。

    例如,在 add() 方法中,我会执行以下操作:

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

    然后,您将能够在 add() 方法完成之前查看该学生 ID 的隐藏位置并根据需要使用它。我不知道您的数组的确切结构,但很可能您应该能够执行以下操作:

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

    只需检查 debug() 的输出(在提交表单之后)以确定您想要的数据在数组中的位置。

    【讨论】:

    • 谢谢!我一定会在未来使用它。现在开始工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2013-01-11
    • 2023-03-10
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多