How to Pass Param from Controller to Layout in Yii2

How to pass param from controller to layout in YII2

yii\base\View has special $params property.

For example it's used for building breadcrumbs in default generated CRUD code templates with Gii.

You can set it like this before rendering:

use Yii;

Yii::$app->view->params['customParam'] = 'customValue';

Inside a controller you can set it like this:

$this->view->params['customParam'] = 'customValue';

Then it will be available in views (including main layout):

/* @var $this yii\web\View */

echo $this->params['customParam'];

You can also find it in official guide.

Pass params from view to layout in Yii2

If your view is rendered by a controller, you can do as below.

  1. Declare a public member in your controller

    public $params;

  2. Assign value in your view

    $this->context->params['name'] = 'masoud';

  3. Now you can use the variable in your layout

    <?= $this->context->params['name'] ?>


Yii2 pass parameters to mail layout

I just found out another way to set params to layout from controller :

// In your controler before send mail : 
Yii::$app->mailer->view->params['title'] = $title;

// In your layout
echo $this->params['title'];

Hope this help!

How to pass variable from controller to model after function execution Yii2

For example, an Investment amount should be more or equal with the Proposal's min_investment value. Below is the beforeValidate() function in Investment model.

public function beforeValidate()
{
parent::beforeValidate();

$proposal = Proposal::findOne($this->proposal_id);

if ($this->amount < $proposal->min_investment)
{
$this->addError('amount', Yii::t('app', 'Minimum amount should be ' . $proposal->min_investment));
return FALSE;
}

return TRUE;
}

Is that what you're trying to achieve?

How to access variables from controller in layout/main.php Yii2

You used is as string, but it should me variable:

<?= $form->field($searchModel, 'subject')....

Yii 2 - how to pass a variable to main view file to the renderer?

// layouts/main.php
var_dump($this->params);

// action method
$this->view->params['balance'] = $balance;

Also take a look http://www.yiiframework.com/doc-2.0/guide-structure-views.html#using-blocks



Related Topics



Leave a reply



Submit