【问题标题】:CakePHP passing id to edit formCakePHP 传递 id 来编辑表单
【发布时间】:2011-05-09 21:34:48
【问题描述】:

我注意到,在编辑数据库条目时,它们有许多不同的方式将 ID 传递给表单。例如,对于编辑用户个人资料表单,我有以下代码:

function edit($id = null)
{
    $this->layout = 'page';

    // this line isn't needed?
    //$this->User->id = $id;

    if (empty($this->data))
    {
        $this->data = $this->User->read();
    }
    else
    {
        if ($this->User->save($this->data))
        {
            $this->Session->setFlash('Your profile has been updated', 'flash', array('header' => 'Announcement', 'myclass' => 'success'));
            $this->redirect(array('controller' => 'users', 'action' => 'view', $id));
        }
    }
}

现在函数需要一个 id 传入 url,例如/users/edit/2 但是假设我希望它像/profile/edit 一样对用户更友好(通过路由重写),我将不再将 ID 作为 url 的一部分传递。正如您在我的代码中看到的那样,我有一行因为不需要而被注释掉了?

我也需要<?php echo $this->Form->input('id', array('type' => 'hidden')); ?>,为什么?

基本上,这更多的是我可以用来构建各种类型的编辑表单并将数据传递给表单的选项。如果数据是通过 URL 或其他方式传递的,那么表单中的隐藏字段需要什么

我还注意到在一些网站上,他们有表单键和存储在页眉元标记中的用户名之类的东西???

编辑:

public function beforeFilter()
{

        $this->set('authUser', $this->Auth->user());

        //

        $user = $this->Auth->user();

        if (!empty($user))
        {
            Configure::write('User', $user[$this->Auth->getModel()->alias]);
        }

}

public function beforeRender()
{
    $user = $this->Auth->user();

    if (!empty($user))
    {
        $user = $user[$this->Auth->getModel()->alias];
    }
    $this->set(compact('user'));
}


// NEW VERSION
function settings()
    {
        $this->layout = 'page';

        $this->set('title_for_layout', 'Edit Profile');

        $this->User->id = $user['id'];

        if (empty($this->data))
        {
            $this->data = $this->User->read();
        }
        else
        {
            if ($this->User->save($this->data))
            {
                $this->Session->setFlash('Your settings have been updated', 'flash', array('myclass' => 'success'));
                $this->redirect(array('controller' => 'users', 'action' => 'settings'));
            }
        }
    }

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    我也需要 Form->input('id', 数组('类型' => '隐藏')); ?> 为什么?

    id 隐藏在表单中消除了控制器操作从uri 中获取$id 的需要(又名作为参数传递)。在表单中时,它会自动放入您的$data 数组中。

    隐藏字段需要什么 在表格中,如果数据正在 通过 URL 或某些 其他方式

    如果它可以从 uri 中获得,则在表单中不需要它。您只需获取 $id 并将其分配给 User 模型(就像注释掉的代码一样)。

    假设我希望它成为某种东西 对用户更友好,例如 /profile/edit

    我认为那是用户编辑自己的个人资料的时候。在这种情况下,您的系统应该能够通过会话检索用户的 ID。

    【讨论】:

    • 但是我该如何传递这些信息呢?即使我有隐藏字段,它也不承认用户 ID。请参阅 OP,了解我如何在整个网站上显示用户信息。
    猜你喜欢
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多