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   4186 Views

Avatar
mattconfusion

Community Member, 48 Posts

12 July 2010 at 7:39pm

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

Forum Moderator, 5513 Posts

12 July 2010 at 8:45pm

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

Community Member, 48 Posts

12 July 2010 at 9:06pm

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

Forum Moderator, 5513 Posts

12 July 2010 at 9:12pm

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

Community Member, 48 Posts

12 July 2010 at 9:44pm

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!