变量 $context 在模板中没有被正确解释。

huangapple go评论42阅读模式
英文:

the variable $context is not interpreted correctly in the template

问题

I can't get out of this error: Object of class Symfony\Bridge\Twig\Mime\WrappedTemplatedEmail could not be converted to string

My setup:
php 8.2
symfony 6.2
mailer 6.2
and i use maildev

My service :

namespace App\Service;

use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;

class SendMailService
{
    private $mailer;

    public function __construct(MailerInterface $mailer)
    {
        $this->mailer = $mailer;
    }

    public function send(string $from, string $to, string $subject, string $template, array $context): void
    {
        $email = (new TemplatedEmail())
            ->from($from)
            ->to($to)
            ->subject($subject)
            ->htmlTemplate("emails/$template.html.twig")
            ->context($context);

        // On envoie le mail
        $this->mailer->send($email);
    }
}

if I put ->context([$context]) instead of ->context($context), in my template I get this error: there is no variable 'prenom'

My controller action :

#[Route('/app_email', name: 'app_email', methods: ['POST'])]
public function sendEmail(Request $request, SendMailService $mail): Response
{
    if ($request->isXmlHttpRequest()) {
        $from = $this->getParameter('from_email');
        $emailAdressTo = $request->request->get('email');  // To
        $template = 'contact';
        $subject = "Envoi à partir du formulaire de contact du site Vous assurance";
        $nom = $request->request->get('nom');
        $prenom = $request->request->get('prenom');
        $entreprise = $request->request->get('entreprise');
        $message = $request->request->get('message');

        $context = array(
            'nom' => $nom,
            'prenom' => $prenom,
            'entreprise' => $entreprise,
            'message' => $message,
        );

        dump($from);
        dump($emailAdressTo);
        dump($subject);
        dump($template);
        dump(gettype($context));

        $mail->send($from, $emailAdressTo, $subject, $template, $context);
        return new Response("ok");
    }
    return new Response("Erreur : ceci n'est pas une requête ajax", 400);
}

Dump result :

Dumped Contents In MainController.php line 54: "xxxx@xxx.fr" In MainController.php line 55: "xxxxx@xxxxx.com" In MainController.php line 56: "Envoi à partir du formulaire de contact du site" In MainController.php line 57: "contact" In MainController.php line 58: "array"

if I comment out the $context variable, my email is sent

My ajax function :

var formNewContact = $('form[id="formContact"]');
formNewContact.on("submit", function (e) {
  e.preventDefault();
  var formData = new FormData($(this)[0]);
  $.ajax({
    method: "POST",
    url: "{{ path('app_email') }}",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
      if (response === 'ok') {
      } else {
        alert("Erreur");
      }
    }, // Fin success
    error: function () {
      alert("Erreur serveur");
    }, // Fin error
  }); // Fin ajax
}); // Fin function submit form contact

My template :

<p>Bonjour,</p>
<p><strong>De :</strong>{{ prenom }}<strong>{{ nom }}.</strong></p>
<p><strong>Email : </strong>{{ email }}</p>
<p><strong>Entreprise : </strong>{{ entreprise }}</p>
<p><strong>Message :</strong></p>
<hr />
<p>{{ message }}</p>
<hr />
</div>

dump(gettype($context)); -> array

Thanks for your help.

I changed :
In form this field :

<div class="mb-3">
    <label for="emailTo" class="form-label">Mail (obligatoire)</label>
    <input type="email" class="form-control" name="emailTo" id="emailTo" aria-describedby="mailHelp" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required>
    <div class="valid-feedback feedback-pos">
        Adresse email OK
    </div>
    <div class="invalid-feedback feedback-pos">
        Cette adresse email n'est pas correcte
    </div>
</div>
英文:

I can't get out of this error: Object of class Symfony\Bridge\Twig\Mime\WrappedTemplatedEmail could not be converted to string

My setup :
php 8.2
symfony 6.2
mailer 6.2
and i use maildev

I would like to generate a mail sending with ajax.

My service :

    &lt;?php

namespace App\Service;

use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;


class SendMailService
{
    private $mailer;

    public function __construct(MailerInterface $mailer)
    {
        $this-&gt;mailer = $mailer;
    }

    public function send(string $from, string $to, string $subject, string $template, array $context): void
    {
        $email = (new TemplatedEmail())
            -&gt;from($from)
            -&gt;to($to)
            -&gt;subject($subject)
            -&gt;htmlTemplate(&quot;emails/$template.html.twig&quot;)
            -&gt;context($context);

        // On envoie le mail
        $this-&gt;mailer-&gt;send($email);
    }
    
}

if I put ->context([$context]) instead of ->context($context), in my template I get this error: there is no variable 'prenom'

My controller action :

#[Route(&#39;/app_email&#39;, name: &#39;app_email&#39;, methods: [&#39;POST&#39;])]
public function sendEmail(Request $request, SendMailService $mail): Response
{
    if ($request-&gt;isXmlHttpRequest()) {
        $from = $this-&gt;getParameter(&#39;from_email&#39;);
        $emailAdressTo = $request-&gt;request-&gt;get(&#39;email&#39;);  // To
        $template = &#39;contact&#39;;
        $subject = &quot;Envoi &#224; partir du formulaire de contact du site Vous assurance&quot;;
        $nom = $request-&gt;request-&gt;get(&#39;nom&#39;);
        $prenom = $request-&gt;request-&gt;get(&#39;prenom&#39;);
        $entreprise = $request-&gt;request-&gt;get(&#39;entreprise&#39;);
        $message = $request-&gt;request-&gt;get(&#39;message&#39;);

        $context = array(
            &#39;nom&#39; =&gt; $nom,
            &#39;prenom&#39; =&gt; $prenom,
            &#39;entreprise&#39; =&gt; $entreprise,
            &#39;message&#39; =&gt; $message,
        );

        dump($from);
        dump($emailAdressTo);
        dump($subject);
        dump($template);
        dump(gettype($context));
        
        
        $mail-&gt;send($from, $emailAdressTo, $subject, $template, $context);
        return new Response(&quot;ok&quot;);

    }
    return new Response(&quot;Erreur : ceci n&#39;est pas une requ&#234;te ajax&quot;, 400);
}

Dump result :

Dumped Contents In MainController.php line 54: &quot;xxxx@xxx.fr&quot; In MainController.php line 55: &quot;xxxxx@xxxxx.com&quot; In MainController.php line 56: &quot;Envoi &#224; partir du formulaire de contact du site&quot; In MainController.php line 57: &quot;contact&quot; In MainController.php line 58: &quot;array&quot;

if I comment out the $context variable, my email is sent

My ajax function :

var formNewContact = $(&#39;form[id=&quot;formContact&quot;]&#39;);
formNewContact.on(&quot;submit&quot;, function (e) {
  e.preventDefault();
  var formData = new FormData($(this)[0]);
  $.ajax({
    method: &quot;POST&quot;,
    url: &quot;{{ path(&#39;app_email&#39;) }}&quot;,
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
      if (response === &#39;ok&#39;) {
      } else {
        alert(&quot;Erreur&quot;);
      }
    }, // Fin success
    error: function () {
      alert(&quot;Erreur serveur&quot;);
    }, // Fin error
  }); // Fin ajax
}); // Fin function submit form contact

My template :

&lt;p&gt;Bonjour,&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;De : &lt;/strong&gt;{{ prenom }}&lt;strong&gt;{{ nom }}&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Email : &lt;/strong&gt;{{ email }}&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Entreprise : &lt;/strong&gt;{{ entreprise }}&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;Message :&lt;/strong&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;{{message}}&lt;/p&gt;
&lt;hr /&gt;
&lt;/div&gt;

dump(gettype($context)); -> array

Thanks for your help.

I changed :
In form this field :

&lt;div class=&quot;mb-3&quot;&gt;
    &lt;label for=&quot;emailTo&quot; class=&quot;form-label&quot;&gt;Mail (obligatoire)&lt;/label&gt;
    &lt;input type=&quot;email&quot; class=&quot;form-control&quot; name=&quot;emailTo&quot; id=&quot;emailTo&quot; aria-describedby=&quot;mailHelp&quot; pattern=&quot;[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$&quot; required&gt;
    &lt;div class=&quot;valid-feedback feedback-pos&quot;&gt;
       Adresse email OK
    &lt;/div&gt;
    &lt;div class=&quot;invalid-feedback feedback-pos&quot;&gt;
       Cette adresse email n&#39;est pas correcte
    &lt;/div&gt;
&lt;/div&gt;

答案1

得分: 1

你的模板中,你尝试将电子邮件实例渲染为字符串,使用 {{ email }}。这就是为什么你会收到这个错误消息。

也许你想要打印电子邮件地址:{{ email.to[0].address }}

查看:https://symfony.com/doc/current/mailer.html#html-content

Twig 模板可以访问传递给 TemplatedEmail 类的 context() 方法的任何参数,还可以访问一个名为 email 的特殊变量,它是 WrappedTemplatedEmail 的一个实例。

英文:

In your template, you are trying to render the email instance as a string with {{ email }}. That's why you get this error.

Maybe you want to print the email address instead : {{ email.to[0].address }}

See : https://symfony.com/doc/current/mailer.html#html-content

> The Twig template has access to any of the parameters passed in the context() method of the TemplatedEmail class and also to a special variable called email, which is an instance of WrappedTemplatedEmail.

huangapple
  • 本文由 发表于 2023年2月8日 18:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定