1

I'm trying to add an asset to an entry's assetfield when the entry is saved by using the onBeforeSaveEntry service provided by Craft.

craft()->on('entries.onBeforeSaveEntry', function(Event $event) use ($fileIds)
  {
      $entry = $event->params['entry'];
      if ($entry->section['handle'] == "bildupload" && $event->params["isNewEntry"]){
        $entry->getContent()->useruploads = $fileIds;
      }
  });

Contents of the $fileIds-array are created like so:

$copyrightedImage = craft()->assets->insertFileByLocalPath(
      $tempPath,
      $originalFile,
      $myAssetFolderId,
      AssetConflictResolution::KeepBoth
);

if ($copyrightedImage->isSuccess()){
      $fileIds[] = $copyrightedImage->getDataItem('fileId');
}

This works pretty well for fields such as a formatted text field or the title, but I cant figure out how to change the asset inside an asset field. The assetfield of the entries in the section bildupload goes by the handle useruploads. How would I go about fetching the assetId, the full Url to the photo or whatever is used here and add the desired photo into the assetfield as an additional used asset?

Thanks for any help or hints.

Edit: I tried following what Brandon described here, but to no avail. There are no errors thrown, however the assetfield of the entry remains completely empty and does not have any image assigned to it. I'm using closures to use the array $fileIds in the functions shown below.

1

After taking a look again, it turned out to simply be an issue with the scope of the array and a therefore empty array as a result. Works as expected now.

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.