I am trying to get cakePHP to update a record in the database as appose to creating a new one. My script does a check with “FIRST”, and if it does not return false, it should create a new record, else it should update the existing one based on the ID I am specifying. I have below deliberately added the $this->Asset->id = 62; to try force an update, but it does not work. Any help? (Also, if you can understand what it’s suppose to do, please feel free to guide me with perhaps better code 🙂 Very new to cake:
public function index() {
if($this->request->is("post")) {
$aid = $this->request->data['Asset']['asset_identifier'];
$type = $this->request->data['Asset']['asset_type_id'];
$asset = $this->Asset->find("first",array("fields" => array("Asset.id", "Asset.user_id", "Asset.status_id", "Asset.financial_id", "Asset.insurance_id"),"conditions" => array("Asset.asset_identifier" => $aid, "Asset.asset_type_id" => $type)));
if($asset != false) {
$uid = $this->Auth->user("id");
// UPDATE, depends on info:
$this->Asset->id = $asset['Asset']['id'];
foreach(array("financial_id", "insurance_id", "user_id") as $value) {
if($asset['Asset'][$value] != 0) {
$emails[] = $asset['Asset'][$value];
}
}
if(isset($emails) && count($emails)) {
$this->request->data['Asset']['status_id'] = 1;
$email = new CakeEmail();
$email->from(array('noreply@assetchase.co.za' => 'Assetchase.co.za'));
$email->subject('Assetchase.co.za result notification.');
foreach($emails as $value) {
$user = $this->User->find("first",array("fields" => array("username"),"conditions" => array("id" => $value)));
$email->to($user['User']['username']);
$email->send('A new notification, booyah!');
// Send an email with the username.
}
}
if($this->Auth->user("user_type_id") == 2) {
$this->request->data['Asset']['user_id'] = $uid;
} elseif($this->Auth->user("user_type_id") == 3) {
$this->request->data['Asset']['financial_id'] = $uid;
} elseif($this->Auth->user("user_type_id") == 4) {
$this->request->data['Asset']['insurance_id'] = $uid;
}
}
$this->Asset->id = 62;
if($this->Asset->saveAll($this->request->data)) {
$this->Session->setFlash("A new asset has been loaded",'success');
$this->redirect(array("controller" => "asset", "action" => "thankyou", "guest"));
} else {
$this->Session->setFlash('An error has occured.','default',array('class'=>'error'));
}
}
$assetTypes = $this->Asset->AssetType->find('list');
$this->set("assetTypes", $assetTypes);
}
When you call
$this->Asset->saveAll($this->request->data)you are telling Cake to take the POST data and try to save it. It does not look at$this->Assetwhere you set the ID to 62 at all. You can verify that by inspecting the output ofvar_dump($this->request->data). Try something like$this->request->data['Asset']['id'] = 62instead.