So I have added to properties to an image and I am having trouble accessing them, can someone point out where I’m going wrong please?
This is part of my blueprint:
files:
fields:
textalt:
label:
en: Alt Text
de: Alt Text
type: text
maincolor:
label:
en: Main Image Color
de: Main Image Color
type: text
fields:
heroimage:
label:
en: Hero Image
de: Hero Image
type: image
width: 1/3
required: true
This is how I am trying to render it on the front-end. The URL works, but the image data of maincolor doesn’t come through. It has created the needed text file inside the content folder with the image name etc… So I can see the data is saving.
<?php
if($image = $page->heroimage()->toFile()) {
$color = $image->maincolor()->html();
}
else {
$color = ''; // or use a default color here
}
The just echo the $color variable in your section styles.
Please not that you should always, always, always use this kind of check, no matter if you are dealing with images (image objects), pages (page objects) or any other object. PHP otherwise throws an error if you try to call an object method on a non-existing object.
Well, yes, because even if the field is required, its value might not yield anything, for example, the user selected an image as heroimage. Later, the image is deleted but the value is still there, but it does not point to an image anymore. Therefore, requiring a field alone is no guarantee for anything.
I’m a bit surprised you did not get any errors before. Have you turned on debugging. If not, I strongly suggest to do so in your config.php during development.
Yes debug is set on, and I’ve not had any errors regarding this bit of code/dev. It was just outputting background-color: ; with no value, the image could change and was outputting correctly, just that main color attr would not come through.
I will keep in mind to add in checks even if the field is required.