编辑数据b / w cakephp中的两个模型

时间:2011-09-08 06:10:50

标签: cakephp models has-one

我有两个模型,一个是Login,另一个是Userdetail。我使用Login关系在两个模型中保存了模型hasone中的数据。

请告诉我如何编辑它们。

我在add.ctp文件中使用以下代码进行保存:

echo $form->create('Login', array('action'=>'add'));
    echo $form->input('first_name');
    echo $form->input('last_name');
    echo $form->input('email');
    echo $form->input('user_name');
    echo $form->input('password');
    echo $form->input('Userdetail.first_name');
    echo $form->input('Userdetail.last_name');
    echo $form->input('Userdetail.designation');
    echo $form->input('Userdetail.contact');
    echo $form->input('Userdetail.address');
    echo $form->end('Add');
and in controller i used : 
function add() 
    {
        if (!empty($this->data)) 
        {
            if ($this->Login->saveAll($this->data)) 
            {
                // User and Profile created successfully
                $this->Session->setFlash('Your post has been saved.');
                $this->redirect(array('action' => 'index'));
            } 
            else 
            {
                // Error creating user
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

您的edit.ctp:

<?php
echo $form->create('Login');
echo $form->input('id');
echo $form->input('first_name');
echo $form->input('last_name');
echo $form->input('email');
echo $form->input('user_name');
echo $form->input('password');
echo $form->input('Userdetail.id');//updated
echo $form->input('Userdetail.first_name');
echo $form->input('Userdetail.last_name');
echo $form->input('Userdetail.designation');
echo $form->input('Userdetail.contact');
echo $form->input('Userdetail.address');
echo $form->end('Submit');
?>

您在控制器中的编辑操作:

function edit($id = null)
{
$this->set('title_for_layout', __('Edit', true));

    if (!$id && empty($this->data)) {
        $this->Session->setFlash(__('Invalid ', true), 'default', array('class' => 'error'));
        $this->redirect(array('action'=>'index'));
    }
    if (!empty($this->data)) {
        if ($this->Login->save($this->data)) {
            $this->Userdetail->create();//updated code
            $this->Userdetail->id = $this->data['Userdetail']['id'];//updated code
          if ($this->Userdetail->save($this->data['Userdetail'])) {
            $this->Session->setFlash(__('Data has been saved', true), 'default', array('class' => 'success'));
            $this->redirect(array('action'=>'index'));
           }
        } else {
            $this->Session->setFlash(__('Data could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
        }
    }
    if (empty($this->data)) {
        $this->data = $this->Login->read(null, $id);
    }
   }

答案 1 :(得分:0)

如何编辑?与添加表单相同,登录为echo $form->input('id');,Userdetail为echo $form->input('Userdetail.id');