How the hell do I push data from Drupal into Javascripts (Drupal 7)

So here was my scenario:

I was creating an edit form for node type for a customer. When the node was originally submitted, the user could choose a location from a map, and the coordinates were saved in the node. And now, when a registered user is editing the node, he needs to see the map with the coordinates in place.

In order to do so, I use hook_form_alter to create a markup within the form:
$form['map_markup']['#weight'] = 16;
$form['map_markup']['#markup'] = '<div class="map-markup"><label class="control-label">Kort</label><div id="mapDiv"></div></div>';

Then I expose my data to Javascript:
$coords = [ 'xcoord' => $xcoord, 'ycoord' => $ycoord, ];
drupal_add_js($coords, 'setting');

That's all! Now I have access to : Drupal.setting.xcoord and Drupal.setting.ycoord on the client side. Very slick!

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.