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

How to test for Children()


Reply

7 Posts   342 Views

Avatar
tazzydemon

20 August 2013 at 12:47pm Community Member, 122 Posts

I have this function in a custom page_controller to work out how many "columns" of display items I have for css purposes. Its children with published children.

The problem is that $child->Children() returns an arraylist and therefore effectively true even when there are no published items and the printing sub-loop returns null.

As a result the count is wrong. I also use <% if Children %> in my templates.

Is there an alternative function?

public function columnCount(){
$count = 0;
if($this->Children()){
foreach($this->Children() as $child){
if($child->Children()){
$count++;
// following 4 lines just for test
foreach($child->Children() as $mokopuna){
print_r("Child name: ");
print_r($mokopuna->URLSegment.' - '.$mokopuna->URLSegment);
print_r("<BR>");
}
}
print_r("<hr>");
}
};
return $count;
}

Avatar
tazzydemon

20 August 2013 at 12:48pm Community Member, 122 Posts

Doh, think I might have figured it out all my by own self...

test for $child->Children()->count()

Avatar
Mo

22 August 2013 at 11:07pm Community Member, 509 Posts

Assuming you are using SS 3, Children should return a DataList.

So, you should be able to use:

if($this->Children()->exists()) {}

Or (in a template):

<% if $Children.exists %><% end_if %>

Mo

Avatar
IOTI

23 August 2013 at 12:14am Community Member, 189 Posts

Did you try using the built in [url=http://doc.silverstripe.org/framework/en/reference/templates#modulus-and-multipleof]Modulus[/url] template variable? Would probably be easier then creating your own function to do the counting. Maybe not applicable for what you are trying to do though.

Avatar
tazzydemon

27 August 2013 at 4:10pm Community Member, 122 Posts

Thanks.

BTW I don't think you need the $ inside the <% %>

Avatar
tazzydemon

27 August 2013 at 4:13pm Community Member, 122 Posts

I've used modulus elsewhere. This was just to start off loops like <ul>.. etc.

I also have to precount things to figure out responsive column sizes in the controller

Avatar
Mo

28 August 2013 at 6:59am (Last edited: 28 August 2013 6:59am), Community Member, 509 Posts

Hi Tazzydemon,

You are right, $ isn't required inside <% %>, but last docs I say indicated that you should use $, so I have been training myself to use it, just incase variables without $ are depreciated in the near future.

Also, not sure if this is useful, or if you are aware, but you should also be able to call count inside your template, EG:

$Children.Count
<% if $Children.Count = 1 %>

Cheers,

Mo