0

We would like to have the URL pattern for Article content type to use article/[node:field_short_description]. In the scenario where field_short_description is not populated, we would like for the URL pattern to be article/[node:title] as a fallback.

Questions

  1. Is it possible to use the field_short_description field if populated, else use the title field without custom code?
  2. How would we do this without custom code?

We tried to use article/[node:field_short_description]|[node:title] but when both fields are populated, then both are added to the URL.

0

We found the solution using the sample found on How To Create A Custom Token In Drupal 8?

Code

/**
 * Implements hook_token_info().
 */
function my_module_token_token_info() {
  $info = [];
  $info['types']['my_token_group'] = ['name' => t('Custom Group'), 'description' => t('Custom Group')];
  $info['tokens']['my_token_group’][‘my_token’][] = 'A token to extract desired characters from Node body to be used in meta descriptions';
  return $info;
}

/**
 * Implements hook_tokens().
 */
function  my_module_token_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'my_token_group') {

    foreach ($tokens as $name => $original) {
      // Find the desired token by name.
      switch ($name) {
        case ‘my_token’:
          $node = $data['node'];
          if(is_object($node) && !$node->myFieldName->isEmpty()) {
            $token_value = $node->myFieldName->value; // or something similar.
          }
          else {
            $token_value = $node->label();
          }
          $replacements[$original] = $token_value;
          break;
      }
    }
  }
  return $replacements;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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