Reputation: 1
I am trying to show an image of each trainer when viewed. The images of trainers are taken from a form and are stored in the database. Now I want to extract images. Please help Me. Adding the code for more clarity.I am not sure whether I am following the right code for the same.
This is my the code I have added in view:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'name',
'email:email',
'phone',
'age',
'gender',
'experience',
'training_category',
'expectation',
'professional_certificate',
'special_clients',
'time_zones',
'certificates',
'document',
'id',
'timestamp',
'status',
[
'attribute'=>'photo',
'value'=>yii::getAlias('@trainerImgUrl') . '/' .$model->photo,
// 'value'=>Yii::getAlias('@web').'/'.$model->photo,
'format'=>['image',['width'=>'100','height'=>'100']]
]
],
]) ?>
This is the model code:
public function rules()
{
return [
[['name', 'email', 'phone', 'age', 'gender', 'experience', 'training_category', 'expectation', 'professional_certificate', 'special_clients', 'time_zones', 'certificates', 'photo', 'document', 'status'], 'required'],
[['phone'], 'integer'],
[['timestamp'], 'safe'],
[['photo'],'file'],
[['name', 'email', 'age', 'gender', 'experience', 'training_category', 'expectation', 'professional_certificate', 'special_clients', 'time_zones', 'status'], 'string', 'max' => 20],
[['certificates', 'photo', 'document'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'name' => 'Name',
'email' => 'Email',
'phone' => 'Phone',
'age' => 'Age',
'gender' => 'Gender',
'experience' => 'Experience',
'training_category' => 'Training Category',
'expectation' => 'Expectation',
'professional_certificate' => 'Professional Certificate',
'special_clients' => 'Special Clients',
'time_zones' => 'Time Zones',
'certificates' => 'Certificates',
'photo' => 'Photo',
'document' => 'Document',
Controller code:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new JoinUs model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new JoinUs();
if ($model->load(Yii::$app->request->post()) ) {
$model->save();
$trainerId= $model->id;
$image= UploadedFile::getInstance($model,'photo');
$imgName='tra_' .$trainerId. '.' .$image->getExtension();
$image->saveAs(yii::getAlias('@trainerImgPath') . '/' .$imgName);
$model->photo = $imgName ;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
Upvotes: -1
Views: 116
Reputation: 577
You can render it like that:
[
'attribute'=>'photo',
'value'=> function($model){
return Html::img(yii::getAlias('@trainerImgUrl') . '/' .$model->photo, ['alt' => 'my photo', ....// other image attributes//]); //check if your image url is correct
}
'format'=>'raw'
]
Upvotes: 0