I am using the following code, but the JavaScript console prints undefined
instead of the value of settings.api_key
. What is wrong in the code I am using?
libraries.yml file
stripe_files:
version: 1.x
js:
https://js.stripe.com/v2/: { type: external, minified: false }
js/custom_stripe.js: {}
dependencies:
- core/jquery
- core/drupal.ajax
- core/drupal
- core/drupalSettings
- core/jquery.once
css:
theme:
css/custom_stripe_integration.module.css: {}
JavaScript file
(function ($) {
Drupal.behaviors.stripe = {
attach: function (context, settings) {
alert('hello4');
console.log(settings.api_key);
}
};
})(jQuery);
Form class
/**
* @file
* Contains \Drupal\amazing_forms\Form\ContributeForm.
*/
namespace Drupal\custom_stripe_integration\Form;
use Drupal\Core;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\SharedTempStore;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Locale;
require_once 'modules/custom/donate_gateway/vendor/autoload.php';
/**
* Contribute form.
*/
class StripeSponsorForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'stripe_sponsor_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state,$nid = 0) {
$config = $this->config('custom_stripe_integration.settings');
$api_key = $config->get('stripe_api_key');
$form['#attached']['library'][] = 'custom_stripe_integration/stripe_files';
$form['#attached']['drupalSettings']['api_key'] = $api_key;
return $form;
}
}
drupalSettings
in your JavaScript code withsettings
, which is the variable passed toattach()
.