Yii Framework Forum: How To Access Relation Data In Any View - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How To Access Relation Data In Any View Rate Topic: -----

#1 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 07:01 AM

I've a relation like below.. how can i access this join relation data through out my site..using

Yii::app->user->organisations or Yii::app->benefitUses


the following is my relation and it is generated by gii..

this is my relation for User model.
public function relations()
	{
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	'benefitUses' => array(self::HAS_MANY, 'BenefitUse', 'user_id'),
	'organisations' => array(self::MANY_MANY, 'Organisation', 'user_organisation(user_id, organisation_id)'),				
			
	}


when i'm accessing like this
<?php var_dump(Yii::app()->user->benefitUses);die; ?>

from view it is showing error like "Property "CWebUser.benefitUses" is not defined."[/code]

And

when i'm accessing like this
<?php var_dump($this->user->benefitUses);die; ?>

from view it is showing error like "Property "UserController.user" is not defined."[/code]

how to get the user instance here rather than CWebUser or UserController?? and how can i access the joining data all over site with
Yii::app->user->organisations or Yii::app->benefitUses


Any help pls..

Many Thanks,
0

#2 User is offline   Keith 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,600
  • Joined: 04-March 10
  • Location:UK

Posted 31 January 2013 - 07:16 AM

Personally, I'd extend CWebUser, like so:
<?php

class WebUser extends CWebUser
{
    private $_model;

    public function getModel()
    {
        if ($this->_model === null)
            $this->_model = User::model()->findByPk($this->id);

        return $this->_model;
    }
}


With updated config:
    'user'=>array(
        'class'=>'WebUser',
        ....
    ),


Then you can access any of your user relations:
Yii::app()->user->model->benefitUses;


It uses lazy loading of the user record, so it will only hit the database if you access the model, and will store it for the remainder of the request.

EDIT:
There's actually a pretty good wiki article here which does a very similar thing.
1

#3 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 07:20 AM

thank you very much for your reply keith.

i'm getting this error as you suggested..but i'm getting this error..

Trying to get property of non-object 

with following code
<?php Yii::app()->user->model->benefitUses;?>


but my User model is extending CActiveRecord like this..
*/
class User extends CActiveRecord
{

....
....
}
0

#4 User is offline   Keith 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,600
  • Joined: 04-March 10
  • Location:UK

Posted 31 January 2013 - 09:35 AM

Can you post the full stack trace and error message?
0

#5 User is offline   Imre 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 30-March 11

Posted 31 January 2013 - 10:20 AM

View Postdeveloper!, on 31 January 2013 - 07:20 AM, said:

Trying to get property of non-object 



Most probably the model returned is null.
I'd guess you are probably not logged in or you have not properly set up the id of WebUser.

$user = Yii::app()->user->model;
if($user == null) throw new CException('User not defined');

// use
CVarDumper::dump($user->benefitUses, 10, true);


It is important to note that Yii::app()->user is a WebUser that is not User (your model class)
0

#6 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 11:22 AM

this is what i'm getting

PHP notice

Trying to get property of non-object

/Applications/MAMP/htdocs/webapp/protected/models/User.php(99)

087         // class name for the relations automatically generated below.
088         return array(
089             'benefitUses' => array(self::HAS_MANY, 'BenefitUse', 'user_id'),
090              'organisations' => array(self::MANY_MANY, 'Organisation', 'user_organisation(user_id, organisation_id)'),                               
091         );
097     }
098     public function searchNames(){
099         var_dump(Yii::app()->user->model->benefitUses);die;
100         var_dump(Yii::app()->user->benefit);echo "ding";die;
101         return $this->benefit;
102     }
103     /**
104      * @return array customized attribute labels (name=>label)
105      */
106     public function attributeLabels()
107     {
108         return array(
109             'id' => 'ID',
110           
Stack Trace
#0	
–  /Applications/MAMP/htdocs/webapp/protected/controllers/UserController.php(200): User->searchNames()
195     /**
196      * Lists all models.
197      */
198     public function actionIndex()
199     {
200         $models = User::model()->searchNames();var_dump($models);die;
201         $dataProvider=new CActiveDataProvider('User');
202         $this->render('index',array(
203             'dataProvider'=>$dataProvider,
204         ));
205     }
#1	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/actions/CInlineAction.php(50): UserController->actionIndex()
#2	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(309): CInlineAction->runWithParams(array("r" => "user"))
#3	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CFilterChain.php(134): CController->runAction(CInlineAction)
#4	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CFilter.php(41): CFilterChain->run()
#5	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(1146): CFilter->filter(CFilterChain)
#6	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CInlineFilter.php(59): CController->filterAccessControl(CFilterChain)
#7	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CFilterChain.php(131): CInlineFilter->filter(CFilterChain)
#8	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(292): CFilterChain->run()
#9	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(266): CController->runActionWithFilters(CInlineAction, array("accessControl"))
#10	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/CWebApplication.php(283): CController->run("")
#11	
+  /Applications/MAMP/htdocs/framework-1.1.12/web/CWebApplication.php(142): CWebApplication->runController("user")
#12	
+  /Applications/MAMP/htdocs/framework-1.1.12/base/CApplication.php(162): CWebApplication->processRequest()
#13	
–  /Applications/MAMP/htdocs/webapp/index.php(19): CApplication->run()
14 
15 // remove the following line when in production mode
16 defined('YII_DEBUG') or define('YII_DEBUG',true);
17 
18 require_once($yii);
19 Yii::createWebApplication($config)->run();
20 
21 
22 
2013-01-31 17:19:19 Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/0.9.8r DAV/2 PHP/5.4.4 Yii Framework/1.1.12

0

#7 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 11:26 AM

View PostImre, on 31 January 2013 - 10:20 AM, said:

Most probably the model returned is null.
I'd guess you are probably not logged in or you have not properly set up the id of WebUser.

$user = Yii::app()->user->model;
if($user == null) throw new CException('User not defined');

// use
CVarDumper::dump($user->benefitUses, 10, true);


It is important to note that Yii::app()->user is a WebUser that is not User (your model class)



I'm logged in, I've set it u the user id and i'm getting my user id with

	echo Yii::app()->user->id;

0

#8 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 11:34 AM

CVarDumper::dump(Yii::app()->user->benefitUses, 10, true);


this line is saying
Property "WebUser.benefitUses" is not defined.



CVarDumper::dump(Yii::app()->user, 10, true);


this line is showing
WebUser#1
(
    [model] => null
    [WebUser:_model] => null
    [allowAutoLogin] => true
    [guestName] => 'Guest'
    [loginUrl] => array
    (
        0 => '/site/login'
    )
    [identityCookie] => null
    [authTimeout] => null
    [autoRenewCookie] => false
    [autoUpdateFlash] => true
    [loginRequiredAjaxResponse] => null
    [CWebUser:_keyPrefix] => '00993cbdf63e0aad232dsee020c25071'
    [CWebUser:_access] => array()
    [behaviors] => array()
    [CApplicationComponent:_initialized] => true
    [CComponent:_e] => null
    [CComponent:_m] => null
)

0

#9 User is offline   Keith 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,600
  • Joined: 04-March 10
  • Location:UK

Posted 31 January 2013 - 11:50 AM

The var dumper should be accessing Yii::app()->user->model->benefitUses;
0

#10 User is offline   Imre 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 30-March 11

Posted 31 January 2013 - 11:53 AM

what about:
CVarDumper::dump(Yii::app()->user->model, 10, true);

0

#11 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 11:56 AM

View PostImre, on 31 January 2013 - 11:53 AM, said:

what about:
CVarDumper::dump(Yii::app()->user->model, 10, true);



null
0

#12 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 11:58 AM

View PostKeith, on 31 January 2013 - 11:50 AM, said:

The var dumper should be accessing Yii::app()->user->model->benefitUses;



getting error with

CVarDumper::dump(Yii::app()->user->model->benefitUses);

Trying to get property of non-object
0

#13 User is offline   seenivasan 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 620
  • Joined: 17-June 12
  • Location:Chennai,TamilNadu,India.

Posted 31 January 2013 - 12:07 PM

Dear Friend

I hope following will solve the issue.
Add a line in your LoginForm::login

public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
                            $this->_identity->setState('model',User::model()->findByAttributes(array('id'=>$this->_identity->id)));//this is the added line.
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}


It assumes that you have set primarykey of user as property id of UserIdendity in components folder.

Regards.
0

#14 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 12:13 PM

View Postseenivasan, on 31 January 2013 - 12:07 PM, said:

Dear Friend

I hope following will solve the issue.
Add a line in your LoginForm::login

public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
                            $this->_identity->setState('model',User::model()->findByAttributes(array('id'=>$this->_identity->id)));//this is the added line.
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}


It assumes that you have set primarykey of user as property id of UserIdendity in components folder.

Regards.



thanks for your reply seenivasan.. i tried it but there is no change in the problem..
0

#15 User is offline   seenivasan 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 620
  • Joined: 17-June 12
  • Location:Chennai,TamilNadu,India.

Posted 31 January 2013 - 12:17 PM

Dear Friend

That is finely working in my local host.

Try to use CWebUser rather than your derived class WebUser.

LoginForm::login

public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
                            $this->_identity->setState('model',User::model()->findByPk($this->_identity->id));//this is the added line.
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}



UserIdendity.php

public function getId()
	{
		$user=User::model()->findByAttributes(array('username'=>$this->username,'password'=>$this->password));
		return $user->id;
	}


In a view

if(!Yii::app()->user->getIsGuest())
	echo Yii::app()->user->model->username;



Cheers.
0

#16 User is offline   FrankW 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 07-December 12

Posted 31 January 2013 - 12:27 PM

View Postdeveloper!, on 31 January 2013 - 11:58 AM, said:

getting error with

CVarDumper::dump(Yii::app()->user->model->benefitUses);

Trying to get property of non-object


Your WebUser class does not have the 'benefitUses' property/method, your User model does. You need to provide that method in WebUser similar to:
public function getBenefitUses() {
    $user = User::model()->with('benefitUses')->findByPk($this->id);
    if ($user) {
        return $user->benefitUses;
    } 

    return array();

}


Then you can use Yii::app()->user->benefitUses to get your array.

Does your getId() method in WebUser return the primary key of the user table? If that is not the case then that is the reason your User model would return a null. I added the 'with' since you expect to grab that relation anyways, you may as well have the model do a proper join for a single DB call instead of several.

I hope this helps!
1

#17 User is offline   developer! 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 110
  • Joined: 28-November 12

Posted 31 January 2013 - 01:25 PM

great thanks FrankW. Its now working with your idea :)


Thanks a ton :)
0

#18 User is offline   FrankW 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 07-December 12

Posted 31 January 2013 - 01:47 PM

View Postdeveloper!, on 31 January 2013 - 01:25 PM, said:

great thanks FrankW. Its now working with your idea :)


Thanks a ton :)


You are very welcome! I am watching this thread, so if you come across a related issue, maybe I can help. I'm far from a Yii master, but the community here is great.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users