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.

Template Questions /

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

Problem looping through items in array


Go to End


3 Posts   1928 Views

Avatar
John Broadwater

Community Member, 2 Posts

19 September 2016 at 11:35pm

Edited: 19/09/2016 11:42pm

My class testPage.php looks like this:

<?php
class testPage extends Page {

private static $db = array(

'Location1' => 'Text',
'Location2' => 'Text',
'Location3' => 'Text'

);

public function getCMSFields() {

$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Content.Locations', TextField::create('Location1','Location #1'));
$fields->addFieldToTab('Root.Content.Locations', TextField::create('Location2','Location #2'));
$fields->addFieldToTab('Root.Content.Locations', TextField::create('Location3','Location #3'));

return $fields;

}

}

And my template (testPage.ss) looks like this:

<ul>

<script type="text/javascript">

for ( i=1; i<4; i++ ) {

document.write('<li>$Location [ i ]</li>');

}

</script>

</ul>

I've used the CMS to add values to each location e.g. Location #1 = Ipswich. But the template doesn't return any location values. I expected it to return Ipswich as the first line item for example. But it just returns " [ i ] " as each line item. Obviously I'm doing something simple wrong. Can anyone advise please?

Avatar
swaiba

Forum Moderator, 1899 Posts

20 September 2016 at 3:09am

Have you completed the lessons, John?
This is pretty basic template stuff... "for" loops do not exist, it's more like...

<% loop $MyLocations %>
      <!-- do stuff -->
<% end_loop %>

See here... https://www.silverstripe.org/learn/lessons/adding-dynamic-content

Avatar
John Broadwater

Community Member, 2 Posts

21 September 2016 at 9:20pm

What would I loop through in this case? loop $db doesn't work