Z
Z
ZaurK2019-02-07 11:26:07
Yii
ZaurK, 2019-02-07 11:26:07

What caused the error when calling the inverse function in GridView?

Hello! In yii2, I have little experience, one moment caused difficulties.
In the GridView, one of the columns displays some id_quiz parameter, I need to replace this id_quiz with the corresponding title.

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'id',
            'id_user',
            'result:ntext',
            [
            'attribute'=>'id_quiz',
            'value' => function ($model, $service) {
                return  $service->getQuizTitleById($model->id_quiz);
            },
            ],

        // тут некоторый код
        ],
    ]); ?>

Models $model, $service I declare, and in the $service object there is a getQuizTitleById method, which should replace the id with the title
public function getQuizTitleById($order_quiz)
    {
        $my_quiz = Quiz::find()
                         -> where(['id' => $order_quiz])
                         -> one();
        return $my_quiz['quiztitle'];
    }

But I get the error "Call to a member function getQuizTitleById() on integer", is it correct to call the function like this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2019-02-07
@ZaurK

AR returns an object, and you use it as an array, so it's probably not
right
, or use asArray() in the query
BUT!!! This is shitcode. There are links in yii2 for similar purposes. It's simple: There must be a getQuiz method that implements the relationship:

public function getQuiz()
    {
        return $this->hasOne(Quiz::class,['id' => 'id_quiz']);
    }

and in the gridview it will be enough
'columns' => [
....
'quiz.quiztitle'
....
]

Of Doc on the topic:
https://www.yiiframework.com/doc/guide/2.0/en/db-a...
Video on the topic:
https://youtu.be/v9wfyGOoGR8?list=PLOm4dl-NavgyBnt.. .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question