【发布时间】: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'));
}
}
}
【问题讨论】: