0

Drupal 8

I have a View that uses the View result counter starting at '0'. It works great, except for the fact that when you change to Next page the counter doesn't start off at '0' again, but rather continues on.

I tried using Twig modulus to get a circular-list (always reset back to 0), the reason I use 10 is because my pager displays 10 items.

{{ counter % 10 }}

It doesn't work, it always prints 0 for some reason. But if I do {{ 11 % 7 }} it prints the correct result which is '4'.

Does anyone know either of these:

  • Can I force view to restart counter at '0' when it goes to other pages int he pager?
  • Why is Twig not printing the proper math result of {{ counter % 10}} ? (Keep in mind that doing things like {{ counter + 1 }} don't work either. For some reason it only works when you use only numbers like {{ 1 + 3 }} )

Thanks.

1

It doesn't work because counter is actually an object with the value as a property, that's done to properly handle markup or special characters and preventing them from being escaped multiple times.

Depending on what template you're overriding and where, you could possibly do this in twig, especially if you are where you are loop over the rows already, although that might be a bit complicated.

My/the backend developer approach would be to make your own counter views field/plugin that doesn't consider the pager. This logic happens in \Drupal\views\Plugin\views\field\Counter::getValue(). So you can copy this class into a custom module, rename to NoPagerCounter or so, and change the annotation to @ViewsField("no_pager_counter"). Then you remove the pager related part in the getValue(). Now you just need to implement hook_views_data() and define this as a field, just like views_views_data does with the counter:

  $data['views']['no_pager_counter'] = array(
    'title' => t('View result counter (no pager)'),
    'help' => t('Displays the actual position of the view result'),
    'field' => array(
      'id' => 'no_pager_counter',
    ),
  );

(Possibly with a better title/help, I just switched the ids)

Another variant of that would be to add an option for this to the existing class and provide a core patch/feature request for this. If others agree that it is useful then it might eventually get committed and you don't need to maintain custom code, but you will have to maintain the patch until then.

  • It's an excellent option (upvoting), though I ended up removing the Counter field and using preprocess_views_view_field template hook and accessing row->index. I'll be posting the answer with the code in case anyone can use it. – Chayemor Nov 28 '16 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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