Jump to:

23355 Posts in 17838 Topics by 2862 members

General Questions

SilverStripe Forums » General Questions » Sort DataList by ID array

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 940 Views
  • Matulko
    Avatar
    Community Member
    9 Posts

    Sort DataList by ID array Link to this post

    hello

    i got array with last opened pages and i wanna ask you how to order items in datalist by this ordered array

    i tried to add items one by one but it doesnt work

    $idList = Session::get('recentproducts');
          
    $dl = DataList::create('ProductPage')->byIDs(array($idList[0]));
    for ($i = 1; $i < count($idList); $i++)
    {
       $dl->addMany( DataList::create('ProductPage')->byIDs(array($idList[$i])));   
    }
          
    return $dl;

    aby better idea?
    thx

  • dpde
    Avatar
    Community Member
    14 Posts
  • Matulko
    Avatar
    Community Member
    9 Posts

    Re: Sort DataList by ID array Link to this post

    thanks, but i'm not sure you understood my problem

    I have array with ID of pages
    (for example 35 43 30 32 40 50 83 52)
    and I want to create DataList with DataObjects in same order as in array

    (or maybe i dont understand how to use sort method in this case, can you show me it in code please)

  • dpde
    Avatar
    Community Member
    14 Posts

    Re: Sort DataList by ID array Link to this post

    Sorry, I misunderstood your problem, but although you can use the sort metod combined with SQL functions .

    You have an array with product ids and want to create a DataList with that products wich are in the same order like in your array?

    Try the following:

    // $idList is a comma separated string?
    $dl = DataList::create('ProductPage')->byIDs(array($idList[0]))->sort('FIELD(ID, ' . $idList . ')');

    // Plain SQL would look like
    // SELECT * FROM ProductPage WHERE ID IN (35, 43 ,30 ,32) ORDER BY FIELD (ID, 35, 43, 30, 32);

    Greetings
    dpde

  • Blackdog
    Avatar
    Community Member
    156 Posts

    Re: Sort DataList by ID array Link to this post

    If you are planning for this to be in a GridField and you wish to change the sorting I would checkout the Sortable GridField Component.

    https://github.com/UndefinedOffset/SortableGridField

    Then you can drag and drop those items into whatever order you want and just use the sort() function when you build the list.

    940 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.