cakephp编辑时获取字段(父键)的值

时间:2012-06-02 17:37:31

标签: cakephp redirect

在cakephp 2.1上,我使用此结构在保存时拦截数据:

$this->request->data['Setup']['active'] = 1;  

现在,在编辑了一条记录(Dir)之后,我希望通过这种方式获取父ID来重定向到它的父(project_id):

$ownParentId = $this->request->data['Dir']['project_id'];

但这并没有让任何价值传递到这里:

$this->redirect(array('controller' => 'projects', 'action' => 'edit', $ownParentId));

所以我的重定向失败了。

=============回复后==============
由于以下原因,似乎project_id根本没有旅行:

在我的dir编辑表格中,我评论道:

//echo $this->Form->input('project_id');

因为用户不应该更改项目ID。

我只是尝试取消注释该行,表单现在显示一个空的或空的选择控件,不发布任何内容。 我期待一个编辑控件,我可以以某种方式隐藏或禁用。

我的dirs表上的field project_id

CREATE TABLE IF NOT EXISTS `dirs` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `project_id` int(10) NOT NULL,
  ....  

与...相关联 我的项目表上的id字段:

CREATE TABLE IF NOT EXISTS `projects` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`pr_number` varchar(10) NOT NULL,
`client_id` int(5) NOT NULL,
`exec_id` int(5) NOT NULL,
 ....  

项目模型

var $hasMany = array('Daily', 'Dir');

dir模型

var $belongsTo = array('Project');

也许我只需要一个很好的find()结构来填充我的编辑表单上的project_id控件? - 或 -
在保存编辑之前获取project_id值? (projectt_id已经保存,因为是编辑。
我在http://carlosgarcia.us/support/DirsController.txt发布了完整的dirs控制器。

你能帮忙吗?非常感谢你。

卡洛斯

1 个答案:

答案 0 :(得分:1)

要在编辑或删除子记录后重定向,首先我获得了父ID(我的控制器上的编辑/删除方法)

     $ownParentId = $this->Dir->find
                    (
                    'first', array
                (
                // recursive 0 so no child tables travel, use 1 to retrieve ALL tables  
                'recursive' => 0,
                'fields' => array('Dir.project_id'),
                'conditions' => array('Dir.id' => $id)
                    )
    );

然后保存后重定向:

$this->redirect(array('controller' => 'projects', 'action' => 'edit', $ownParentId['Dir']['project_id']));

在添加孩子后重定向到父记录有点棘手 - 对我来说是假人 -

1.-从我看来,如果Add链接发送了一个名为parentProject的参数:

echo $this->Html->link(__('Add'), array('controller' => 'dirs', 'action' => 'add', 'parentProject' => $project['Project']['id']));  

2.-在我的子控制器中,将此参数设置为数组(添加方法):

$this->set('parentProject', $this->request->params['named']['parentProject']);

3.-保存之前,请设置我的子记录的字段值:

$this->request->data['Dir']['project_id'] = $this->request->params['named']['parentProject'];  

4.-保存后使用相同的值重定向:

$this->redirect(array('controller' => 'projects', 'action' => 'edit', $this->request->data['Dir']['project_id']));  

此外,通过这种方式,我可以在添加/编辑子项时从父模型中获取所需的所有数据:

   $ProjectData = $this->Dir->Project->find
                    (
                    'first', array
                (
                // recursive 0 so no child tables travel, use 1 to retrieve ALL tables  
                'recursive' => 0,
                'fields' => array('Project.name', 'Project.pr_e_start'),
                'conditions' => array('Project.id' => $this->request->params['named']['parentProject'])
                    )
    );

    $this->set(compact('ProjectData'));

很高兴它有效,并希望与像我一样的苦苦挣扎的初学者分享。

卡洛斯。