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

Avatar
vxd

Community Member, 16 Posts

25 February 2013 at 8:57pm

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

Community Member, 175 Posts

25 February 2013 at 10:02pm

Edited: 25/02/2013 10:05pm

<% 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

Community Member, 225 Posts

25 February 2013 at 10:04pm

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

Community Member, 16 Posts

26 February 2013 at 1:05am

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

Community Member, 175 Posts

26 February 2013 at 5:43am

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

Community Member, 16 Posts

26 February 2013 at 9:58am

Hi Kinglozzer,

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

Avatar
vxd

Community Member, 16 Posts

26 February 2013 at 1:39pm

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

Community Member, 16 Posts

26 February 2013 at 1:48pm

Edited: 26/02/2013 1:54pm

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