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?

6
+50

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);
| improve this answer | |

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.