CakePHP对同一控制器中非对象的成员函数create()的调用


CakePHP Call to a member function create() on a non-object in same Controller

好吧,这真的很奇怪,我有以下testrongign_up操作:

  public function test_sign_up(){
    if($this->request->is('post')){
        $signup_result = $this->request->data;
        $userData = array('User' => array(
            'username' =>$signup_result['User']['username'],
            'password'=> $signup_result['User']['password'],
            'group_id' => 2,
            'client_id' => 9999));
        $this->User->create();
    if ($this->User->saveAll($userData)) {
        $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.'));
    }
    }
}

现在,当我试图保存一个用户时,我得到:

 Call to a member function create() on a non-object 

请注意,此功能在我的UsersController

更新

如果我这样做:

$this->loadModel('User');

它工作起来没有问题,但当我已经在绑定到用户模型的控制器中时,这是必要的吗?

如果控制器中有$uses数组,则控制器将在实例化时将这些数组作为模型加载。例如:

<?php
class UsersController extends AppController {
    public $uses = array(
        'Client',
        'Website',
        'Category',
        'Type',
        'WebsiteIssue'
    );
}

在上文中,用户控制器将加载指定的五个模型。如果您希望用户模型也被实例化(默认情况下,如果没有指定$uses),那么只需将'User'添加到$uses数组中即可。

使用$this->Form->create()而不是$form->create()

必须在助手对象之前使用$this

您的index.php代码应该如下所示:

echo $this->Form->create("Contact");