SilverStripe random order for ArrayList ()

I know that we can randomly sort a DataList with the following:

 $example = Example::get()->sort('RAND()'); 

But when I try to randomly sort an ArrayList , this does not work. I can sort ArrayList by ID DESC , but not with RAND() .

Is there a way to make ArrayList randomly sort its elements?

Example:

 public function AllTheKits() { $kits = Versioned::get_by_stage('KitsPage', 'Live'); $kitsArrayList = ArrayList::create(); foreach ($kits as $kit) { if ($kit->MemberID == Member::currentUserID()) { $kitsArrayList->push($kit); } } return $kitsArrayList; } 

On the page:

 public function getKitsRandom() { return $this->AllTheKits()->sort('RAND()'); } 

This does not work in the template with <% loop KitsRandom %>

+5
source share
2 answers

Not really. This is the best workaround I can come up with:

 foreach($myArrayList as $item) { $item->__Sort = mt_rand(); } $myArrayList = $myArrayList->sort('__Sort'); 
+4
source

You can randomly sort the DataList before DataList over it, instead of randomly sorting the ArrayList :

 public function AllTheKits($sort = '') { $kits = Versioned::get_by_stage('KitsPage', 'Live', '', $sort); $kitsArrayList = ArrayList::create(); foreach ($kits as $kit) { if ($kit->MemberID == Member::currentUserID()) { $kitsArrayList->push($kit); } } return $kitsArrayList; } public function getKitsRandom() { return $this->AllTheKits('RAND()')); } 

As an additional note, you can filter the source DataList to retrieve the KitsPages that are related to this MemberID in the Versioned::get_by_stage :

 public function AllTheKits($sort = '') { $kits = Versioned::get_by_stage( 'KitsPage', 'Live', 'MemberID = ' . Member::currentUserID(), $sort ); $kitsArrayList = ArrayList::create($kits); return $kitsArrayList; } 

You can also just do this:

return KitsPage::get()->filter('MemberID', Member::currentUserID())->sort('RAND()');

When you browse the site live you only get live KitPages .

+3
source

Source: https://habr.com/ru/post/1266088/


All Articles