3

I'm working on importing entries from EE to Craft. I started with the craftimport plugin, and I am expanding it to do a bit more. One of the things I need is to save an image from a remote URL into an entry's assets field.

So far I've only managed to save it to disk, and then I can go into Craft admin and index the assets folder, and re-run the import, which will save the relation between the image and the entry using this:

$command = craft()->db->createCommand();
$imgRecord = $command
            ->select('id')
            ->from('assetfiles')
            ->where(array("AND", "filename='" . $images[0]['filename'] . "'", "folderId=2"))
            ->queryRow();

if ($imgRecord['id']) {
    $imgFieldRecord = FieldRecord::model()->findByPk($imgFieldId);
    $imgFieldModel = FieldModel::populateModel($imgFieldRecord);
    craft()->relations->saveRelations($imgFieldModel, $entryModel, array($imgRecord['id']));
}

So I'm wondering if it's possible to do this whole thing in one run instead of two? I guess the only thing the indexing does is look for images and store them in the database. But I can't seem to find anything in the documentation that tells me how to do it.

3

Your best bet to get the image in as an Asset in one go would be to use

$response = craft()->assets->insertFileByLocalPath($fileLocation, $fileName, $targetFolderId, AssetConflictResolution::KeepBoth);
  • $fileLocation would be the file's location on the disk
  • $fileName is the desired file name
  • $targetFolderId is the Assets folder, obviously. Look it up in craft_assetfolders table
  • The last argument is how to resolve any naming conflicts.

This will return an AssetOperationResponseModel object.

$fileId = $response->getDataItem('fileId');

This will get you the file Id. For an in-action example, see AssetsController::actionExpressUpload()

Note: This will copy the file to the location. This method is intended for importing a file into an Assets source from a different location, say, a temporary folder. It will probably work alright if the file is already in it's intended place, but I still feel like I need to warn you about this

You can also use this to import images to external sources, by the way.

| 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.