rahul s negi
rahul s negi

Reputation: 139

How and where to write function to use in layout(main.php) in yii2 basic

previously i made a navigation bar in a view page for which i wrote the function in corresponding controller but now i have to put this in main file (layout). But now i don't know where to write the function. also i have to pass two variable to the layout file through the function that will contain the value of navigation bar. I have already tried some method but it allows me to return only on value. Basically i want to know that where can i write the below function to use it in main layout of yii2 basic

public function actionMenutest()
{

    $query = new Query;

    $data= $query->select('name,id')
        ->from('menu')->all();

    $query2 = new Query;

    $data2= $query2->select('name,menu_id')
        ->from('submenu')->all();


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

Upvotes: 0

Views: 238

Answers (1)

Chinmay Waghmare
Chinmay Waghmare

Reputation: 5456

You can use EVENT_BEFORE_RENDER for this purpose. For advanced app the below code need to go into common\config\bootstrap.php file.

use yii\base\Event;
use yii\base\View;

Event::on(View::className(), View::EVENT_BEFORE_RENDER, function() {
    $query = new Query;

    $data= $query->select('name,id')
    ->from('menu')->all();

    $query2 = new Query;

    $data2= $query2->select('name,menu_id')
    ->from('submenu')->all();

    Yii::$app->view->params['data'] = $data;
    Yii::$app->view->params['data2'] = $data2;

});

Then in your main layout you can use your model as:

$data= $this->params['data'];
$data2= $this->params['data2'];

I have not used basic template as yet. But you can try the following:

Create a bootstrap.php file in config folder.

After that update the web/index.php file. Put the below code in that:

require(__DIR__ . '/../config/bootstrap.php');

Then put the above code in bootstrap.php file. Try it and let me know if you need any more help.

Upvotes: 1

Related Questions