我正在构建一个Cake PHP应用程序。不同的用户有不同的属性所以我使用两个对象来存储一个用户例如
- 用户有一个学生/学生属于用户
- 用户有一个讲师/讲师属于用户
配置文件编辑页面将允许用户编辑两个对象的所有详细信息。我已经设置了表单并使用saveAll保存两个对象。我的问题是根据用户的角色动态地填充下拉菜单。
例如,counties字段。管理员没有地址,而学生和讲师有。我已经设置了我的国家模型来查找我所有的国家,并将它们放入选择框中的选项组中(按国家排序,如图所示)
我可以在Students/LecturersController中做到这一点,因为它们允许我在设置$uses变量时访问Country模型。我不想在UsersController中这样做,因为不是所有的用户角色都有一个地址,地址永远不会存储在user对象中。我试着把代码放在模型中,但后来我不知道如何访问模型内的其他模型。到目前为止,我还没有遇到任何问题,我觉得我可能在某个地方做了一个糟糕的设计决定,或者我没有正确理解。
本质上我是在问我如何实现下面的setForForm()
函数。
public function edit() {
//get user
$user = $this->Auth->user();
//get role
$role = $user['User']['role'];
if ($this->request->is('post') || $this->request->is('put')) {
//get IDs
$userID = $user['User']['id'];
$roleID = $user[$role]['id'];
//set IDs
$this->request->data[$role]['user_id'] = $userID;
$this->request->data[$role]['id'] = $roleID;
$this->request->data['User']['id'] = $userID;
//delete data for role that is not theirs
foreach ($this->request->data as $key => $value) {
if($key !== 'User' && $key !== $role) {
unset($this->request->data[$key]);
}
}
if ($this->User->saveAll($this->request->data)) {
//update logged in user
$this->Auth->login($this->User->$role->findByUserId($userID));
$this->Session->setFlash('Changes saved successfully.');
} else {
$this->Session->setFlash(__('Please try again.'));
}
}
//set role for easy access
$this->set(compact('role'));
//sets required variables for role form
$this->User->$role->setForForm();
//fills in form on first request
if (!$this->request->data) {
$this->request->data = $user;
}
//render form depending on role
$this->render(strtolower('edit_' . $role));
}
//this is the method I would like to implement in the Student/Lecturer model somehow
public function setForForm() {
$counties = $this->Country->getCountiesByCountry();
$homeCounties = $counties;
$termCounties = $counties;
$this->set(compact('homeCounties', 'termCounties'));
}
我不确定你的问题是否正确,但我认为你想要的是:
User hasOne Student / Student belongs to User
和
Student hasOne Country / Country belongsTo Student
(讲座也是一样)
那么从你的UsersController你可以做:
$this->User->Student->Country->findCountiesByCountry();
希望对你有帮助
——编辑:
如果你想使用$role而不是Student/Lecturer,你必须这样做:
$this->User->{$role}->Country->findCountiesByCountry();
最后我决定只在用户控制器中加载县,不管表单是否需要它们,因为Admin是唯一不需要它们的用户。
试试这样:
public function setForForm() {
App::import('model', 'Country');
$Country = New Country();
$counties = $Country->getCountiesByCountry();
$homeCounties = $counties;
$termCounties = $counties;
$this->set(compact('homeCounties', 'termCounties'));
}
我不知道这是不是最好的解决方案,但至少它是有效的:)
编辑这是另一个错误。不建议从模型到视图设置变量,你可以返回数据,然后在编辑函数中设置,通常设置为视图,但无论如何,如果你需要从模型到视图设置,你可以使用App::import();
加载控制器类到你的模型,并使用set函数。