How to access node field content in a custom module?

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
SseggembeMoses's picture

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 node 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? And what function am I to use?
Or is there another way of achieving this.

Comments

You can achieve what you

cavinm's picture

You can achieve what you described with open layers

Let me try it out

SseggembeMoses's picture

Let me try it out

Tech-256

Custom menu item outputting JSON

lwanga.matovu's picture

Hi. Sorry this is late.

Assuming Drupal 7, this is how I would approach this.

1. Menu item in Custom module

function module_menu() {
$items['get-district-data'] = array (
        'page callback' => 'module_get_district_data',
      'type' =>  MENU_CALLBACK,
);
return $items;
}


function module_get_district_data() {
   /** two options here,
   *  - you can get node results from the same displayed view
     *  - OR just load all nodes of district type - let's go with this one
     *
  *  - use db_query instead of EntityFieldQuery - faster
     *
  */
    $query_result = db_query("SELECT nid FROM {node} WHERE type = :nodeType", array(':nodeType' => 'project'))->fetchAllKeyed(0,0);
    $district_nodes = node_load_multiple(array_keys($query_result));
   $districts_json = array();
foreach ($district_nodes as $district_node) {
      $district = entity_metadata_wrapper('node', $district_node);
     $districts_json = array(
           'nid' => $district->nid,
           'hazard' => $district->field_hazard->raw(),
         'alert' => $district->field_alert_level->raw()
      );
}
  drupal_json_output($districts_json);
}

2. Call JSON using jQuery/javascript

var districtJSON = $.getJSON('get-district-data');

Does this make sense?

Thanks for the solution. I

SseggembeMoses's picture

Thanks for the solution.
I had already found a solution using Leaflet.js( with some codding). But i will also try out this solution, it looks solid. Thanks for your time bro.

Tech-256

Uganda

Group organizers

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: