Skip to content

Commit adca59b

Browse files
committed
Fix autofill datetime field logic
1 parent 03b7e7e commit adca59b

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

src/Model/Behavior/InsertBehavior.php

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use App\Model\Entity\ResourceFormatterTrait;
66
use Cake\Database\Expression\QueryExpression;
77
use Cake\Database\StatementInterface;
8+
use Cake\I18n\FrozenTime;
89
use Cake\ORM\Behavior;
910
use Cake\ORM\Entity;
1011
use Cake\ORM\Query;
@@ -67,16 +68,17 @@ public function insertOnce(Entity $entity, array $conditions = null)
6768
{
6869
if ($this->_config['event']['beforeSave']) {
6970
$this->_table->dispatchEvent('Model.beforeSave', compact('entity'));
70-
if ($entity->created) {
71-
$entity->created= $entity->created->toDateString();
72-
}
73-
if ($entity->modified) {
74-
$entity->modified= $entity->modified->toDateString();
75-
}
7671
}
7772

7873
$entity->setVirtual([]);
7974
$insertData = $entity->toArray();
75+
if (isset($insertData['created']) && !is_null($insertData['created'])) {
76+
$insertData['created'] = FrozenTime::now()->toDateTimeString();
77+
}
78+
if (isset($insertData['modified']) && !is_null($insertData['modified'])) {
79+
$insertData['modified'] = FrozenTime::now()->toDateTimeString();
80+
}
81+
8082
$escape = function ($content) {
8183
return is_null($content) ? 'NULL' : '\'' . addslashes($content) . '\'';
8284
};

tests/TestCase/Model/Behavior/InsertBehaviorTest.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Itosho\EasyQuery\Test\TestCase\Model\Behavior;
44

55
use Cake\Chronos\Chronos;
6+
use Cake\I18n\FrozenTime;
67
use Cake\ORM\Table;
78
use Cake\ORM\TableRegistry;
89
use Cake\TestSuite\TestCase;
@@ -187,7 +188,7 @@ public function testInsertOnceAddTimestampBehavior()
187188
'published' => 1
188189
];
189190
$entity = $this->Articles->newEntity($newData);
190-
$now = Chronos::now();
191+
$now = FrozenTime::now();
191192

192193
$this->Articles->insertOnce($entity);
193194

@@ -240,7 +241,7 @@ public function testInsertOnceWhenIsNull()
240241

241242
$actual = $this->Articles
242243
->find()
243-
->where( [
244+
->where([
244245
'title' => 'First Article',
245246
'body IS' => null,
246247
'published' => 1

0 commit comments

Comments
 (0)