0

How to style views row layout debending on result count?

If views has 4 results then items should be placed on two rows and two columns:
| |
| |

And when views has more than 4 items - for example 6 then:
| | |
| | |

1 Answer 1

1

You could implement hook_views_pre_render and count the number of results, then apply a class to the wrapper element.

function hook_views_pre_render(&$view) {
  switch($view->name) {
    case 'MY_VIEW_NAME':
      switch($view->current_display) {
        case 'MY_DISPLAY_ID':

          $numResults = count($view->result);

          /*
            Do your logic with $numResults here
          */
          if ($numResults <= 4) {
            $grid = 2;
          }
          else {
            $grid = 3;
          }

          $view->style_plugin->options['class'] = (isset($view->style_plugin->options['class'])) ? $view->style_plugin->options['class'] . ' grid-' . $grid : 'grid-' . $grid;

          break;
      }
      break;
  }
}

So then you can style the width of the views-row under grid-2 to be 50%, and 33% width for views-row under grid-3 in your CSS.

Your View display needs to use "HTML List" format for this code to work.

11
  • Okey. I added to template.php your code and edited: "function theme_views_pre_render(&$view) { switch($view->name) { case 'front_tiles-block': switch($view->current_display) { case 'block':" But it is not adding classes. I have 4 items in front_tiles-block view.
    – hene
    Aug 13, 2014 at 11:54
  • front_tiles-block is not a valid views name. Please check you have correct names in your switch statements. $view->name refers to the machine name of your view, it only has numbers, letters and underscores. Dashes are not allowed there.
    – Beebee
    Aug 13, 2014 at 13:12
  • Ok, I exported my views and it says: $view->name = 'front_tiles'; - So changed front_tiles-block to front_tiles. But now I'm getting warning: Notice: Undefined index: class in theme_views_pre_render() (line 267 of /home/public_html/sites/all/themes/theme/template.php). And in that 267 line it has code: "$view->style_options['class'] = $view->style_options['class'] . ' grid-'.$grid;"
    – hene
    Aug 13, 2014 at 13:59
  • Nevermind the warning, are you getting the class name on the wrapper element though?
    – Beebee
    Aug 13, 2014 at 14:01
  • Nope. There is no any grid class.
    – hene
    Aug 13, 2014 at 14:07

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.