5

I am using the following code to save an asset that has been downloaded to the storage/runtime/temp directory from an external API

$response = craft()->assets->insertFileByLocalPath(
    $tempPath,
    $photo['FileName'],
    $folderId,
    AssetConflictResolution::Replace
);

// if the response is a success, get the file id
if ($response && $response->isSuccess()) {
    $fileIds[] = $response->getDataItem('fileId');
}

In this example $photo[] array is the response from the api with all photo information. What I need to do is also save $photo['PhotoId'] to a field I have setup on the photo asset source in Craft.

I can't however find an example of how to achieve this. Does anyone know how?

Dave Coggins
  • 588
  • 3
  • 12

1 Answers1

6

To save a custom field value on an Asset, you'll first need to pull the actual AssetFileModel, set the custom attribute on the Asset's ContentModel, and finally re-save the Asset.

The following example assumes you've set a field photoId on your asset source:

$fileId = $response->getDataItem('fileId');
$asset = craft()->assets->getFileById($fileId);
$asset->getContent()->setAttribute('photoId', $photo['PhotoId']);
$success = craft()->assets->storeFile($asset);
Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69