0

I need to dynamically change a value in Twig templates by selecting a configuration value (defined in a custom module) based on the current environment.

I did the following in a Form class, which works fine:

  /**
   * Generate parent site Base URL per environment.
   *
   * @return string
   *   The parent site Base URL used in all templates site-wide.
   */
  public function getBaseUrl() {
    $host = $this->requestStack->getCurrentRequest()->getHost();
    $config = $this->configFactory->get('clientname_cta_base.settings');
    switch ($host) {
      case 'resources.clientname.com':
        // Set $base_url to Production environment.
        $base_url = $config->get('prod_base_url') ?? [];
        break;
      case 'uatresources.clientname.com':
        // Set $base_url to UAT environment.
        $base_url = $config->get('uat_base_url') ?? [];
        break;
      case 'qaresources.agencyname.com':
      case 'qaresources.clientname.com':
        // Set $base_url to QA environment.
        $base_url = $config->get('qa_base_url') ?? [];
        break;
      default:
        // All other environments, including local, link to Dev.
        $base_url = $config->get('dev_base_url') ?? [];
        break;
    }
    return $base_url;
  }
  /**
   * Generate CTA destination URL per environment.
   *
   * @return string
   *   The CTA destination URL used in all templates site-wide.
   */
  public function getCtaUrl() {
    $config = $this->configFactory->get('clientname_cta_base.settings');
    $cta_url = $this->getBaseUrl() . $config->get('default_link_dest') ?? [];
    return $cta_url;
  }

This displays the desired URL paths in two disabled fields when the SettingsForm is loaded:

    // Active URL configuration (read-only).
    $form['clientname_cta_base_computed_base_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed base URL (Preview)'),
      '#default_value' => $this->getBaseUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];
    $form['clientname_cta_base_computed_cta_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed CTA URL (Preview)'),
      '#default_value' => $this->getCtaUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];

I could even store these updated values in configuration when the SettingsForm is submitted -- but that will not quite get me what I want.

These values need to be computed dynamically by selecting config based on the value of $host at runtime -- importing the Dev environment's computed config values to the QA environment won't do. So I am looking for a way to call the module's public methods (getBaseUrl() and getCtaUrl()) in either theme preprocess or Twig templates.

Is this approach possible? Should I have used theme settings instead?

1
  • 2
    I'd create a helper service for getBaseUrland getCtaUrl. Inject the service into the form, for Twig call the helper service in theme preprocess and pass down the values. (don't forget to add cache context/tags)
    – Hudri
    Commented Mar 16, 2021 at 19:19

1 Answer 1

0

In case you wondered, I resolved this by adding my methods to a service class, as @Hudri suggested in comments.

I can call those methods in a Form or other OO class by dependency injection of the Drupal\clientname_cta_base\Cta\Base service class:

    // Active URL configuration (read-only).
    $form['clientname_cta_base_computed_base_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed base URL (Preview)'),
      '#default_value' => $this->ctaBase->getBaseUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];
    $form['clientname_cta_base_computed_cta_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed CTA URL (Preview)'),
      '#default_value' => $this->ctaBase->getCtaUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];

The example above does not include all the dependency injection setup in the Form class, or the service class setup, services YAML config, and other steps that are well documented elsewhere.

In theme preprocess, dependency injection is not available, so I get the computed values via \Drupal::service('cta.base') like so:

/**
 * Implements template_preprocess_page().
 */
function clientname_preprocess_page(&$variables) {
  $service = \Drupal::service('cta.base');
  $config = \Drupal::config('clientname_cta_base.settings');
  $variables['computed_base_url'] = $service->getBaseUrl();
  $variables['computed_cta_url'] = $service->getCtaUrl();
  $variables['default_link_text'] = $config->get('default_link_text');
}

Note that for configuration values that are not dynamically generated, I can just access them directly in theme preprocess via \Drupal::config('clientname_cta_base.settings').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.