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.

General Questions

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Gridfield loop and count in template


Go to End
Reply

9 Posts   2146 Views

Avatar
vxd

25 February 2013 at 8:57pm Community Member, 16 Posts

I have a gridfield and would like to count the objects and do something if count = 2.

eg:

<% loop Objects %>
$title
if ($count = 3)
<br />

<% end_loop %>

Is the above possible?

Avatar
kinglozzer

25 February 2013 at 10:02pm (Last edited: 25 February 2013 10:05pm), Community Member, 146 Posts

<% if $Pos = 3 %>

Or if you mean the actual number of items in the list, you might be able to do:

<% if Objects.Count = 3 %>

Haven't tested that though, no idea if it'll work. If it doesn't work, you can create a function in your controller to count them and return true/false.

Avatar
Devlin

25 February 2013 at 10:04pm Community Member, 215 Posts

What you're looking for is $Pos or $MultipleOf.

<% loop Objects %>
$title

<% if Pos = 3 %>
<br /> Position #3
<% end_if %>

<% if MultipleOf(3) %>
<br /> each third iteration
<% end_if %>

<% end_loop %>

http://doc.silverstripe.org/framework/en/reference/templates#looping-over-lists

Avatar
vxd

26 February 2013 at 1:05am Community Member, 16 Posts

Thanks, just found the page too.

How about conditional statements?

<% if $Pos=="3" %> works

How about => or != I get errors when I use !=

"Sorry, there was a problem with handling your request."

Avatar
kinglozzer

26 February 2013 at 5:43am Community Member, 146 Posts

There's no built-in less than/greater than, you can implement that sort of thing by creating a function in your controller. For 'not', use:

<% if not $Pos=3 %>

See here: http://doc.silverstripe.org/framework/en/reference/templates#conditional-logic

Avatar
vxd

26 February 2013 at 9:58am Community Member, 16 Posts

Hi Kinglozzer,

Do you have an example of how to write the custom functions in the controller?

Avatar
vxd

26 February 2013 at 1:39pm Community Member, 16 Posts

Controller

function MoreThen() {
if($pos > $value) {
return TRUE;
} else {
return FALSE;
}

}

Template

If the function is outside of the loop it works and returns "1"

$MoreThen(2,1)
<% loop GalleryObjects %>
<% end_loop %>


If the function is inside of the loop if does not work. No value is returned.

<% loop GalleryObjects %>
$MoreThen(2,1)
<% end_loop %>

Avatar
vxd

26 February 2013 at 1:48pm (Last edited: 26 February 2013 1:54pm), Community Member, 16 Posts

Found it: $Top.MoreThen(2,1)

But $Pos doesn't seem to actually work.
There are 5 items so " 2 is more than 1" should be fired off twice. NOthing is returned.

<% if Top.MoreThen($Pos,2) %>
2 is more than 1
<% end_if %>

Go to Top