L
L
Leopandro2018-11-09 18:43:02
Yii
Leopandro, 2018-11-09 18:43:02

How to pass models to js file?

In the controller we take models:

public function actionIndex()
    {
        $searchModel = new BookSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render($this->getIndexByRole(), [
            'searchModel' => $searchModel,
            'models' => $dataProvider->getModels(),
        ]);
    }

Then we try to display :
$script = <<< SCRIPT
var app4 = new Vue({
    el: '#app-4',
    data: {
        todos: '$models'
    }
});
console.log($models);
SCRIPT;
$this->registerJs($script);

<div id="app-4">
        <ol>
            <li v-for="todo in todos">
                {{ todo.id }}
            </li>
        </ol>
    </div>

But nothing comes out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Bay, 2018-11-09
@kawabanga

return $this->asJson(ArrayHelper::map($models,'id',function($model){
            return $model->attributes('id');
        }));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question