Hi I have a “Variation v”, what is the simplest way of getting its variation image?
Litium version: 6.2
Hi I have a “Variation v”, what is the simplest way of getting its variation image?
Litium version: 6.2
If you do something like the following snippet you will fetch the variant and from the fields take the assigned images and create the ImageModel
. ImageModel
have a simple method to take out the url for an image in correct max size.
var variant = _variantService.Get(variantId);
var imageModel = variant.Fields.GetValue<IList<Guid>>(SystemFieldDefinitionConstants.Images)?.FirstOrDefault().MapTo<ImageModel>();
var url = imageModel.GetUrlToImage(...);
Some times it is the images on the BaseProduct
that should be used instead. Then you will do the same but use the BaseProductService
to fetch that entity instead, the rest of the code is the same.
So basically this? Or should the null check be higher up in the logic?
var imageModel = variant.Fields.GetValue<IList<Guid>>(SystemFieldDefinitionConstants.Images)?.FirstOrDefault().MapTo<ImageModel>();
if(imageModel == null)
{
BaseProduct baseProduct = _baseProductService.Get(variant.BaseProductSystemId);
imageModel = baseProduct.Fields.GetValue<IList<Guid>>(SystemFieldDefinitionConstants.Images)?.FirstOrDefault().MapTo<ImageModel>();
}
That should work.
If we check how the ProductModel
is working that will take decision from the display template if that is using base product or variant url’s and if you want to use the same logic it can be better to convert the variant into the product model and from that take the image.
var variant = _variantService.Get(variantId);
var productModel = _productModelBuilder.BuildFromVariant(variant)
var imageModel = productModel.GetValue<IList<Guid>>(SystemFieldDefinitionConstants.Images)?.FirstOrDefault().MapTo<ImageModel>();
var url = imageModel.GetUrlToImage(...);