Reputation: 28030
I am using Cakephp 3.0.2. I would like to add a new record. A complete record $this->request->data
would look something like this;
'date_taken' => [
'month' => '01',
'day' => '05',
'year' => '2015',
'hour' => '02',
'minute' => '51'
],
'moves_per_minute' => '80',
'person_id' => '1'
However, I want to HTTP Post $this->request->data
such that it looks like this;
'moves_per_minute' => '80',
'person_id' => '1'
The dates_taken
data should be updated automatically by using the current time.
I defined the column dates_taken
as DATETIME type and default as CURRENT_TIME_STAMP. When I do a HTTP Post and send $this->request->data
over leaving date_taken
empty, the new row cannot be added.
This is how my controller code looks like;
$newRecord = $this->newRecords->newEntity();
if ($this->request->is('post')) {
$newRecord = $this->newRecords->patchEntity($newRecord, $this->request->data);
if ($this->newRecords->save($newRecord))
{
//success
Debugger::dump("Save success");
}
else
{
$this->response->statusCode(400); //bad request
Debugger::dump("Save failure");
}
}
How should a correct controller look like?
Upvotes: 1
Views: 88
Reputation: 1291
Add the columns 'created' and 'modified' to your database table (both DATETIME), then inside the model for the table add this line:
class ArticlesTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
// Timestamp is the correct, even though the field is a datetime
}
}
After you add new records, the datetime stored in the created field will be the exact time of creation and the modified field will be the last time you modify the record. Cake will do this by default every time you access this record through the entity.
More information can be found via the Timestamp documentation here: http://book.cakephp.org/3.0/en/orm/behaviors/timestamp.html
You could also save the current time by using the Time library and manually setting it in the entity before saving:
$time = Time::now();
$newRecord->date_taken = $time;
$this->newRecords->save($newRecord);
Again assuming the date_taken field is a datetime object in your table. I'd recommend letting the database set it for you rather than this method, though.
Upvotes: 1