Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions

how to loop through data object set?


Reply

5 Posts   4157 Views

Avatar
mattconfusion

12 July 2010 at 7:39pm Community Member, 48 Posts

I need to get all the dataobjects of a certain kind and perform actions on each of them, not inside the page controller but in the normal page class.
So I have:

$myobjectset = DataObject::get("MyObject");
foreach ($myobjectset as $singleobject) {

...

}

Silvertripe says that I give the wrong argument, and i may be understaing why, DataObject set it's not an array. What's the correct method of looping through a dataobject set?

Avatar
Willr

12 July 2010 at 8:45pm Forum Moderator, 5511 Posts

A foreach is the correct way. It could be throwing an error if $myobjectset is an empty set so wrap the foreach in if($myobjectset) { .. }.

Also make sure its not something inside the loop throwing the error.

Avatar
mattconfusion

12 July 2010 at 9:06pm Community Member, 48 Posts

the error disappeared when I tried to use DataObject::getIterator("MyObject")
anyway i'm trying to use this structure to remove the tabs and fields in a certain page from an administration page . I created a dataobject with a field for the tab/field name, the tab path, and a checkbox

So, in the getCMSFields function i do:

$customizeInterface = DataObject::getIterator("FieldsTabs"); //in this object are stored the names of the fields to be removed
   
    if ($customizeInterface){
    foreach ($customizeInterface as $myobj) {
      
      if ($myobj->Enabled == '0'){
      
         $fields->removeFieldFromTab($myobj->TabPath, $myobj->NameOfField);      
      }
   
    }
   }

No errors, but it's not working.

Avatar
Willr

12 July 2010 at 9:12pm Forum Moderator, 5511 Posts

You shouldn't have to use getIterator(), a simple DataObject::get() should work fine as long as FieldsTabs is a subclass of DataObject. Can you post the full file and the actual error message you got originally.

Avatar
mattconfusion

12 July 2010 at 9:44pm Community Member, 48 Posts

You're right WillR. Removing getIterator make the whole function work neatly and perfectly! Just a DataObject::Get and a control over the fact that the set may be empty.
Thank you so much!