3
votes

i have 2 tables in my project MainAds and AdsImage and its structure is as follow

MainAds       AdsImage

id            id
category      main_ads_id
description   image
title
price

and I have the following listview

<div class="container">
    <div class="row">
        <div class="item">
            <div class="well">
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">
                    <span>$21.00</span>
                <h4>
                    <a href="#">Project Name</a>
                </h4>
            </div>
        </div>
    </div>
</div>

Which is nothing but a template and in that i want to display all data from table advertisement so how can i do that? so how can i display that data into the view file

I have tried this so far but i its not working properly

<?php foreach ($dataProvider->models as $model) {
    echo "<div class='item'>" +
            "<div class='well'>" +
                "<img class='img-responsive' src='../uploads'.'$imagemodel->image'. alt=''>" +
                    "<span>$21.00</span>" +
                    "<h4>" +
                        "<a href='#'>Project Name</a>" +
                    "</h4>" +
                "</div>"+
            "</div>";
       }
?>

Is the right way to display data on view file or something else as well

I know how to do it using the detailview but i dont know how to use custom layout on the view page using different models.

I tried what Double H suggested in answer below and i am getting the error like below

http://i.stack.imgur.com/UcVtR.png

1

1 Answers

3
votes

Create a relation in MainAds model as : -

public function getAdsImage(){
    $this->hasOne(AdsImage::className() ,['id' => 'main_ads_id']);
}

Make a controller action Index as

public function actionIndex(){
    $query = Addresses::find()->joinWith(['adsImage']);

    $dataProvider = new ActiveDataProvider([
            'query' => $query,

      ]);  
   return $this->render('index' ,['dataProvider' => $dataProvider]);
}

In index.php view

<?= \yii\widgets\ListView::widget([
        'dataProvider' => $dataProvider,
        'itemView' => 'listview'
    ]); ?>

Change your listview.php file as

<div class="container">
    <div class="row">
        <div class="item">
            <div class="well">
                    <?php if(ArrayHelper::getValue($model->adsImage,'image') !== null):?>

       <?= \yii\helpers\Html::img($model->adsImage->image,['class' => 'img-responsive' ,'alt' =>''])?>

    <?php endif; ?>
                    <span>$<?= $model->price?></span>
                <h4>
                    <a href="#"><?= $model->title?></a>
                </h4>
            </div>
        </div>
    </div>
</div>