I used the examples from the cookbook, the job application form and want to make it fit my needs. That is making attachments to an email just optional.
The cookbook examples requires to upload an attachement.
Of course I deleted the “required” from the file form field but this wasn’t enough.
How do I make attachments optionally?
in the controler there are some lines that look suspicious to me:
// get the uploads
$uploads = $kirby->request()->files()->get('file');
Is “request” the problem?
if ($upload['error'] === 4) {
$alerts[] = 'You have to attach at least one file';
There is this alert but it is not the thing that demands a file to be attached, right?
Well, error 4 means there is no file attached, so in this case we throw an error. You probably have to adapt it some more, but I would have to check this out myself.
if ($uploads[0]['error'] !== 4) {
foreach ($uploads as $upload) {
// make sure there are no other errors
if ($upload['error'] !== 0) {
$alerts[] = 'The file could not be uploaded';
// make sure the file is not larger than 2MB…
} elseif ($upload['size'] > 2000000) {
$alerts[] = $upload['name'] . ' is larger than 2 MB';
// …and the file is a PDF
} elseif ($upload['type'] !== 'application/pdf') {
$alerts[] = $upload['name'] . ' is not a PDF';
// all valid, try to rename the temporary file
} else {
$name = $upload['tmp_name'];
$tmpName = pathinfo($name);
// sanitize the original filename
$filename = $tmpName['dirname']. '/'. F::safeName($upload['name']);
if (rename($upload['tmp_name'], $filename)) {
$name = $filename;
}
// add the files to the attachments array
$attachments[] = $name;
}
}
}
If it still doesn’t work, I’ll have to postpone this till tomorrow and test it myself (not to fluent with files in forms).