Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array to string for date format in CakePHP 3.x

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
like image 589
mistaq Avatar asked Mar 23 '26 20:03

mistaq


1 Answers

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

  • Cookbook > Datebase Access & ORM > Database Basics > Data Types
  • API > \Cake\Database\Type::build()
  • API > \Cake\Database\Type\DateType::marshal()
like image 52
ndm Avatar answered Mar 26 '26 10:03

ndm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!