Custom attachment variable, doesn't added in $attachment to access via drupalSettings

Created on 18 May 2023, almost 2 years ago
Updated 24 May 2023, almost 2 years ago

Hi team,

In D7, we have used drupal_add_js with DrupalSettings for accessing php variables to javascript files, for that we have used in D7 in my custom function like below

function custom_function($data)
{
   drupal_add_js(array('test_ajax_responders' => $data), 'setting');
}

But for D9, we need to use #attached property to replace this, but how i need to pass this $data related in to $attachments.
Seems this is my custom_function and $data is populating dynamically, so hard coding with page_attachments is not a feasible and that is used for different logic

So for this custom point of view how we can attach the drupalSetting variables in to existing $attachements array to get in javascript files.
I have tried below possibilities in D9 and nothing worked out.

function custom_function($data)
{ 
        return ['#attached' => ['drupalSettings' => [ 'test_ajax_responders' => $data, ],], ];    
}
function custom_function($data) { 
     $page['#attached']['drupalSettings']['test_ajax_responders'] = $data;
     \Drupal::moduleHandler()->alter('page_attachments', $page);
}
💬 Support request
Status

Active

Component

Once

Created by

🇮🇳India mathisomu

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

Comments & Activities

Production build 0.71.5 2024