2011-05-09 74 views
0

我注意到他们有很多不同的方法来编辑数据库条目时传递一个ID到表单。因此,例如用于编辑用户配置文件的形式,我有以下代码:CakePHP通过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传入网址,例如: /users/edit/2但是,让我们说我希望它是更像用户友好的东西,例如/profile/edit(通过路由重写)我不再传递ID作为URL的一部分。正如你可以在我的代码中看到的,我有一条线我已经注释掉了,因为它不是必需的?

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

基本上这是更多的选项可用于我建立各种类型的编辑窗体和传递数据的形式。如果数据通过URL或其他方式传递,需要隐藏字段

我也注意到在一些网站上他们有类似于表单键和存储在用户名中的用户名页眉中的meta标签?

编辑:

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')); 
      } 
     } 
    } 
形式我还需要形状配合>输入

回答

2

另外( 'ID',数组 ( '类型'=> '隐藏')); ?>为什么?

具有id隐藏在形式消除了你的控制器动作抓取从URI(作为参数传递又名)的$id的需要。在表格中时,它将自动放入您的$data阵列中。

是什么形式需要的隐藏字段 如果数据被 通过URL或某些 其他方式通过任何

这是没有必要的形式,如果是从uri。您只需抓住$id并将其分配给用户模型(如注释掉的代码所做的那样)。

比方说,我想它是什么 更加用户友好喜欢/型材/编辑

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

+0

但是,如何传递此信息?即使我有隐藏字段,它也不会确认用户标识。请参阅OP了解我如何在网站上显示用户信息。 – Cameron 2011-05-09 21:50:16

+0

@Cameron:我编辑并添加了更多细节。 – webbiedave 2011-05-09 21:52:55