我是cakePHP的新手试图创建一个博客网站,其中用户在类别选择后添加博客,我有一个类别表:fields:category_id,name和posts table:fields:id,category_id,title,body。 我想将所有类别提取到下拉列表中。当用户添加新帖子时,他们必须先选择类别,然后他才能发布任何内容..
My PostsController:
<?php
class PostsController extends AppController{
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session','Paginator');
public function index(){
$this->Paginator->setting = array(
'limit' =>'10',
'order' => array('Post.id' =>'Desc')
/*'conditions' => array(
'Post.user_id' => AuthComponent::user(id)
)*/
);
$arrPosts = $this->Paginator->paginate('Post');
$this->set('posts', $arrPosts);
}
public function view($id = null){
if(!$id){
throw new NotFoundException(__("Error Processing Request ID"));
}
$post =$this->Post->findById($id);
if(!$post){
throw new NotFoundException(__("Error Processing Request POST"));
}
$this->set('post',$post);
}
public function add(){
// HERE I want to fetch all categoryies from categories table and want to send to view
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}
}
}
?>
我想以添加形式显示我的类别:
请帮帮我......
答案 0 :(得分:1)
在控制器操作中,您需要使用$this->set()
来设置View变量。只要您在Post模型中正确设置了关联,就可以使用: -
$this->set('categories', $this->Post->Category->find('list'));
Cake的FormHelper应该自动知道Post.category_id
表单字段想要成为选择输入$categories
作为选项。
还有一点,最好在处理表单后设置视图变量,因为如果它正确保存就不需要它们,因此可以将数据库查询的数量减少1。
如果您使用find('all')
检索类别,则需要将其转换为find('list')
使用的格式,这可以使用Hash::combine()
轻松完成: -
$categories = $this->Post->Category->find('all');
$this->set(
'categories',
Hash::combine($categories, '{n}.Category.id', '{n}.Category.name')
);
这样做的唯一真正价值在于你需要$categories
来做其他事情。
答案 1 :(得分:0)
public function add(){
/*Here get the category list & set the view (ctp file)*/
$this->set('categories', $this->Post->Category->find('list'));
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}
}
//设置ctp文件中的下拉列表 $ this-&gt;表单&gt;输入(&#39; category_id&#39;,数组(&#39;类型&#39; =&gt;&#39;选择&#39;,&#39;选项&#39; =&GT;&#39;分类&#39;));