CakePHP-FileUpload-Plugin
CakePHP-FileUpload-Plugin copied to clipboard
Saving file with new record
I'm trying to use the FileUpload plugin in my CakePHP (1.3) app. I have two models: PendingContract and PendingContractFile. A PendingContract can have many PendingContractFile. When saving a new PendingContract, I'd also like to save the uploaded PendingContractFile, however, my save method fails because PendingContract does not yet have an ID, and that is used as the foreign key in my PendingContractFile.
For clarity, here are my models:
<?php
class PendingContract extends AppModel {
var $name = 'PendingContract';
var $belongsTo = array(
'Supplier'
);
var $hasMany = array(
'PendingContractFile'
);
}
<?php
class PendingContractFile extends AppModel {
var $name = 'PendingContractFile';
var $belongsTo = array(
'PendingContract' => array(
'className' => 'PendingContract',
'foreignKey' => 'pending_contract_id'
),
'Author' => array(
'className' => 'User',
'foreignKey' => 'author_id'
)
);
}
And here is my controller method where I'm saving my PendingContract:
<?php
class PendingContractsController extends AppController {
function add() {
if (!empty($this->data)) {
if ($this->FileUpload->success) {
$this->Session->setFlash('Pending contract successfully created.');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash($this->FileUpload->showErrors());
}
}
}
}
Currently the error I'm getting is:
1452: Cannot add or update a child row: a foreign key constraint fails (pending_contract_files, CONSTRAINT pending_contract_files_ibfk_1 FOREIGN KEY (pending_contract_id) REFERENCES pending_contracts (id) ON DELETE CASCADE ON UPDATE CASCADE)
How can I use the FileUpload plugin so that it attaches the uploaded file with my new PendingContract record?