D
D
Dmitry2016-11-13 13:46:24
Yii
Dmitry, 2016-11-13 13:46:24

How to pass model to yii2 custom widget?

Good afternoon.
You need to display data from several models on the main page, in the footer.
The widget was written, but the question arose, how now to dynamically transfer the model to the widget class?
Now it looks like this:

// вызов виджета на главной
<?= MainWidget::widget(['limit' => 7]); ?>

// класс виджета
class MainWidget extends Widget
{
    public $limit; // LIMIT на количество записей из базы
    public $data; // Сюда надо передать модель

    public function init()
    {
        if($this->limit == null){
            $this->limit = 5;
        }
        parent::init();
    }

    public function run()
    {
      
       $listGlobe = Countries::find()->where(['status' => Countries::STATUS_ACTIVE])->limit($this->limit)->all();

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

I can’t figure out how to transfer a model from outside to public $data so as not to write for each model
<?php
$listGlobe = NameModel::find()->where(['status' => Countries::STATUS_ACTIVE])->limit($this->limit)->all();
?>

and in the widget call specify
<?php
GlobeWidget::widget(['data' => NameModel]);
?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-11-13
@slo_nik

For example like this:

<?php
$model = MyModel::find()->all();
echo MainWidget::widget(['limit' => 7, 'data'=>$model]); ?>

Of course, you can also pass the class name to the model, but this is not correct:
<?php
echo MainWidget::widget(['limit' => 7, 'data'=>MyModel::classname]); ?>

Ideally, the model should originate in the controller and be passed to the view, where it is further passed to the widget. Or the widget should get not the model itself, but certain data. Perhaps you need to write your own dataProvider. look at the activedataprovider example www.yiiframework.com/doc-2.0/guide-output-data-pro...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question