JKLM
JKLM

Reputation: 1520

Yii2: How to display Image in View using image path saved in database?

Trying to display image in view:

id_image holds image path in db.By using path need to display image. Tried with following code but it not showing any image.

<div class="row">
  <div class="col-xs-6 col-md-3">
    <a href="#" class="thumbnail">
      <img src="<?php $dataProvider->models[0]->id_image; ?>">
    </a>
  </div>

View:

public function actionView($id)
    {
         $searchModel = new CreateBookingsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

Create/Upload File in Controller

public function actionCreate()
    {
        $model = new CreateBookings();

        if ($model->load(Yii::$app->request->post()))
        {
            $imageName = $model->first_name;
            $mobile = $model->primary_mobile;
            $model->file = UploadedFile::getInstance($model, 'file');
            $model->file->saveAs( 'uploads/id_images/'.$imageName.'_'.$mobile.'.'.$model->file->extension);
            //save the path in the db column
            $model->id_image = 'uploads/id_images/'.$imageName.'_'.$mobile.'.'.$model->file->extension;

            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

Path Example saved in db:

uploads/id_images/kumar_9015879992.jpg

Upvotes: 1

Views: 17146

Answers (2)

joachim
joachim

Reputation: 1

You want to use first_name name before you save it into DB I guess, try it

if ($model->load(Yii::$app->request->post()))
{
    $model->save();

    //then use first_name on your image like you did.

    $model->save();
}

Upvotes: 0

Anamika Shrivastava
Anamika Shrivastava

Reputation: 713

You have to add the base url to the image path .Use the below one.

  <img src="<?php echo Yii::getAlias('@web').'/'.$dataProvider->models[0]->id_image; ?>">

Upvotes: 4

Related Questions