John Doe
John Doe

Reputation: 649

saveAll() inserts new row instead of updating

I'm trying to update a record with CakePHP SaveAll() method but however, it adds new row instead of updating it.

My model are as follow: A Store hasOne Map

class Store extends AppModel {  
    var $name = 'Store';

    var $hasOne = array(
        'Map' => array(  
            'className' => 'Map',
            'foreignKey' => 'store_id',
            'dependent' => true,
            'exclusive' => true
        )
    );
}

My edit form has a Store ID (hidden field) to tell CakePHP to update a particular record only.

<?php echo $this->Form->input('Store.id'); ?>
<?php echo $this->Form->input('Store.name', array('label' => 'Store name', 'required')); ?>
<?php echo $this->Form->input('Map.latlng', array('label' => 'Map location', 'required')); ?>

My edit method in the Store controller are as follow.

if ($this->Store->saveAll($this->data)) {
    $this->Session->setFlash('Store has been updated.');
    $this->redirect(array('controller' => 'store', 'action' => 'admin_index'));
}

Whenever I edit a Store, the store name is updated fine but CakePHP keeps on inserting a new row on the Map table.

Am I missing anything here? Thanks

Additional info

My debug($this->data) are as follow

Array
(
    [Store] => Array
        (
            [id] => 52
            [name] => Sena The Accessorizer
        )

    [Map] => Array
        (
            [latlng] => 3.1580681, 101.7126311
        )

)

Upvotes: 3

Views: 6186

Answers (3)

John Doe
John Doe

Reputation: 649

As @Dunhamzzz has pointed out, Map does not have an ID, hence CakePHP inserts a new record.

To solve this, I created a hidden field for Map.id

<?php echo $this->Form->input('Map.id'); ?>

This will tell CakePHP to update that particular record instead of inserting a new one.

Upvotes: 4

thecodeparadox
thecodeparadox

Reputation: 87073

for update you should use:

$this->Store->updateAll($this->data, array('Store.id' => $this->data['Store']['id']));

Upvotes: 1

Oldskool
Oldskool

Reputation: 34837

If you want to update data, rather then saving, you should always set the id you want to update prior to saving, like this:

// Set the store ID
$this->Store->id = $this->data['Store']['id'];

// Then save using that id
if ($this->Store->saveAll($this->data)) {
    $this->Session->setFlash('Store has been updated.');
    $this->redirect(array('controller' => 'store', 'action' => 'admin_index'));
}

Upvotes: 2

Related Questions