abcy122
abcy122

Reputation: 125

Inserting new row instead of Updating

I am trying to update a profile in the database without passing the profile id as a paramater and instead of updating I am adding new row. I tried to use the getLastInsertId() but it did not work.

public function editProfile(){

    if (isset($this->data)){

        $Client = $this->Client->find('first', array(
        'fields' => array('email','username','first_name','surname','country','phone_prefix','phone'),
        'conditions' => array(
            'Client.email' => $this->request->query['email'],
            'Client.client_type' => $this->request->query['client_type']
             ),
        )
    );


 if($this->request->is('get')) {

        if($data = $this->Client->save($this->request->query,array('first_name','surname','country','phone_prefix','phone')))
        {
            $this->Client->id = $this->Client->getLastInsertId();

Upvotes: 1

Views: 727

Answers (3)

Simon Mason
Simon Mason

Reputation: 561

Looking at the code it seems you have two possible keys:

  1. The client email
  2. The last saved id

First, using the last saved id seems very fragile - how can you be sure this will always be the record you want to update? Best to avoid this approach.

However, if you have the user's email you can use the following method:

$client = $this->Client->findByEmail($this->request->data['Client']['email']);
$id = $client['Client']['id'];

You now have the client record id available to use in your save. Something like:

$data = array();
$data['Client']['id'] = $id;
$data['Client']['fieldFromForm'] = $this->data['Client']['fieldFromForm'];

$this->Client->save($data);

...

Upvotes: 1

AgRizzo
AgRizzo

Reputation: 5271

It looks like you are trying to update a record in your Client model based on the email and client type because (I assume) you don't know the id.

Try changing your code to get the id based on the information you have-

public function editProfile(){

if($this->request->is('get')) {
  if (isset($this->data)){

    $conditions = array('conditions' => array(
            'email' => $this->request->query['email'],
            'client_type' => $this->request->query['client_type']
         ));
    $this->Client->id = $this->Client->field('id', $conditions);

    if($this->Client->save($this->request->query,array('id', 'first_name','surname','country','phone_prefix','phone')))
    {
      $this->setFlash('success');
    }else{
      $this->setFlash('fail');
    }
  }
}

Upvotes: 1

theotherdy
theotherdy

Reputation: 715

Without the id, cake will assume that you are adding a new Client. To update via save you'll need to tell it which Client.id to update in some way. Is there some reason that you can't provide the Client.id? The usual approach is to have Client.id present in a hidden input on your edit view which you can then pass to the edit action...

Upvotes: 0

Related Questions