Force saving with when insert primary key value
Have you ever try to make a save when you manually set the primary key value?? > By default Cakephp perform an update query, when in the fields array there is the primary key value set. <br > If we have a DB table, where the primary key is not an AI, but is a value generated by an algoritm, we need to force cakephp to make an insert into query instead an update this workaround use the beforeSave callback. > beforeSave is called after cakephp decide in the current saving process in an insert or an update. <h1>put this code in the app_model:< h1> ` publicfunctionbeforeSave($opt){ parent::beforeSave($opt); if(isset($opt[‘id’])&&$opt[‘id’]){ if(!isset($this->data[$this->name][$this->primaryKey])){ $this->data[$this->name][$this->primaryKey]=$opt[‘id’]; } } returntrue; } ` ><br >
When you need to force the save use this:
` $this->save( array( ‘Model’=>$fields ), array( ‘id’=>$newId ) ); ` ><br > Replace $fields with the array fields to save but NOT INSERT IN IT THE PRIMARY KEY VALUE. > Replace $newId with the value of the primary key < strong> ><br >