1

I have a view that collect fields of some content type and one of those fields is image field. I can set image style for that image from view editing page and that image in every row will have that same image style.

Now I need to set different image style for some rows. I.e. first row image should have style "ep1", second "ep2" and third and fourth "ep3".

What I tried so far is pre-processing image field like this:

function hook_preprocess_views_view_field(&$variables)
{
  $view = $variables['view'];
  $field = $variables['field'];


  switch ($view->id()){
    case 'view_id':
      switch($field->field) {
        case 'image_id':
          $rowIndex = $variables["field"]->view->row_index;

          $variables['field']->options["settings"]["image_style"] = 'thumbnail';
          break;
      }
      break;
  }
}

This way I can collect row number, but setting this "thumbnail" style is not working. On front-end I'm still getting image style set from view.

Then I tried preprocessing image formatter like this:

function cr_common_preprocess_image_formatter(&$variables) {
  if ($variables['image']['#style_name'] === 'style_to_change') {
    $variables['image']['#style_name'] = 'thumbnail';
  }
}

And this way style really is changed, but I don't' have info on current view row so it can be used only for setting random image styles or something.

1 Answer 1

1

You could try a different approach, via the Views UI, adding the same image field 3 times, and assigning each of these different image styles.

Add a View result counter field, this will let you know the row number.

Then on template/twig file print image field that was assigned x image if counter (this is the twig variable name for View result counter) equals y.

1
  • Not exactly but I was looking for, but useful.
    – MilanG
    Mar 3, 2020 at 10:35

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.