Add Images Programatically without a form

Permalink 4 users found helpful
Hi,

I'm migrating content from a site (not done by me) to a new version I'm building and I need to import and attach images to pages but I'm having a bit of trouble importing the images.
here's the code I'm trying to use:
//Create Page and add attributes to it, this part works just fine...
$parentPage = \Page::getByID('156');
$pageType = \PageType::getByHandle('event');
$template = \PageTemplate::getByHandle('events');
$entry = $parentPage->add($pageType, array(
    'cName' => $title,
    'cDescription' => '$description',
    'cHandle ' => $th->urlify($title)
), $template);
//Image Import
Loader::library("file/importer");
$importer = new \Concrete\Core\File\Importer();
$importer->import($imgSrc);
$newFile = $importer->import($imgSrc);
$entry->setAttribute('thumbnail', $newFile);


The images are in a folder on the server, I tried using a path from domain and also the server path, with identical results (nothing happens).
I also thought of importing everything through the File Manager and mapping the images with the content but I didn't find an option to get an image object by it's name, only ID.
I think It worked one time, I don't know why and got me a bit confused because I couldn't make it work again so clearly something must be wrong on that code, the weird thing is I don't think I changed anything relevant from the time it worked..

Can anyone help out?
Thanks

ESKEMA
 
ESKEMA replied on at Permalink Reply
ESKEMA
So after more tries, It's working using the full server path to the image, but now it throws an error adding it as attribute:

Fatal error: Call to undefined method Concrete\Core\File\Version::isError()


I thought using
$newFile = $importer->import($imgSrcLocal);
would return the file object, but apparently it doesn't??
ESKEMA replied on at Permalink Best Answer Reply
ESKEMA
Ok got it working finally.
here's the final code in case someone wants to do the same:
$imgSrc = '/full/server/path/to/file.jpg';
Loader::library("file/importer");
$importer = new \Concrete\Core\File\Importer();
$newFileVersion = $importer->import($imgSrc);
$newFile = $newFileVersion->getFile();
// If you want the file ID to use elsewhere
// $newFileID = $newFileVersion->getFileID(); 
$page->setAttribute('thumbnail', $newFile);
somesayinice replied on at Permalink Reply
You are a beautiful beautiful individual. I really appreciate the time you took to figure this out. Thank you so much. It has helped me out a lot.