F
F
FrelFrloich2019-01-25 14:38:59
Yii
FrelFrloich, 2019-01-25 14:38:59

Yii2 Widgets and database?

Good day, I'm very young and green in php and in yii in particular, I'm interested in the question of whether it is correct to connect to the database table in the widget. If it's not correct, I ask you to explain, if possible, how to correctly display data in the widget.
For clarity, in this way, in this menu there will be pictures that I would like to replace as needed, I don’t know other ways how to pull pictures from the database into the menu (let’s say on the same bg) and subsequently change them as you please.

$menu = Imagemenumain::find()->all();
                         
        return $this->render
        ('myimagemenu',
            ['menuimg' => $menu]
        );     
  }

myimagemenu is the widget's view where html. I would be very grateful if you point to any article with this topic, and how to act in the right way (my own futile searches did not lead to anything, including in the off-line documentation for yii, and knowledge is not enough to solve the issue on my own).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2019-01-25
@webinar

Here, probably, any answer will be controversial, but I think it’s better to do this:
in the config (or in the base controller) we cling to the beforeAction event:

'on beforeAction' => function($event){
      Yii::$app->params['menuData'] = ArrayHelper::map(Imagemenumain::find()->all(),'id','title');
      //ArrayHelper тут для примера, хотел обозначить, что не стоит засовывать в params более чем нужно виджету. Там должен оказаться подготовленный массив с нужными данными
    },

in views/layout/main.php we use the widget
echo SomeMyWidget::widget([
  'someWidgetParam' => Yii::$app->params['menuData'],
  'someWidgetParam2' => 'маракуя',
  'otmetitOtvetom' => true
]);

The widget does not need to know about the database. Tomorrow the database structure will change, but the widget will continue to work. Since it receives a certain array of data. And when changing the structure of the database, you simply change the method of forming the desired array, which would be passed to the widget. For the same reason, it can be reused in other projects.
PySy: Formation of an array along with a request to the database probably makes sense to cache.

L
Lander, 2019-01-25
@usdglander

In fact, a widget is isolated code that must form the html. That is, it is part of the species. And in the form itself, access to the data should not be carried out. All data that is needed for display must be transferred from outside.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question