TransWikia.com

How to do views random sort for all the items in a pager?

Drupal Answers Asked on December 4, 2021

I created five nodes:

  • Apple
  • Pear
  • Kiwi
  • Orange
  • Cheese

Then I created a view with the following settings:

  • Show content of type Fruit
  • Display 1 item per page, use mini pager
  • Sort: Global: Random

Now I flip through the nodes one at a time as an authenticated user.

There should be five nodes, but I don’t see all 5 nodes in a random order; instead, I see some nodes twice, and other nodes not at all.

Things I tried

  • In the query settings for the view, I have tried toggling DISTINCT on/off and rebuilding the cache; it appears to have no effect.
  • I tried setting the views caching to time-based (1 hour), thinking that this would give me all the nodes arranged in a random order that changes each hour, but I still get some nodes twice and others not at all

Is there a way to sort the nodes in a random order and yet still go through the entire set?

Potential problems with random sorting that don’t affect this use case

2 Answers

After struggling with this, it seems that when you use a pager, random sort can return the same item on multiple pages. In other words, Views random sort will randomly generate a list of results on each page, and you can get repeat results among different pages.

So what do you do if you want a random sort of all view results (on all pages of the pager) with no repeats?

You have to do it yourself.

Here's what I did.

First, add an integer field, Random Int.

Then, in hook_node_presave(), set the field to a random value.

function MYMODULE_node_presave(NodeInterface $node) {
  // Randomize the order in which missed cards appear.
  $node->set('field_int_random', MYMODULE_randomize_repeat_sort());
}

/**
 * Returns a number between 1 and 1000 for randomizing sort.
 *
 * @return int
 *   A random number from 1 to 1000.
 */
function MYMODULE_randomize_repeat_sort() {
  return mt_rand(1, 1000);
}

Finally, in your view, sort by the Random Int field instead of Views random sort.

Of course, the method here only randomizes the nodes on node save. For my use case, that is sufficient, but if you want a random sort per user, etc., you will need to do it a different way.

Answered by Patrick Kenny on December 4, 2021

In your view under filter criteria, use Aggregation settings -> group results together.

This should remove your duplicate results

Answered by pr1859 on December 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP