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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

Replace And Add To Arraylist


Go to End


3 Posts   1400 Views

Avatar
aaroncaldwell

Community Member, 3 Posts

6 April 2015 at 9:25am

Hello All,

I would like to loop through an arraylist and add key/values and replace values of specific keys. What is the best practice for this? Anyone have any idea how to do this. I'm struggling to find the best way to change/manipulate data from the dataobject to the template render.

my code

$Jumps = DataObject::get('JumpStart')->toArray();
   
    $Jumps = new ArrayList($Jumps);

    //loop replace specific key/value here

    return $Jumps;

Avatar
aaroncaldwell

Community Member, 3 Posts

6 April 2015 at 10:50am

Oops! I'm an idiot. I just looped Arraylist and set the object value like so:

Does anyone know why this doesnt work when the toArray() is set on the Arraylist and not The dataobject?

cheers,

$Jumps = DataObject::get('JumpStart')->toArray();
    $Jumps = new ArrayList($Jumps);

    foreach ($Jumps as &$Jump) {
    $Jump->Description = "22 Street";
    }


    return $Jumps;

Avatar
Pyromanik

Community Member, 419 Posts

7 April 2015 at 11:20pm

You should just be able to loop the DataList adding/altering the field to the DataObject directly. Lists implement php's array interface, so work as is in foreach loops (etc.)