1

I want a user to upload a PDF file to his request. On the backend, I can manage to save the file on server, but I'm looking for a way to save it in the Entry just as if I was doing it manually on the admin panel but don't know how. So far I tried different things but I'm not sure what goes in the "cadFile" field as a handle to the actual file. Any help would be appreciated.

if($_FILES){
  $myFile = UploadedFile::getInstanceByName('cadFile');
  $success = $myFile->saveAs('assets/order/' . $myFile->baseName . '.' . $myFile->extension);

  if($success) {
    $model->setFieldValue('cadFile', [$myFile->baseName . '.' . $myFile->extension]);
    $success = Craft::$app->elements->saveElement($model, false);

1 Answer 1

2

You need to register the file into the assets. We can do like this :

        $myFile = UploadedFile::getInstanceByName('cadFile');
        $success = $myFile->saveAs('assets/order/' . $myFile->baseName . '.' . $myFile->extension);
        $asset                          = new Asset();
        $asset->tempFilePath            = 'assets/order/' . $myFile->baseName . '.' . $myFile->extension;
        $asset->filename                = $myFile->baseName . '.' . $myFile->extension;
        $asset->volumeId                = 1;
        $asset->setScenario(Asset::SCENARIO_CREATE);
        $result = Craft::$app->getElements()->saveElement($asset);

So that code will upload your code and register it as asset, for the volumeId you can replace it with your volume id. Then after that we need to save the assets in your entry. To save it on your field you need to pass your asset id inside array.

 entry->setFieldValue('cadFile', [asset->id]);
 $success = Craft::$app->elements->saveElement($entry, false);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.