Yii2 pass parameters to mail layout
Asked Answered
A

3

5

Is there any way to access your parameters within a mail layout when using the Yii mailer class? I can access $model from the view but not the layout.

<?php

        $params = array(
           "model" => $model
        );

        $message = Yii::$app->mailer->compose([
            'html' => $view.'Html',
            'text' => $view,
        ], $params)
        ->setFrom("[email protected]")
        ->setTo($recipient)
        ->setSubject($subject);
?>

I know that for a standard web view you would set yii\web\View::$params to access variables in the layout but this doesn't appear to work for the mailer.

Any ideas?

Antalkali answered 13/8, 2015 at 14:34 Comment(0)
B
8

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!

Bremble answered 17/11, 2016 at 7:18 Comment(0)
H
5

I'd do something similar to how you get breadcrumbs back to the view.

//In your view file, model was passed down via compose as you have it.
//this adds model element to the View object's params.
$this->params['model'] = $model; 

//In your layout
echo $this->params['model']->attribute;
Harem answered 13/8, 2015 at 17:3 Comment(1)
Thanks for that. It's unfortunate that I'll need to do this in every one of my email views but it's much better than having to duplicate header/footer htmlAntalkali
K
-1

I had the same problem and now the params you pass can be directly called as variables in the email template:

// In controller
<?php
$params = [
    'username' => 'diegouser',
    'password' => 'supersecret',
];

Yii::$app->mailer->compose([
            'html' => 'layouts/' . $view . '-html',
            'text' => 'layouts/' . $view . '-text',
        ], $params)
        ->setFrom($mailFrom)
        ->setTo($emailTo)
        ->setSubject($subject)
        ->send();

So you can just echo the variables in the layout:

<?php
// In email layout:
<?= $username ?>
<?= $password ?>
Kilt answered 26/2, 2020 at 22:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.