Jump to:

3431 Posts in 1058 Topics by 734 members

Data Model Questions

SilverStripe Forums » Data Model Questions » how to loop through data object set?

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 4023 Views
  • mattconfusion
    Avatar
    Community Member
    48 Posts

    how to loop through data object set? Link to this post

    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?

  • Willr
    Avatar
    Forum Moderator
    5489 Posts

    Re: how to loop through data object set? Link to this post

    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.

  • mattconfusion
    Avatar
    Community Member
    48 Posts

    Re: how to loop through data object set? Link to this post

    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.

  • Willr
    Avatar
    Forum Moderator
    5489 Posts

    Re: how to loop through data object set? Link to this post

    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.

  • mattconfusion
    Avatar
    Community Member
    48 Posts

    Re: how to loop through data object set? Link to this post

    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!

    4023 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.