How To pass parameter from node to webform with custom token In Drupal 8 & 9

29th May 2022
Table of contents

In this article, I'll show you how to pass parameter from node to webform with custom token In Drupal 8 & 9.

Follow the instructions below:

Create MODULENAME.info.yml file:

name: Email Token
type: module
description: "Return email field from current node"
package: custom
core: 8.x

Create MODULENAME.module file:

The first thing we’ll need in this file is, hook_tokens_info() This is where we’ll define our tokens for Drupal. Which will make your new token available in UI.

In the second half of the code, the hook_tokens() function is used to actually make the token perform its desired function.

Example 1 if you display webform in node page:

<?php

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info()
 */

function email_etab_token_token_info()
{

    $info['tokens']['site']['email_field'] = array(
        'name' => t("Email field token"),
        'description' => t("Email field from the current node"),
    );

    return $info;
}

/**
 * Implements hook_tokens()
 */

function email_etab_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)
{
    $replacements = array();
    if ($type == 'site') {
        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'email_field':
                    $node = \Drupal::routeMatch()->getParameter('node');
                    $email_field = "";
                    if ($node){
                        if (isset($node->field_email)) {
                            $email_field = $node->field_email->getString();
                        }
                    }
                    $replacements[$original] = $email_field;

                    break;

            }
        }
    }

    return $replacements;
}

Example 2 if you open the webform in a modal:

just in your node twig page pass nid value to the modal like this.

<a class="use-ajax" data-dialog-options="{&quot;width&quot;:800}"
   data-dialog-type="modal"
   href="/form/contact?nid={{ node.nid.value|trim }}">
    <button type="button"> Contact Person</button>
</a>

and in our hook_tokens() function we get the nid of current node like this.

<?php

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info()
 */

function email_etab_token_token_info()
{

    $info['tokens']['site']['email_field'] = array(
        'name' => t("Email field token"),
        'description' => t("Email field from the current node"),
    );

    return $info;
}

/**
 * Implements hook_tokens()
 */

function email_etab_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)
{
    $replacements = array();
    if ($type == 'site') {
        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'email_field':
                    $nid = \Drupal::request()->query->get('nid');
                    $node = \Drupal\node\Entity\Node::load($nid);
                    $email_field = "";
                   if ($node){
                       if (isset($node->field_email)) {
                           $email_field = $node->field_email->getString();
                       }
                   }
                    $replacements[$original] = $email_field;
                    break;

            }
        }
    }

    return $replacements;
}

Then clear your Drupal  caches, and then your new token will be available in UI.

custom token

I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.

Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.