Context: For a redesign and port to CraftCMS, I need to import the content from a blog hosted on another platform with a lot of content (over 500 posts and over 3000 images).

Strategy: To import the images from external URLS, I have written a simple "dedicated" plugin which uses the technique described here and relies on craft()->assets->insertFileByLocalPath().

Issue: To make sure each import uploads the latest version of the images, I pass AssetConflictResolution::Replace as fourth argument to the method. This works perfectly the first time I run the import, but dies when files were uploaded before and there is a filename conflict:

Trying to get property of non-object
[...] $source = craft()->assetSources->getSourceTypeById($theNewFile->sourceId);

I am not sure why this error occurs, but I suspect it is because newly imported files are not uploaded yet at the time Craft tries to resolve the conflict.

Possible solutions: I tried to handle conflicts manually, by first deleting the existing file with craft()->assets->deleteFiles($response->getDataItem('fileId'), true), and then re-uploading the new file with insertFileByLocalPath but no success...

Since the target assets source is reserved for the imported images, I also thought about dumping all files in the target assets source before the import starts. But that would cause problems if I want to import only a subset of all the post images (very likely since the import needs time to execute).

Question: How can I work around this error?

The solution should make sure:

  1. newly uploaded files always replaces existing files with the same filename.
  2. partial imports don't remove unrelated files that were uploaded before.
  • Have you observed what the value of "$theNewFile" is when uploading for a second time? The line before that is: $theNewFile = $this->getFileById($theNewFileId); so perhaps the issue is actually with the getFileById method.
    – JBB
    Oct 31 '16 at 6:01
  • Without seeing the actual plugin code (at least the method) it's hard to tell what's going on. Can you post some code on github and link to it for reference or, better yet, just post it here? Oct 31 '16 at 7:20
  • Did you find a solution? Experiencing something alike and are curious of what you did to fix it
    – Erik Weber
    Feb 15 '19 at 7:41

Your Answer

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

Browse other questions tagged or ask your own question.