Entity JS

Entity JS allows for Javascript layer access to some commonly used entity-related functions such as EntityFieldQuery.

This is achieved through Drupal menu callbacks and jQuery $.ajax calls.

Note: jQuery's jqXHR Object uses the .done() method that requires later versions of jQuery (1.5+) than what currently ships with Drupal 7. In order to use these examples, we recommend installing jQuery Update. For more on .done(), review the .promise() method jQuery API docs.

entity_create

Create an entity by providing a type and an array of arguments. Shown printing response below.

values = {
    "name": "username", 
    "mail": "username@example.com",
}
entity_create('user', values).done(function(data) { console.log(data); });

Uses a $.post callback URL: /entity_create/[entity_type]

entity_render_view

Return a rendered entity using a view mode. Shown printing HTML to console below.

entity_render_view('node', 1, 'default').done(function(data) { console.log(data); });
Uses a $.get callback URL: /entity_js_drupal_render_entity_view/[entity_type]/[entity_id]/[view_mode]

Querying to get a list of taxonomy terms or nodes using EntityFieldQuery

This belongs inside your module code.

You can get a collection of nodes matching particular parameters by using EntityFieldQuery, instead of writing an SQL statement. I had a hard time getting all the syntax together, so here are a couple of simple samples:

// We use the machine name to ensure we have the proper vocab
// that is not fixed to a specific vid on a installation.

// Define this outside of the two conditions to avoid PHP notices.
$term_options_list = array();      
if ($range_vocab = taxonomy_vocabulary_machine_name_load('range')) {
  $efq = new EntityFieldQuery();
  $result = $efq->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $range_vocab->vid)
    ->propertyOrderBy('weight')
    ->execute();
  if (!empty($result['taxonomy_term'])) {
    // The results contain an array of entity stubs keyed by {term}.tid.
    // The stub only has {term}.tid and vocabulary_machine_name.
    $first_term_stub = current($result['taxonomy_term']);
    $first_term_tid = key($result['taxonomy_term']);

    // To load all terms.
    $terms = taxonomy_term_load_multiple(array_keys($result['taxonomy_term']));
    // To generate an options list.
    foreach ($terms as $term) {
      // To hook into i18n and everything else, use entity_label().
      $term_options_list[$term->tid] = entity_label('taxonomy_term', $term);
      // Single language, no term label alters.
      $term_options_list[$term->tid] = $term->name;      
    }
  }
}
// IMPORTANT. This was for a select list that expects raw values.
// If ANYTHING else is required, escape the term names, either here
// or where the name is used.
$safe_term_options_list = array_map('check_plain', $term_options_list);

Subscribe with RSS Subscribe to RSS - Entity Field Query