silverstripe-framework/docs/en/02_Developer_Guides/00_Model/03_Lists.md
Aaron Carlino 6888901468
NEW: Update docs to be compliant with Gatsby site (#9314)
* First cut

* Temporarily disable composer.json for netlify build

* POC

* New recursive directory query, various refinements

* Fix flexbox

* new styled components plugin

* Apply frontmatter delimiters

* Mobile styles, animation

* Search

* Redesign, clean up

* Nuke the cache, try again

* fix file casing

* Remove production env file

* ID headers

* Move app to new repo

* Add frontmatter universally

* Hide children changelogs

* Add how to title

* New callout tags

* Revert inline code block change

* Replace note callouts

* Fix icons

* Repalce images

* Fix icon

* Fix image links

* Use proper SQL icon
2019-11-18 17:58:33 +13:00

2.3 KiB

title summary icon
Managing Lists The SS_List interface allows you to iterate through and manipulate a list of objects. list

Managing Lists

Whenever using the ORM to fetch records or navigate relationships you will receive an SS_List instance commonly as either DataList or RelationList. This object gives you the ability to iterate over each of the results or modify.

Iterating over the list.

SS_List implements IteratorAggregate, allowing you to loop over the instance.

use SilverStripe\Security\Member;

$members = Member::get();

foreach($members as $member) {
    echo $member->Name;
}

Or in the template engine:

<% loop $Members %>
    <!-- -->
<% end_loop %>

Finding an item by value.

// $list->find($key, $value);

//
$members = Member::get();

echo $members->find('ID', 4)->FirstName;
// returns 'Sam'

Maps

A map is an array where the array indexes contain data as well as the values. You can build a map from any list

$members = Member::get()->map('ID', 'FirstName');

// $members = array(
//    1 => 'Sam'
//    2 => 'Sig'
//    3 => 'Will'
// );

This functionality is provided by the Map class, which can be used to build a map around any SS_List.

$members = Member::get();
$map = new Map($members, 'ID', 'FirstName');

Column

$members = Member::get();

echo $members->column('Email');

// returns array(
//    'sam@silverstripe.com',
//    'sig@silverstripe.com',
//    'will@silverstripe.com'
// );

ArrayList

ArrayList exists to wrap a standard PHP array in the same API as a database backed list.

$sam = Member::get()->byId(5);
$sig = Member::get()->byId(6);

$list = new ArrayList();
$list->push($sam);
$list->push($sig);

echo $list->Count();
// returns '2'

API Documentation