I’m learning Yii and MVC and building my first app to teach myself.
I have a DB table called "projects", it lists all the projects by name and some can have a logo attached to them.
when i’m displaying the projects, i need to check:
1- if they have a logo attached
2- if so, display the logo
3- if not, display a default image.
I’m a little unsure how to go about this, i’ve achieved it by using the “view” but i’m not happy with having the logic for this in there. Can someone point me in the right direction.
I currently have this for my controller
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Projects', array(
'criteria'=>array(
'condition'=>'deleted=0',
'order'=>' created_on DESC',
),)
);
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
class Projects extends CActiveRecord
{
// ...
public function getLogosPath()
{
// returns the path to all logos
}
public function getLogosUrl()
{
// returns the url of logos directory
}
public function getLogoFileName()
{
return 'th_'.CHtml::encode($this->logo_file);
}
public function getLogoExists()
{
return is_file($this->getLogosPath().'/'.$this->getLogoFileName());
}
public function getLogoUrl()
{
return $this->getLogosUrl().'/'.($this->getLogoExists() ? $this->getLogoFileName() : 'logo_50x50.gif');
}
public function getLogoPath()
{
return $this->getLogosPath().'/'.$this->getLogoFileName();
}
protected function afterDelete()
{
parent::afterDelete();
@unlink($this->getLogoPath());
}
}
// and in you view:
CHtml::link('<img width="60" height="60" src="'.$data->logoUrl.'" />', array('view', 'id'=>$data->id));
If you think there are too many functions to handle logos in your model, then you can merge some of them, but they can be useful separately in some situations.