2013-01-04 46 views
2

我有两个模型商业和用户。他们与HABTM关系有关。如何在CakePHP中将两个HABTM保存为一种形式?

一切正在与烘焙的控制器,模型和视图。

现在我试图在一种形式中结合这两种模式,以便用户可以输入一个企业名称与用户信息。

这里的形式:



    Form->create('User'); ?> 
    
    
    Form->input('Business.name', array('label' => __('Business name'))); 
    echo $this->Form->input('User.email'); 
    echo $this->Form->input('User.firstname'); 
    echo $this->Form->input('User.lastname'); 
    echo $this->Form->input('User.password'); 
    echo $this->Form->input('User.phone_cell', array('type' => 'text')); 
    echo $this->Form->input('User.phone_home', array('type' => 'text')); 
    echo $this->Form->input('User.phone_work', array('type' => 'text')); 
    ?> 
    
    Form->end(__('Submit')); ?> 
    

的唯一途径,我能够让它的工作是先保存用户,然后获取用户ID,并通过添加用户数组新后保存业务ID。



    if ($this->User->save($this->request->data)) { 
     $this->request->data['User'] = array('User' => array(0 => $this->User->id)); 
    if ($this->User->Business->save($this->request->data)) { 
     // User saved 
    } else { 
     // User not saved 
    } 
    } else { 
     $this->Session->setFlash(__('The user could not be saved. Please, try again.')); 
    } 

我试着saveAll方法没有成功。是否可以优化这个CakePHP的方式来保存一次?

感谢

回答

0

我能得到它的名为UserGroup情侣款工作的自己。下面是我的一些代码剪以示我是如何做的:

UsersController.php

public function edit($id = null) 
{ 
    $this->User->id = $id; 

    if ($this->request->is('get')) { 
     //On page load load the user data 
     $this->request->data = $this->User->read(); 
    } else { 
     //Saving 
     if ($this->User->save($this->data)) { 
      //....snipped... 
     } else { 
      $this->Session->setFlash('Unable to update the user.'); 
     } 
    } 

    //Build $groups array for form 
    // Only admins can assign admin rights 
    if ($this->isMember('Admin')) { 
     $this->set('groups',$this->User->Group->find('list')); 
    } else { 
     $this->set('groups',$this->User->Group->find('list',array(
      'conditions' => array(
       'Group.name !=' => 'Admin' 
      ) 
     ))); 
    } 
    //...more snipping... 
} 

edit.ctp(查看)

echo $this->Form->create('User', array('action' => 'edit')); 
    echo $this->Form->input('User.username'); 
    echo $this->Form->input('Group',array(
      'type' => 'select', 
      'multiple' => true, 
      'label' => "Group (Select multiple entries with CTRL)", 
      'size' => count($groups) 
     ) 
    ); 
    //More snipping 

与实例,从工作,你怎么样验证输入的Business.name是否有效并且可以与HABTM关系匹配?在这种情况下,Mine强制选择列表。我的模型非常简单,所以我没有包含它。

你的输出是debug($this->data);还是debug($this->request->data)

+0

您有用户ID来关联组。用你的例子,我想同时添加一个新用户和新组。 – user1949419

+0

我使用'$ this-> User-> Business-> invalidFields();验证了Business.name;'' – user1949419