Cody
Cody

Reputation: 112

Cakephp - How to loop through array in email template?

I am able to set the viewVars for a single record and mail it successfully. A problem occurs when I want to send an email containing more than one record. I find the correct records and I am able to pass them to my mail function. The problem comes in that when I debug the array passed to the mail template, I get a

Notice (8): Undefined variable: vars [APP\View\Emails\html\latest_projects.ctp, line 1]

However, just below the error, it does show me the information I want:

(int) 0 => array(
    'Project' => array(
        'id' => '809',
        'created' => '2014-04-23',
        'project_number' => 'SPN00000809',
    )
),
(int) 1 => array(
    'Project' => array(
        'id' => '810',
        'created' => '2014-04-23',
        'project_number' => 'SPN00000810',
    )
)

*Certain fields omitted for brevity.

How do I loop through this array in the email template? I have tried the standard foreach loop as you would in the view, but then I get the undefined variable supplied foreach problem. Any advice or suggestions?

Upvotes: 0

Views: 1787

Answers (3)

Cody
Cody

Reputation: 112

The problem was that the array passed, $dataForView, which is generated by cake, was a combination(?) array - meaning that some keys were associative such as $dataForView['content'] => '', while the other keys were (int)0 => array(); The array received looked as such:

array(
  content => '',
  (int) 0 => array(
    Project => array(
      fieldName1 => value,
      fieldName2 => value
    )
  ),
  (int) 1 => array(
    Project => array(
      fieldName1 => value,
      fieldName2 => value
    )
  )
)

I found that if I unset the associative keys (content) I am able to loop through the normalized array as per usual. I did it in this way, it might not be the best way, but it works.

//remove associative key
unset($dataForView['content']);

//loop through array and output values
foreach($dataForView as $key=>$val):
echo $val['Project']['id']; //echo other info as well
endforeach;
debug($dataForView); 

Thank you all for helping.

Upvotes: 0

Fury
Fury

Reputation: 4776

//Pass your variable
$Email->viewVars(array('projects' => $projects));

//In your email body or template
<ul>
    <?php foreach ($projects as $project) { ?>
        <li><?php echo $project['Project']['project_number']; ?></li>
    <?php } ?>
</ul>

Upvotes: 1

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4142

like said in documentation :-

$Email->viewVars(array('value' => 12345));

you will be able to use it as $value in mail template.

just like that set your array to 'value' you will be able to use $value as array.

Upvotes: 0

Related Questions