CedricParkerLewis
CedricParkerLewis

Reputation: 403

Drupal custom modules and cache issue

We created a few custom custom modules for a Drupal site and we have the following issue : each time we create or update a content (whatever it is), the content generated by the custom modules disappears. We have to clear all caches to get this content to appear again.

As it is our first experience with Drupal, we are certainly missing something but we don't know what.

Any help would be greatly appreciated!

Below is the code of one of these custom modules:

File website_actualites.module

    <?php
/**
 * Implements hook_block_info().
 */
function website_actualites_block_info() {
    $blocks['website_actualites'] = array(
        'info' => t('website_actualites'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function website_actualites_block_view($delta = '') {
    $aDelta = explode('+', $delta);
    $nbActualite = 2;
    if (!empty($aDelta[1])) {
        $nbActualite = $aDelta[1];
    }
    $block = null;
    switch ($aDelta[0]) {
        case 'website_actualites':
            $block['content'] = _website_actualites_sweet_block_content($nbActualite);
            break;
    }
    return $block;
}

/**
 * Callback implemented by hook_block_view().
 */
function _website_actualites_sweet_block_content($nbActualite=2) {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_mise_en_avant', 'value', 1)
        ->propertyOrderBy('created', 'DESC')
        ->range(0, $nbActualite)
        ->addMetaData('account', user_load(1));
    $result = $query->execute();

    // width col pour nb actu=2 : 4,8
    // width col pour nb actu=4: 2,4,2,4

    $colWidthEven=4;
    $colWidthOdd=8;
    if (4 == $nbActualite) {
        $colWidthEven=2;
        $colWidthOdd=4;
    }

    $data = array();
    if (isset($result['node'])) {
        $nids = array_keys($result['node']);
        $items = entity_load('node', $nids);

        $i=0;
        foreach ($items as $item) {
            $colWidth=$colWidthOdd;
            if (0 == $i%2) {
                $colWidth = $colWidthEven;
            }
            $i++;
            $data[$item->nid] = array(
                'title' => $item->title,
                'tags' => isset($item->fielsTags['und'][0]) ? $item->fielsTags['und'][0] : '',
                'body' => isset($item->body['und'][0]['value']) ? $item->body['und'][0]['value'] : '',
                'image' => isset($item->field_image['und'][0]) ? $item->field_image['und'][0] : '',
                'nid' => $item->nid,
                'col-width' => $colWidth,
                'alias' => drupal_get_path_alias('node/'.$item->nid)
            );
        }
    }

    $static_title = t('Static Title');
    $static_content = 'static content';



    return theme('website_actualites_output', array(
            'title' => $static_title,
            'content' => $static_content,
            'data' => $data
        )
    );
}

File website_actualite-sweet--block.tpl.php

<?php

foreach ($data as &$row) {
    $url = drupal_get_path_alias('node/' . $row['nid']);
    $imageWrapper = file_stream_wrapper_get_instance_by_uri($row['image']['uri']);
    if (is_object($imageWrapper) && is_callable(array($imageWrapper, 'getExternalUrl'))) {
        $imageUrl = $imageWrapper->getExternalUrl();
        print '<div class="col-sm-'.$row['col-width'].'">
                    <div class="img">
                        <a href="/'. $url .'"><img src="' . $imageUrl . '" class="img-responsive" alt="image description"></a>
                    </div>
                    <p><a href="/'. $url .'">' . $row['title'] . '</a></p>
                </div>';
    }
}

Upvotes: 1

Views: 1424

Answers (1)

GroovyCarrot
GroovyCarrot

Reputation: 514

first of all there are several problems with this code. If you're going to use Drupal then you need to stick to Drupal coding standards. Avoid using camel casing for variables, instead you should use underscores. Also you should use 2 spaces for indentation.

In your block info function you define a single block however you assign it to an unassigned variable:

// Define $blocks first.
$blocks = array();

$blocks['website_actualites'] = array(

Next issue is that you call hook_block_view($delta), this call will be fired for every block delta, and regardless of the block delta you are setting it to null (also for future reference should be NULL):

$block = null;

So Drupal is building the render array for each block, and you are wiping all the data. You are doing this because you are trying to use the block delta as a way to pass a parameter into your block with a delta like website_actualites+10. Blocks aren't designed to work this way and delta's are meant to be static so that Drupal can keep track of them in the database and perform the correct caching according to your cache flag. You've defined the delta website_actualites in your hook_block_info() but Drupal has no knowledge or configuration information for any other block delta.

If you have a need for the same block to display varying quantities, then just define several blocks (in your hook_block_info()) and call the same helper function as you are now. If there is a requirement to configure the block then you should use the hook_block_configure() API

Now the data you are passing into your theme function, you are extracting field data from the node object using: $item->field_image['und'][0]. A couple of things here: fields are provided by the field module which has an extensive API to retrieve field data. You should use field_get_items() instead, which will return an array of all items associated with that field for that entity (as fields can be multi-valued) and handles the language for you. The other thing is never use 'und' use the constant LANGUAGE_NONE.

$body = field_get_items('node', $item, 'body');
$field_image = field_get_items('node', $item, 'field_image');
$field_tags = field_get_items('node', $item, 'field_tags');

$data[$item->nid] = array(
  'title' => $item->title,
  'tags' => $field_tags ? $field_tags : FALSE,
  'body' => $body ? $body[0] : FALSE,
  'image' => $field_image ? $field_image[0] : FALSE,
  'nid' => $item->nid,
  'col-width' => $colWidth,
  'alias' => drupal_get_path_alias('node/'.$item->nid)
);

Another problem is that you set the $block['content'] to the result of theme('website_actualites_output', ...). Now this function will return markup, Drupal has many more calls in the chain before we need to render any markup, and the problem with calling this now is that you can't mutate your data at any point now in the build process.

In order to call theme('website_actualites_output', ...); You need to have defined this theme function in a hook_theme() call, presumably you have done this in another module, which is perfectly fine but remember to add a dependency on that module in your module.info file. What you really want to be doing is just adding instructions to the Drupal build, not markup:

return array(
  '#theme' => 'website_actualites_output',
  '#title' => $static_title,
  '#content' => $static_content,
  '#data' => $data
);

So then we come to your template, you have a lot of logic in your template and they are only intended for displaying content with markup, with ideally no, or minimal computation if any. A theme function has a hook_preprocess() call before hook_process(), and then the variables are passed into the template.

You are using this theme function to loop over the $data variable to display markup - ideally a theme function would be just that markup with the variables already processed and passed into it:

website-actualites-output--child.tpl.php

<div class="col-sm-<?php print $col_width; ?>">
  <?php if ($image): ?>
    <div class="img">
      <?php print render($image); ?>
    </div>
  <?php endif; ?>
  <?php if ($title): ?>
    <p><?php print render($title); ?></p>
  <?php endif; ?>
</div>

In this example your best bet would be to have a second theme function website_actualites_output__child with the above template.

/**
 * Implements hook_theme().
 */
function website_actualites_theme() {
  $templates = drupal_get_path('module', 'website_actualites') . '/templates';
  return array(
    'website_actualites_output__child' => array(
      'path' => $templates,
      'template' => 'website-actualites-output--child',
      'variables' => array(
        'col_width' => 4, // Default col width.
        'image' => NULL,
        'title' => NULL,
      ),
    ),
  );
}

Then preprocess your current theme function:

/**
 * Implements hook_preprocess_HOOK().
 */
function website_actualites_preprocess_website_actualites_output($variables) {
  $processed_output = array();

  $data = $variables['data'];
  foreach ($data as $row) {
    $image = array(
      '#theme' => 'image',
      '#path' => file_create_url($row['image']['uri']),
      '#alt' => $image['alt'],
      '#attributes' => array('class' => array('img-responsive')),
    );

    $processed_output[] = array(
      '#theme' => 'website_actualites_output__child',
      '#col_width' => $row['col-width'],
      '#image' => array(
        '#theme' => 'link',
        '#path' => 'node/' . $row['nid'],
        '#text' => $image,
        '#options' => array('HTML' => TRUE),
      ),
      '#title' => array(
        '#theme' => 'link',
        '#path' => 'node/' . $row['nid'],
        '#text' => $row['title'],
      ),
    );
  }

  // Reassign the $data variable so that we can just render() it.
  // var_dump($processed_output) to get a better idea what's going on here.
  $variables['data'] = $processed_output;
}

Then all you need to do in your current template is to:

<?php if ($data): ?>
  <?php print render($data); ?>
<?php endif; ?>

And you can wrap this is whatever markup you like.

The Drupal learning curve is high, but remember that if someone else were to maintain this code after you, they would expect that you adhere to Drupal coding standards and followed the process upon which Drupal is built.

Further reading: Render Arrays in Drupal 7

Hope this information helps and makes it a bit clearer.

Upvotes: 1

Related Questions