From 742bd81b7c1b68ed9e7ecc985f0360dd09ae72e8 Mon Sep 17 00:00:00 2001
From: Eric Bremner <ebremner@uwaterloo.ca>
Date: Mon, 29 Nov 2021 16:31:14 +0000
Subject: [PATCH] ISTWCMS-5204: restricting the types of crops on the media
 upload based on node

---
 uw_cfg_common.module | 43 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)

diff --git a/uw_cfg_common.module b/uw_cfg_common.module
index 1288002e..f1970ee9 100644
--- a/uw_cfg_common.module
+++ b/uw_cfg_common.module
@@ -756,6 +756,49 @@ function uw_cfg_common_form_alter(array &$form, FormStateInterface $form_state,
       $form['field_uw_meta_tags']['widget'][0]['twitter_cards']['twitter_cards_page_url']['#access'] = FALSE;
     }
   }
+
+  // If we are on the media upload form, we want to restrict
+  // what crops are available.
+  if ($form_id == 'media_library_add_form_upload') {
+
+    // If the crop widget is on the form, unset certain crops.
+    if (isset($form['media'][0]['fields']['field_media_image']['widget'][0]['#crop_list'])) {
+
+      // Get the parameters from the request, this was the only
+      // way to get out what the bundle was.  Since this is a new
+      // form call from media_library, we could not use get current
+      // path or uri, since it would only return /media_library.
+      // The media library parameters has everything listed for the
+      // node and the node types.
+      $media_lib_parameters = \Drupal::request()->query->get('media_library_opener_parameters');
+
+      // If there are media lib parameters, process them.
+      if ($media_lib_parameters) {
+
+        // If there is a bundle on the parameters, continue
+        // to process.
+        if (isset($media_lib_parameters['bundle'])) {
+
+          // If this is a contact, remove all the responsive crops.
+          // If anything else, remove the portrait crop.
+          if ($media_lib_parameters['bundle'] == 'uw_ct_contact') {
+            foreach ($form['media'][0]['fields']['field_media_image']['widget'][0]['#crop_list'] as $index => $crop) {
+              if ($crop !== 'uw_crop_portrait') {
+                unset($form['media'][0]['fields']['field_media_image']['widget'][0]['#crop_list'][$index]);
+              }
+            }
+          }
+          else {
+            foreach ($form['media'][0]['fields']['field_media_image']['widget'][0]['#crop_list'] as $index => $crop) {
+              if ($crop == 'uw_crop_portrait') {
+                unset($form['media'][0]['fields']['field_media_image']['widget'][0]['#crop_list'][$index]);
+              }
+            }
+          }
+        }
+      }
+    }
+  }
 }
 
 /**
-- 
GitLab