1

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

0

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

This should remove your duplicate results

1
  • Thanks for your answer, but that didn't work for me. I tried turning on aggregation for the view (it wasn't on before) and then making sure Published and Content type both had aggregation set to Group results together, but I still get duplicates when I click through the links. Jul 24 '20 at 15:28
0

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.

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.