0

In my custom module I'm creating a logic with two fields.

The first field is an image and the second is date field. When I choose past date from the date field, the image field should be hidden. If the date value is present or made in future, the image will be visible.

It's working great on hook_node_view, but I can't figure out how to do this on views.

Here's my code:

<?php
function custom_alter_node_view($node, $view_mode, $langcode) {
 if ($node->type == 'hot_offers') {
    $c = strtotime($node->field_hot_offers_new_date['und'][0]['value']);
    $current_time = date("m/d/Y H:i:s");
    $d = strtotime($current_time);
    if ($c < $d) {
    $node->content['field_hot_offers_new_image']['#access'] = FALSE;
    }
  }
}

I know there's a hook_views_pre_render, but how do I create the same logic, so the image will be visible only if the date field value will be present or in future?

2
  • I would give hook_field_access a go. I think both views and node_view will take your access rule into account. api.drupal.org/api/drupal/modules!field!field.api.php/function/… Jun 9, 2014 at 12:26
  • In broad strokes, in hook_views_pre_render(&$view) you would look first at $view->name and then on the correct view, look inside its $view->result and unset or otherwise modify your image field therein based upon similar logic as above.
    – Jimajamma
    Jun 9, 2014 at 13:41

2 Answers 2

1

I've solved the puzzle and I'm sharing the solution.

function custom_alter_views_pre_render(&$view) { 
    if ($view->name == 'hot_offers') {
        //dpm($view);
foreach ($view->result as $key=>$value) {
    $c = @$value->field_field_hot_offers_new_date[0]['raw']['value'];
    $d = date("Y-m-d"); //2014-06-26
    if ($c < $d) {
    $value->field_field_hot_offers_new_image[0]['rendered']['#access'] = FALSE;
    }
  }
 }
}

The tricky part was to set the $d same format as the new_date field, otherwise the if statement logic will not work.

0

You can do it using any of the following ways.

  1. Install View PHP module and you will get a gobal php field in the views where you can write your logic as a php code.

  2. Or as Jimajamma said, in hook_views_pre_render(&$view) you can check $view->name and unset the values from $view->result.

  3. Or you can write your own views custom field handler for the image field and write your logic to display the way you want.

1
  • 1
    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – mpdonadio
    Jun 9, 2014 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.