5

Using yii2 I have created a Model and CRUD using gii.

I want to use a foreach or while loop in my VIEW to display the data in the following format

For each row in database table

echo("addMarker($lat_field, $lon_field);\n");

I have an index page which is rendered using the following controller action.

    public function actionIndex()
{
    $this->layout = 'directory';

    $searchModel = new ShopDirectorySearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

I can use the following to display the data using listview which displays all the data/rows within database however it has html around it and obviously isn't outputted in the format I wish it to be.

    <?=  ListView::widget([
 'dataProvider' => $dataProvider,
 'itemOptions' => ['class' => 'col-xs-6 col-sm-3'],
 'itemView' => '_index',
]);?>

3 Answers 3

18

No need to use ListView here, you should simply try :

foreach ($dataProvider->models as $model) {
    echo "addMarker({$model->lat_field}, {$model->lon_field});";
}

If you really want to use ListView, you could simply edit _index view file.

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution looks perfect I didn't want to use list view I was just unsure on how to display data in yii2 with using one of there widgets.
3
if(!empty($st_data))
    {
        foreach($st_data as $row)
        {
            echo 'Country Name: '.$row['country_name'].'</br>';
            echo 'State Name: '.$row['state_name'].'</br>';
            echo 'City Name: '.$row['city_name'].'</br>';
            echo '</br>';
        }
        exit;
    }

Comments

2
$rows = ShopDirectory::findAll();
if(!empty($rows))
{
  foreach($rows as $row)
  {
    $lat = $row->lat;
    $lon = $row->lon;

    $this->view->registerJs('addmarker("'.$lat.'", "'.$lon.'"."\n");', yii\web\View::POS_END);
    ...
  }
}

http://www.yiiframework.com/forum/index.php/topic/61940-simple-while-loop-to-list-all-rows/page__view__findpost__p__274731

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.