adrexia
7/19/2014 - 2:10 PM

Silverstripe - Divide an SS_List object into groups of x items

Silverstripe - Divide an SS_List object into groups of x items

Divide an SS_List object into groups of x items

::PHP (on page, or controller, or whatever the object is that has the relation to the list)

    /**
     * Method to divide data into columns.
     * @return array
     */
    public function splitIntoCols() {
        $number = $this->splitByNum;
        if(!$number){
            $number = 1;
        }
        $result = array();
        $i = 1;
        foreach ($this->List() as $item) {
            $key = (int)ceil($i / $number);
    
            if (array_key_exists($key, $result)) {
                $result[$key]->push($item);
            } else {
                $result[$key] = new ArrayList(array($item));
            }
            $i++;
        }
    
        return $result;
    }
    
    /**
     * Similar to {@link splitIntoCols()}, but returns
     * the data in a format which is suitable for usage in templates.
     * 
     * @param  string $children Name of the control under which children can be iterated on
     * @return ArrayList
     */
    public function SplitList($children = 'Children') {
        $grouped = $this->splitIntoCols();
        $result  = new ArrayList();
    
        $number = $this->splitByNum;
        $i = 1;
    
        foreach ($grouped as $indVal => $list) {
            $key = (int)ceil($i / $number);
            $Newlist = GroupedList::create($list);
            $result->push(new ArrayData(array(
                $key    => $indVal,
                $children => $Newlist
            )));
            $i++;
        }
    
        return $result;
    }

::ss

    <% if $SplitList %>
        <% loop $SplitList %>
            <% loop $Children %>
                $Title
            <% end_loop %>
    <% end_loop %>
    <% end_if %>