21301 Posts in 5736 Topics by 2603 members
General Questions
SilverStripe Forums » General Questions » Checking a DataObject isn't empty before attempting foreach loop
General questions about getting started with SilverStripe that don't fit in any of the categories above.
Moderators: martimiz, Howard, Sean, Ryan M., biapar, Willr, Ingo, swaiba, simon_w
|
Page:
1
|
Go to End | |
| Author | Topic: | 1327 Views |
-
Checking a DataObject isn't empty before attempting foreach loop

15 July 2010 at 11:13am
I'm trying to work out how to check that a DataObject is populated before running it through a foreach loop. Here is what I came up with:
function LatestNews($num=5) {
$GetNews = DataObject::get("NewsPage", "ParentID = $this->ID", "DisplayDate DESC", "", $num);
$LatestNews = new DataObjectSet();
foreach(empty($GetNews)?array():$GetNews as $NewsItem){
$LongDate = date("l j F Y",strtotime($NewsItem->DisplayDate));
$extrainfo = array(
'ArticleTitle' => $NewsItem->Title,
'ArticleLink' => $NewsItem->Link(),
'DisplayDate' => $LongDate,
);
$LatestNews -> push(new ArrayData($extrainfo));
}
return $LatestNews;
}
As you can see I'm usingso it gracefully fails if $GetNews is empty.foreach(empty($GetNews)?array():$GetNews as $NewsItem)
This works well in our development website but when I rolled it across to our production site it breaks with the following error when the DataObject is not empty - if the DataObject is empty I do not get an error:
[Notice] Trying to get property of non-object
Line 25 in /var/www/sites/wwwtasman/mysite/code/NewsListPage.php
25 $LongDate = date("l j F Y",strtotime($NewsItem->DisplayDate));
The only difference I can make up between the two websites is that our development website is running a slightly higher version of PHP (5.2.11) versus our production website (5.2.10).
All of this is pretty frustrating and I was wondering what tried and true method people use to make sure that if a DataObject is empty a foreach loop is not run.
Cheers
Tama -
Re: Checking a DataObject isn't empty before attempting foreach loop

15 July 2010 at 12:34pm
Wrap an if statement around the foreach:
if ($GetNews)
{
foreach($GetNews as $NewsItem)
{
// do your stuff here
}
} -
Re: Checking a DataObject isn't empty before attempting foreach loop

15 July 2010 at 12:37pm
Hi Ampedup
That was my original idea but I thought there must be a way that was "cleaner".
I think I've probably tried to be too clever and shot myself in the foot
| 1327 Views | ||
|
Page:
1
|
Go to Top |


