Skip to content

Commit

Permalink
Merge pull request #3590 from Haititi/2.6-fix-habtm
Browse files Browse the repository at this point in the history
2.6 fix save() with habtm returning error
  • Loading branch information
markstory committed May 29, 2014
2 parents 1e3730c + 35c2a7e commit a135378
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
38 changes: 21 additions & 17 deletions lib/Cake/Model/Model.php
Expand Up @@ -1784,7 +1784,7 @@ public function save($data = null, $validate = true, $fieldList = array()) {
if (empty($this->data[$this->alias][$this->primaryKey])) {
unset($this->data[$this->alias][$this->primaryKey]);
}
$fields = $values = array();
$joined = $fields = $values = array();

foreach ($this->data as $n => $v) {
if (isset($this->hasAndBelongsToMany[$n])) {
Expand All @@ -1807,6 +1807,11 @@ public function save($data = null, $validate = true, $fieldList = array()) {
}
}

if (empty($fields) && empty($joined)) {
$this->whitelist = $_whitelist;
return false;
}

$count = count($fields);

if (!$exists && $count > 0) {
Expand Down Expand Up @@ -1843,36 +1848,35 @@ public function save($data = null, $validate = true, $fieldList = array()) {
}
}

if (!empty($joined) && $success === true) {
if ($success && !empty($joined)) {
$this->_saveMulti($joined, $this->id, $db);
}

if ($success && $count === 0) {
$success = false;
$this->whitelist = $_whitelist;

if (!$success) {
return $success;
}

if ($success && $count > 0) {
if (!empty($this->data)) {
if ($created) {
$this->data[$this->alias][$this->primaryKey] = $this->id;
}
if ($count > 0) {
if ($created) {
$this->data[$this->alias][$this->primaryKey] = $this->id;
}

if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
$event = new CakeEvent('Model.afterSave', $this, array($created, $options));
$this->getEventManager()->dispatch($event);
}
}

if (!empty($this->data)) {
$success = $this->data;
}

$this->_clearCache();
$this->validationErrors = array();
$this->data = false;
if (!empty($this->data)) {
$success = $this->data;
}

$this->whitelist = $_whitelist;
$this->_clearCache();
$this->validationErrors = array();
$this->data = false;

return $success;
}

Expand Down
4 changes: 3 additions & 1 deletion lib/Cake/Test/Case/Model/ModelWriteTest.php
Expand Up @@ -1824,7 +1824,9 @@ public function testSaveHabtmNoPrimaryData() {

$data = array('Item' => array('Item' => array(1, 2)));
$TestModel->id = 2;
$TestModel->save($data);
$result = $TestModel->save($data);
$this->assertTrue((bool)$result);

$result = $TestModel->findById(2);
$result['Item'] = Hash::sort($result['Item'], '{n}.id', 'asc');
$expected = array(
Expand Down

0 comments on commit a135378

Please sign in to comment.