Upload and if error rollback record

I upload the file, and at the same time I store the file name in the database. As I please do in the controller check the file upload, if the upload fails, I would like to rollback the record.

Example:

        if ($this->request->is(['patch', 'post', 'put'])) {

            $data = $this->request->getData();
            $file = $this->request->getData('file');
            $file_new = $this->getHash() . '.' . pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);

            $data_file = [
                'name' => $file->getClientFilename(),
                'file' => $file_new,
                'size' => $file->getSize(),
            ];

            $informationsAttachment = $this->InformationsAttachments->patchEntity($informationsAttachment, array_merge($data, $data_file));

            $isSave = $this->InformationsAttachments->save($informationsAttachment);

            $this->upload($file, $isSave->id);

            if ($isSave) {
                $this->Flash->success(__('The informations attachment has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The informations attachment could not be saved. Please, try again.'));
        }

I need the ID of the new record to create the folder.

Thank you

You’re looking for transactions.

1 Like