Populate Image & Image List Fields with Bolt CMS Programatically

163 Views Asked by At

I am attempting to create entries programaticaly in Bolt 4. I have managed to create basic text entries fine which covers the majority of fields I need to fill in however unsure how to go about image and image list types.

$content->setFieldValue('name', 'Test Name');

Works fine for most fields as stated but images field types looks like below in database and am unsure what the "Bolt / Symfony / Doctrine" way of generating below is:

{"media":11,"filename":"entity\/year\/month\/image.jpg","alt":"","0":""} 

Which looks like some JSON formatted to contain a media ID, file path and an alt attribute. I'm guessing image lists are similar but with multiple of above but hoping there is a function I can use to generate this output as unsure how I would grab media ID etc.

Am assuming I may need to upload a file temporarily from an external URL and provide this to some function however cannot find any examples. Any help would be much appreciated.

1

There are 1 best solutions below

0
harri On

Not quite sure on this but will answer anyway as it works and may help someone else, but would be good to clear some of the bits up.

Example of an Image:

//not sure what goes in media here but blank seemed to not work here but a 7 did as looked at example in database however worried this is wrong and should be an Id
$image = array('media' => '7', 'filename' => $filename, 'alt' => $image['Alt'], '0' => '');

$imageJSON = json_encode($image);
$content->setFieldValue('image', $image);

Example of an Image List:

$images = array();

foreach ($images as $image) {
     $ImageId = $image['id'];
     //images may be already on system but I had to download them here 
     if ($fileName = $this->downloadImage($propertyFile->{'url'}->__toString(), $ImageId)) {
         //not sure what goes in media here but seemed to work blank for imagelist type and unsure what the 0 is on the end either
         $image[] = array('media' => '', 'filename' => $filename, 'alt' => $image['Alt'], '0' => '');  }
}

$imageJSON = json_encode($image);
$content->setFieldValue('gallery', $image);