Creating a node listing page with EntityFieldQuery

  • Developers dealing with entities and having reason to have to gather a number of entities together have praised EntityFieldQuery. See author Ryan Szrama's post about using EntityFieldQuery in Commerce.

    Ordering Entities with EntityFieldQuery is shown in this example, below. Unfortunately, the order by also acts as a filter— if the field it is being ordered by has no value, that entity is not returned.

    At the time of writing, the documentation at http://api.drupal.org/api/drupal/includes--entity.inc/property/EntityFieldQuery%3A%3Aorder/7 was useless, so we go hunting in core for an example.

    We know the front page lists nodes.

    Implementing hook menu and defining a page callback function for it in dgd7glue.module provides what we need.

    <?php
    /**
     * Implements hook_menu().
     */
    function dgd7glue_menu() {
     
    $items['biographies'] = array(
       
    'title' => 'Author biographies',
       
    'access arguments' => array('access content'),
       
    'page callback' => 'dgd7glue_profiles',
      );
     
      return
    $items;
    }

    /**
     * Menu callback for listing profile nodes for the Author biographies section.
     */
    function dgd7glue_profiles() {
    debug($field = field_info_field('field_pagecount'));
     
    $query = new EntityFieldQuery();
     
    $result = $query->entityCondition('entity_type', 'node', '=')
              ->
    propertyCondition('type', 'profile', '=')
              ->
    fieldOrderBy('field_pagecount', 'value', 'DESC')
              ->
    execute();

      return

    node_view_multiple(node_load_multiple(array_keys($result['node'])), 'teaser');
    }
    ?>

    The function node_load_multiple(), for its part, is a wrapper around entity_load_multiple()

    That created a menu item, but that doesn't mean there's a menu link in any of our menus. We create that by making a named link with the path of the menu item.

    Administration » Structure » Menus, use the add link link for Main menu (admin/structure/menu/manage/main-menu/add)

    Menu link title: Authors
    Path: biographies

    Give it a little weight, a 3, just to see where it goes.

    When saving it, Drupal takes us to a page listing the Main menu links which we can reorder via drag and drop.