未定义的变量:声明

时间:2013-07-18 14:21:02

标签: cakephp-2.3

这是我的控制器代码

<?php
public function view(){
        $this->loadModel('User');
        $this->loadModel('Claim');
        $this->Claim->unbindModel(
            array('belongsTo' => array('User',"Category"),
                'hasMany' => array('Response')));
        $user= $this->User->findById($this->params['id']);
        $claim=$this->Claim->find('all', array(
                        'conditions' => array('user_id' => $user['User']['id']),
                        'fields' => array('title','id','support_count','oppose_count','description','category_id')));

        if(isset($user['User'])):
        $this->set('User',$user);
        else:
        $this->Session->setFlash('User Not Found!', 'flash',array('alert'=>'error'));
        $this->redirect('/');
        endif;

    }?>

这是我的型号代码

class User extends AppModel {

    public $name = 'User';

    public $validate = array(
        'handle' => array(
            'alphaNumeric' => array(
                'rule' => 'alphaNumeric',
                'required' => true,
                'message' => 'Invalid Username'
            ),
            'between' => array(
                'rule' => array('between', 5, 15),
                'message' => 'Username should be between 5 to 15 characters'
            )),
        'password' => array(
            'rule' => array('between', 5, 15),
            'message' => 'Password should be between 5 to 15 characters',
            'last' => true,
            'required' => true
        ),
        'email' => array(
            'email' => array(
                'rule' => 'email',
                'required' => true,
                'message' => 'Enter valid email address'
            )
        )
    ); }

这是查看代码

<?php echo $this->Html->link($Claim['Claim']['title'], 
            array('Controller'=>'User','action'=>'view')); ?>

我收到此错误“未定义的变量:声明[APP / View / User / view.ctp,第6行]” 我试图在模型中将“声明”定义为public $ name ='Claim';但它没有用,我试图将它定义为$ this-&gt; set($ claim('Claim'));但我仍然得到同样的错误...我需要一些帮助,任何人都可以帮助我吗

1 个答案:

答案 0 :(得分:0)

如Nunser所说,您需要在视图中设置变量$ Claim,在控制器中使用$ this-&gt; set(&#39; Claim&#39;,$ claim)。模型从数据库中获取数据。然后将其传递给Controller,您可以通过$ this-&gt; MODELNAME-&gt; METHOD访问它。这里处理数据。最终,Controller(而不是Model)将其传递给视图。所以你需要在Controller中设置它。

另外:如果您要遵循CakePHP约定(实际上,它都是关于约定的),您将不需要在第3行和第4行中使用loadModel。也许还要看看CakePHP关系。 看看这个:http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html在Cake中有一个简短的MVC解释,这个:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html用于介绍关系。