私は Cake PHP アプリケーションを構築しています。ユーザーごとに異なるプロパティがあるため、たとえば、2 つのオブジェクトを使用してユーザーを保存します。
- User hasOne Student / Student は User に属しています
- User hasOne Lecturer / 講師が User に所属
プロファイル編集ページでは、ユーザーは両方のオブジェクトのすべての詳細を編集できます。フォームを設定し、saveAll を使用したので、両方のオブジェクトを保存します。私の問題は、ユーザーの役割に応じてドロップダウン メニューを動的に設定することです。
たとえば、counties フィールドです。管理者には住所がありませんが、学生と講師には住所があります。国モデルをセットアップして、すべての郡を検索し、それらを選択ボックスの opt-group に入れました (動的なoptgroup を使用したドロップダウン リストに示すように、国ごとに並べ替えます) 。
$uses 変数を設定すると、Country モデルにアクセスできるようになるため、Students/LecturersController 内でこれをうまく行うことができます。すべてのユーザーロールがアドレスを持っているわけではなく、アドレスが User オブジェクト内に保存されることはないため、UsersController 内でこれを実行したくありません。モデルにコードを入れてみましたが、モデル内の他のモデルにアクセスする方法がわかりません。これまでのところ、アプリの作成に問題はありませんでしたが、どこかで間違った設計上の決定を下したか、何かが正しく理解されていない可能性があると感じています。
基本的に、以下の機能をどのように実装するかを尋ねてい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'));
}