D
D
Dmitry2017-09-22 16:10:07
Yii
Dmitry, 2017-09-22 16:10:07

How to create a template for a letter from a record in the database?

Good afternoon.
You need to create a letter from a string that is stored in the database.
The line looks like this:

<p><strong>Поступила новая заявка с site.ru.</strong><br />
<br />
<strong>Имя:</strong> {order->name}<br />
<strong>Телефон:</strong> {order->phone}<br />
<strong>Почта:</strong> {order->email}<br />
<strong>Вес:</strong> {order->weight}<br />
<strong>Откуда:</strong> {order->from}<br />
<strong>Куда:</strong> {order->to}<br />
<strong>Дата отправки:</strong> {order->shipping_date}<br />
<strong>Сообщение:</strong> {order->message}</p>

All occurrences starting with order->* must be replaced with values ​​from the POST request.
For example.
There is an action in the controller that saves the data passed through the form.
if(Yii::$app->request->isAjax) {

           $model = new Proposal();

           if($model->load(Yii::$app->request->post()) && $model->validate()){
               if($model->save()){

                   /* получаем шаблон письма из базы данных */
                   $template = EmailTemplate::findOne(['name' => 'new_order']);
                   /* в $model записаны данные, которые надо подставить в $template */
                   Yii::$app->mailer->compose()
                       ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])
                       ->setTo(Yii::$app->siteSettings->get('SITE.EMAIL_ADMIN'))
                       ->setSubject('Новая заявка на сайте' . Yii::$app->name)
                       /* подставляю полученную строку в письмо */
                       ->setHtmlBody($template->body)
                       ->send();

                   return 'ok';
               }
           }
       }
       return false;
    }

How in this case to replace substrings in $template->body with values ​​from $model?
ps So far, such a solution is seen.
When writing a template to the database, create a file in which to write the template itself and use it as a view . When editing a template, overwrite the view file. But there is a slight complication here. Some of the data in $model may be missing. Probably you need to do an additional check to see if the given substring is in the string. For the first version of yii there is a QsEmailManager extension, but is there something similar for the second version?
Yii::$app->mailer->compose('@app/mails')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-09-22
@slo_nik

as the easiest option to use strtr , but before replacing the data from the model must be escaped from html tags

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question