From b8a707e4c5f912a8e24d08144263cb5dd4ac48fc Mon Sep 17 00:00:00 2001 From: Eric Bremner <ebremner@uwaterloo.ca> Date: Mon, 29 Nov 2021 04:29:34 +0000 Subject: [PATCH] ISTWCMS-5204: ensuring that image styles are created so that it can be used with background images even when the image style has not be rendered on a page --- uw_cfg_common.module | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/uw_cfg_common.module b/uw_cfg_common.module index 00276188..1288002e 100644 --- a/uw_cfg_common.module +++ b/uw_cfg_common.module @@ -99,6 +99,48 @@ function uw_cfg_common_entity_presave(EntityInterface $entity) { \Drupal::service('plugin.manager.menu.link')->rebuild(); } } + + // On a node entity save, check if the responsive + // image has created the derivatives so that things + // like hero images will load when no image has yet + // been rendered. If we do not do this, most hero + // images will not work. + if ($entity->getEntityTypeId() == 'node') { + + // If there is a hero image, continue to process. + if ($image = $entity->field_uw_hero_image) { + + // Get the value of the image field. + $image = $entity->field_uw_hero_image->getValue(); + + // Load the file from the hero image. + $file = \Drupal::entityTypeManager() + ->getStorage('file') + ->load($image[0]['target_id']); + + // Load the image styles that are needed for the hero. + $uw_styles = \Drupal::service('uw_cfg_common.uw_service')->uwGetResponsiveImageStyles(); + + // Step through each of the image styles and ensure that + // the derivative is created. + foreach ($uw_styles as $uw_style) { + + // Load the image style. + $style = \Drupal::entityTypeManager() + ->getStorage('image_style') + ->load($uw_style); + + // Get the styled image derivative. + $destination = $style->buildUri($file->getFileUri()); + + // If the derivative doesn't exist yet (as the image style may have been + // added post launch), create it. + if (!file_exists($destination)) { + $style->createDerivative($file->getFileUri(), $destination); + } + } + } + } } /** -- GitLab