试图为下拉列表传递列表但找不到变量

时间:2014-03-13 18:37:43

标签: php forms cakephp drop-down-menu

我是新手,我已经陷入了让我在过去一天陷入困境的僵局

我有3个表帖子,类别和具有1-many关系的用户,其中一个类别可以有很多帖子。

类别表只有两个字段:idcat_descid被设置为主键

在我的postscontroller中我有一个添加功能

public function add() {
    if ($this->request->is('post')) {

        $data = $this->Post->Cat->find('list', ['fields' => array('cat_desc')]);
        $this->set('cats', $data);

        $this->request->data['Post']['user_id'] = $this->Auth->user('id');

          if ($this->Post->save($this->request->data)) {
             $this->Session->setFlash(__('Your post has been saved.'));
             return $this->redirect(array('action' => 'index'));
           }
    }

    $this->set('title_for_layout',"'Add a Post");
    }

在我的视图中,我尝试调用下拉列表

      echo $this->form->create('Post', array('action'=>'add'));
      echo $this->form->input('title');

      echo $this->Form->input('category', array('options' => array('options'=> $cats))
      );

      echo $this->form->input('amount');
      echo $this->form->input('body');
      echo $this->form->end(__('Create a Post', true)); 

我得到一个未定义的变量猫。任何帮助将不胜感激,我感谢你们所有的帖子,因为它帮助我达到了这一点:)

2 个答案:

答案 0 :(得分:2)

首次导航到该页面时,请求类型将为" get"。代码的方式是,只有在请求类型为" post" (所以它只会在你提交表单时定义。)只需将设置$ cats的代码移到if语句if($this->request->is('post'))

之外。

答案 1 :(得分:0)

//controller
    public function add() {
        if ($this->request->is('post')) {

            $this->request->data['Post']['user_id'] = $this->Auth->user('id');

              if ($this->Post->save($this->request->data)) {
                 $this->Session->setFlash(__('Your post has been saved.'));
                 return $this->redirect(array('action' => 'index'));
               }
        } else {

        $cats = $this->Post->Cat->find('list', ['fields' => array('cat_desc')]);
        $this->set('cats', $cats);
        $this->set('title_for_layout',"'Add a Post");
         }
        }

//视图

 echo $this->Form->input('cat_id', $cats, array(options here));