3

In my form, when I submit it, I send a notification email that is populated with the form inputs. One these inputs is called date.

When I submit the form, it is submitted in the format of an array as follows:

[
    'year' => 'yyyy',
    'month' => 'mm',
    'day' => 'dd'
]

In my controller, I then send an email to the logged in user before saving the form data to the database.

This is an excerpt of my email's ViewVars:

$email->viewVars([
                'date' => $date,
            ]);

Because the date is in the form of an array, I get the following error in the email:

Notice (8): Array to string conversion [APP/Template\Email\html\bookingrequest.ctp, line 15]

with line 15 being the line where I do an echo of the viewVars variable $date, as follows:

<?= $date ?>

I was looking up ways of doing a conversion from array to string and have tried the following:

Given $date = $data['session']['date'];

  • $date = date('Y-m-d',$date->getTimestamp()); - cannot be used on an array
  • $date = $this->Bookings->Sessions->deconstruct('date', $date); - found out it was deprecated
  • $date = $data['session']['date']->i18nFormat(); - cannot be used on an array
mistaq
  • 375
  • 1
  • 8
  • 29

1 Answers1

4

You can use the same functionality that CakePHP internally uses to transform array representations of dates to actual date objects, that is utilizing the marshal() method of the respective database type object. Once you have a date object, you can then easily format it to whatever you like.

For date-only types you would use \Cake\Database\Type\DateType, which should be retrieved via the \Cake\Database\Type::build() singleton method, in order to use the same instance as the rest of the application:

$dateObject = \Cake\Database\Type::build('date')->marshal($date);
// ... maybe add a check here to ensure that the conversion was successful
echo $dateObject->i18nFormat();

See also

ndm
  • 59,784
  • 9
  • 71
  • 110