我是 cakephp 的新手。我有一个“用户”表和一个“类别”表
user belongsTo category (fields: users.id, users.name, users.category) category hasMany users (fields: category.id, category.name, users.category)
我正在处理这样的关联数据。
在(用户)edit.ctp 我把
// view/Users/edit.ctp
echo $this->Form->input('name');
echo $this->Form->input('categories', array( 'value' => $this->Form->value('User.category'),
'name'=>'data[User][category]') );
</pre>
in users controller I have
<pre>
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
$sexes = $this->User->Sex->find('list');
$categories = $this->User->Category->find('list');
$this->set(compact('categories'));
}
一切正常,但我怀疑有一种更简单的方法可以完成该表格。这真的需要吗?
, array( 'value' => $this->Form->value('User.category'), 'name'=>'data[User][category]')
没有这些参数,选择框不会高亮选中选项,并没有保存任何内容。
可能是这样的
echo $this->Form->input('Category.name');
例如?但是这样的代码不会显示选择框。
而且它不保存 users.category 字段。
我无法找到任何带有示例的教程或代码。链接将不胜感激。