3

I have the following code in Drupal 6.

drupal_add_js(array(
  'take_control_fb' => array(
      //          'pubKey' => variable_get('take_control_public_key', ''),
      'dataUrl' => base_path() . 'admin/build/take_control/fb/getfiles',
      'appUrl' => take_control_app_url(),
      'appDir' => $appDir,
      'extPath' => $extpath,
      'zipMimes' => take_control_zip_mimes(),
      'dirSeparator' => DIRECTORY_SEPARATOR,
      'validationString' => $validationString,
      'validationToken' => drupal_get_token($validationString),
      'curUserId' => fileowner(file_directory_path()))), 'setting');

I need to convert this, since drupal_add_js() is removed from Drupal 8. I can't use this to pass PHP variables to modulename.js file. How can I pass the PHP variable to JavaScript code?

3

In Drupal 8 drupal_add_css(), drupal_add_js() and drupal_add_library() have been removed, and we are supposed to use #attached.

$page['#attached']['library'][] = 'fluffiness/cuddly-slider';
$page['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

More details about how JavaScript can be added in Drupal 8 can be found in https://www.drupal.org/theme-guide/8/assets#configurable-javascript.

0

In your case, you simply use the following code.

$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');

$form['#attached']['drupalSettings']['take_control_fb'] = [
  'dataUrl' => base_path() . 'admin/build/take_control/fb/getfiles',
  'appUrl' => take_control_app_url(),
  'appDir' => $appDir,
  'extPath' => $extpath,
  'zipMimes' => take_control_zip_mimes(),
  'dirSeparator' => DIRECTORY_SEPARATOR,
  'validationString' => $validationString,
  'validationToken' => \Drupal::csrfToken()->get(),
  'curUserId' => fileowner($stream_wrapper_manager->getViaScheme(file_default_scheme())->getDirectoryPath())
];

Notice that I also replaced drupal_get_token(), which has been replaced from a service, and file_directory_path(), which doesn't exist since Drupal 7.

I am assuming your code is used in a form builder; if you use it in another context, replace $form with the variable containing the render array.

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.