diff --git a/core/model/DataList.php b/core/model/DataList.php index 6d3dd7c67..6f69b1a54 100644 --- a/core/model/DataList.php +++ b/core/model/DataList.php @@ -400,6 +400,41 @@ class DataList extends DataObjectSet { function removeDuplicates() { user_error("Can't call DataList::removeDuplicates() because its data comes from a specific query.", E_USER_ERROR); } + + /** + * Necessary for interface ArrayAccess. Returns whether an item with $key exists + * @param mixed $key + * @return bool + */ + public function offsetExists($key) { + return ($this->getRange($key, 1)->First() != null); + } + + /** + * Necessary for interface ArrayAccess. Returns item stored in array with index $key + * @param mixed $key + * @return DataObject + */ + public function offsetGet($key) { + return $this->getRange($key, 1)->First(); + } + + /** + * Necessary for interface ArrayAccess. Set an item with the key in $key + * @param mixed $key + * @param mixed $value + */ + public function offsetSet($key, $value) { + throw new Exception("Can't alter items in a DataList using array-access"); + } + + /** + * Necessary for interface ArrayAccess. Unset an item with the key in $key + * @param mixed $key + */ + public function offsetUnset($key) { + throw new Exception("Can't alter items in a DataList using array-access"); + } } diff --git a/tests/model/DataObjectTest.php b/tests/model/DataObjectTest.php index 49a1bd400..428fc1a30 100755 --- a/tests/model/DataObjectTest.php +++ b/tests/model/DataObjectTest.php @@ -1098,6 +1098,15 @@ class DataObjectTest extends SapphireTest { $this->assertTrue(DataObject::get("DataObjectTest_SubTeam")->canSortBy("Title")); $this->assertTrue(DataObject::get("DataObjectTest_SubTeam")->canSortBy("SubclassDatabaseField")); } + + function testDataListArrayAccess() { + $list = DataObject::get("DataObjectTest_Team")->sort("Title"); + + $this->assertEquals("Subteam 1", $list[0]->Title); + $this->assertEquals("Subteam 3", $list[2]->Title); + $this->assertEquals("Team 2", $list[4]->Title); + + } }