Adds redundant third party config and dependency to ever block that is edited

Created on 15 October 2024, 2 months ago

Problem/Motivation

Once the module is installed, every block that is edited gets a dependency on this module and has config added even if there is nothing set.

Steps to reproduce

Install the module and edit any block, make no changes to the 'Block Title Link Settings', and save. Export the config and the block is now dependent on the module and has redundant config:

dependencies:
  content:
    - 'block_content:basic:5d10ad91-ab51-47c1-8df3-ae6821af3671'
  module:
    - block_content
    - block_title_link
    - system
  theme:
    - THEME
third_party_settings:
  block_title_link:
    title_link_url: ''
    link_title: ''
    title_link_target: ''
    title_link_enable: 0

Proposed resolution

Use a similar solution to the Geocoder module does and remove the third party settings if nothing is set (https://git.drupalcode.org/project/geocoder/-/blob/8.x-4.x/modules/geoco...).

diff --git a/block_title_link.module b/block_title_link.module
index c56cfba..0e72974 100644
--- a/block_title_link.module
+++ b/block_title_link.module
@@ -74,6 +74,24 @@ function block_title_link_form_block_form_alter(&$form, FormStateInterface $form
     '#description' => t('Check to Enable Title Link to this Block'),
     '#default_value' => $block->getThirdPartySetting('block_title_link', 'title_link_enable'),
   ];
+  /* @uses _block_title_link_form_block_form_third_party_settings_validate() */
+  array_unshift($form['#validate'], '_block_title_link_form_block_form_third_party_settings_validate');
+}
+
+/**
+ * Validation callback for 'block_title_link_form_block_form_alter'.
+ *
+ * @param array $form
+ *   A form API form.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ *   The form state object.
+ */
+function _block_title_link_form_block_form_third_party_settings_validate(array $form, FormStateInterface $form_state): void {
+  // Don't store any settings for this field if it's not configured.
+  $block_title_link_third_party_settings = array_filter($form_state->getValue('third_party_settings')['block_title_link']);
+  if (!$block_title_link_third_party_settings) {
+    $form_state->unsetValue(['third_party_settings', 'block_title_link']);
+  }
 }
 
 /**
Feature request
Status

Active

Version

1.1

Component

Code

Created by

🇬🇧United Kingdom altcom_neil

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024