I have a content type called districts and i have created the following fields

  • district geojson(polygon values)
  • harzards (list) - heavy rain, freezing rain, storm
  • Alert level (list) - extreme, high, low

I am displaying in a view as a leaflet map. Now i would like to write a custom module that can get the field content of a nodes ie harzards and alert level and then pass them to a javascript file that will print specific colors to the districts in the view depending on the alert_level.

What is the best way to get the field content (harzards and alert_level) in to the custom module and then pass them to the javascript file? Or is there another way of achieving this. Thanks

3 Answers 3


Assuming you mean Drupal 7, just off the top of my head, implement something like hook_node_view() and attach the Javascript via the #attached element. I am frequently silly in my hook options, so someone may have a better one to suggest.

  • Do you know how to get the field contents into the custom module so that i can add them to the javascript file using drupal_add_js() Mar 1, 2016 at 10:46
  • hook_node_view() is passed the complete $node object. Avoid drupal_add_js. It is deprecated. Use #attached if possible.
    – cilefen
    Mar 1, 2016 at 16:05

Not sure if what you need, but you can always load the node (the object of your content type) with:

$district = node_load($district_nid);

And then you have access to it's fields:

$harzard = $district->field_harzard['und'][0]['value];

The last line may change, depending on your language configuration.

OR as suggested by @Juraj Nemec, use Drupal's function to access fields:

$harzard = field_get_items('node', $district, 'field_harzard');
  • It is not recommended to use direct access to fields like this (because of language and other factors). Instead use field_get_items('node', $district, 'field_harzard'); Mar 2, 2016 at 0:29
  • Thanks for the suggestion! I'll edit my answer with this function Mar 2, 2016 at 13:50

Why not continue using the same View that builds the leaflet map? Doing so seems simplest and most 'standard' in the Drupal world.

Three options (at least) come to mind for setting your styling if you stick with Views:

  1. use the Views Conditional module.
  2. rewrite the field_hazzard output to account for your conditions.
  3. call the View in your custom module using views::getView.

Here's a step-by-step tutorial that accomplishes something similar using the 2nd option. It looks pretty good and broadly applicable: Conditional Formatting of Data In Drupal Views.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.