首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >控制器方法CAKEPHP中的变量访问

控制器方法CAKEPHP中的变量访问
EN

Stack Overflow用户
提问于 2014-02-06 04:13:53
回答 2查看 395关注 0票数 1

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

我的控制器中有一个add()方法。下面是add()的当前代码。

代码语言:javascript
运行
复制
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'));
}

付款形式代码

代码语言:javascript
运行
复制
<?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')); ?>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-06 04:43:42

您应该能够访问ID,如

代码语言:javascript
运行
复制
$this->request->data['Payment']['student_id']

所以就像这样:

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2014-02-06 04:40:11

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

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

代码语言:javascript
运行
复制
if ($this->request->is('post')) {
    debug($this->request->data);
    die;
}

然后,您将能够看到该学生id隐藏的位置,并在add()方法完成之前使用它。我不知道数组的确切结构,但最有可能的情况是,您应该能够这样做:

代码语言:javascript
运行
复制
$student_id = $this->request->data['Payment']['Student']['id'];

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21593859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档