invictus
invictus

Reputation: 825

Silverstripe 3 - send email with data of foreach-loop

I want to send an email with the data of a foreach loop but I don't know how to get the data into the email body.

that's my current code

...
...

    foreach($cartItems as $cartItem) {
        '<strong>' . $cartItem->Amount . 'x ' . $cartItem->Title . '</strong>' . '<span>' . $cartItem->Price . ' €/St. insgesamt ' . $cartItem->Sum . '</span><br>';
    }
...
...
    $messageBody = " 
         foreach() Content should be here
    "; 
    $email->setBody($messageBody);
...
...

can someone help me?

thank you in advance

Upvotes: 1

Views: 583

Answers (1)

3dgoo
3dgoo

Reputation: 15794

Use the built in Silverstripe Email functionality to take advantage of Silverstripe's templating with your email.

With Silverstripe you can create a template for your email and populate it with whatever data you like.

Within your send function in your controller you can set the template with setTemplate and push data into the email template with populateTemplate:

$email = new Email($from, $to, $subject);

$email->setTemplate('EmailTemplate');

$email->populateTemplate(array(
    'CartItems' => $cartItems,
    'PageTitle' => $this->Title
));

$email->send();

Note that $cartItems has to be a ArrayList or DataList to be able to use <% loop %> in template. If $cartItems is an array, read how to convert it to ArrayList here.

Put your template into themes/mytheme/templates/Email/EmailTemplate.ss

EmailTemplate.ss

<!DOCTYPE HTML>
<html>
<head>
    ...
</head>

<body>
    ...
    <% if $CartItems %>
    <% loop $CartItems %>
    ...
    <% end_loop %>
    <% end_if %>
    ...
</body>
</html>

Upvotes: 2

Related Questions