Drupal Answers Asked on December 4, 2021
I created five nodes:
Then I created a view with the following settings:
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
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
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
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP