Basically trying to do this in a CakePHP 4.5.9 application.
I have a Model called Whitepapers
and with I'm trying to validate a file upload. The code for the application has been created with bake
initially.
The template file has a field called filename
:
<?= $this->Form->create($whitepaper, ['type' => 'file']) ?>
<?= $this->Form->control('filename', ['label' => 'PDF File', 'type' => 'file']) ?>
<?= $this->Form->button(__('Save')) ?>
<?= $this->Form->end() ?>
In my Controller I have the following
public function add()
{
$whitepaper = $this->Whitepapers->newEmptyEntity();
if ($this->request->is('post')) {
$whitepaper = $this->Whitepapers->patchEntity($whitepaper, $this->request->getData());
// PDF file
$file = $this->request->getUploadedFiles();
// Filename stays the same as uploaded by the user.
$uploadedFilename = $file['filename']->getClientFilename();
// Filename for saving in DB
$whitepaper->filename = $uploadedFilename;
// ...
}
}
My intentions are:
- To have the file available to upload into cloud storage, which is what
$file
represents. Subsequent code does this and works correctly. - Save the name of the corresponding file in the database in the
whitepapers
table in a column calledfilename
. - Perform validation such that there must be a file uploaded, it is a PDF, and is 10 MB or under.
The code I have in the Model looks like this, which is based off the linked article.
// src/Model/Table/WhitepapersTable.php
class WhitepapersTable extends Table
{
$validator
->scalar('filename')
->maxLength('filename', 255)
->requirePresence('filename', 'create')
->notEmptyFile('filename');
$validator->uploadedFile('filename', [
'types' => [
'application/pdf',
],
'maxSize' => 10 * 1024 * 1024, // 10 MB
]);
}
This doesn't work. It will let me upload any file, of any size.
I'm not sure if filename
is correct - on the line $validator->uploadedFile('filename')
- since that seemingly represents both a column in the database (i.e. the filename) but somehow also the uploaded file itself?
I've cleared all the files in tmp/cache/*
to make sure the Model isn't being cached.
What am I doing wrong?