f0rtis f0rtis - 7 months ago 11
PHP Question

How to use model attribute value in behavior config Yii

I want create

ImageBehavior
for uploading and saving images. My behavior have two fields:
imagePath
and
imageField
. In my model i'm wrote:

public function behaviors(){
return array(
'imageBehavior' => array(
'class' => 'ImageBehavior',
'imagePath' => 'images/avatar-pics/'.$this->user->username,
'imageField' => 'avatar',
),
);
}


but this doesn't worked - i receive path -


images/avatar-pics//image.png


What a solution? Create in behavior field
imageFolder
and add to config
'imageFolder' => 'user->username'
? Thanks.

Answer

Sorry for answering own question, but almost two years later build correct vision to this issue:

1) don't use line

'images/avatar-pics/'.$this->user->username

in your behavoir - it throws a notice "Trying to get property of non-object" - good application doesn't thows notices and warnings.

2) all you need is use

'images/avatar-pics/' . CHtml::value($this, 'user.username') 

instead. If $this->user is null, value method returns null, so be sure that you have related user to your model.

Comments