Skip to content

Instantly share code, notes, and snippets.

@adrexia
Last active August 29, 2015 14:04
Show Gist options
  • Save adrexia/3c22112811e4e90a5c51 to your computer and use it in GitHub Desktop.
Save adrexia/3c22112811e4e90a5c51 to your computer and use it in GitHub Desktop.
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 %>
@adrexia
Copy link
Author

adrexia commented Jul 22, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment