in Web & Tech

FlexSlider in Drupal using Entity Field Query (EFQ)

Today I learnt how to stop using views for every little listing of entities while staying away from hacking SQL queries manually.

I’m a bit ashamed I haven’t had a look at the infamous EntityFieldQuery class this far.

Here’s my example that builds and inserts a FlexSlider slideshow within my page.tpl.php only for the front page.

In my case FlexSlider is installed and registered as a Library using Libraries and the FlexSlider module (making it possible to load the necessary assets using drupal_add_library

 * We're building our FlexSlider slidehow using Entity Field Queue, so we can
 * keep everything in code and don't need the overhead that comes with views (

// Flexslider should only appear on the front page
if($is_front) :
  // load the necessary library
  drupal_add_library('flexslider', 'flexslider');

<div class="row flex-wrap">
  <div class="twelve columns">
    <div class="main-slider flexslider">
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'node')
          ->propertyCondition('status', 1)
          ->propertyCondition('type', array('slide'))
          ->propertyOrderBy('created', 'DESC')
          ->range(0, 5);

        $result = $query->execute();
        $nodes = node_load_multiple(array_keys($result['node']));

        <ul class="slides"> 
        <?php foreach ($nodes as $slide) : ?>
            $slider_image = field_view_field('node', $slide, 'field_slide_bild', 'default');
            $slider_link = field_view_field('node', $slide, 'field_slide_link', 'default');


            <div class="slide-image">
              <?php print render($slider_image); ?>
            <div class="slide-text">
              <h2><a href="<?php print $slider_link; ?>"><?php print render($slide->title); ?></a></h2>

        <?php endforeach; ?>
    </div><!-- /.main-slider -->

<?php endif; ?>

This basically lists the 5 latest published nodes of type slide.

And don’t forget to call FlexSlider:

jQuery(window).load(function() {
  if(jQuery('.main-slider').length > 0) {
      animation: "fade",               
      animationLoop: true,
      directionNav: true,
      controlNav: false
  } // end: if slide exists in DOM
}); // end: window load

Further Reading & Useful Resources

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)