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're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Data Model Questions /

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

[SOLVED] Average Rating Function Causing Errors


Go to End


6 Posts   2052 Views

Avatar
zenmonkey

Community Member, 545 Posts

29 August 2009 at 9:03am

Edited: 01/09/2009 1:36am

I have a product rating system in place and I calculate average rating on approved ratings. If a product page doesn't have a rating or doesn't have an approved rating I get a White Screen of Death unless I remove the $AverageRating tag from the template.

Below is the Code

function AverageRating() {
		 
		 $records = DataObject::get("Review","Approval = 1 AND ProductID =" . $this->ID);
		 $ratingArray = $records->column('Rating');
		 $totalRatingsCount = $records->Count();
		 $totalRatingSum = array_sum($ratingArray);
		 $averageRating = $totalRatingSum/$totalRatingsCount;
		 if ($averageRating >= ($half = ($ceil = ceil($averageRating))- 0.5) + 0.25) return $ceil;
		 else if($averageRating < $half - 0.25) return floor($averageRating);
		 else return $half;
	 }

I've tried wrapping the rating calculation in in a if (isset($records)) {...}else{return 0;} but that doesn't help

Avatar
Willr

Forum Moderator, 5523 Posts

29 August 2009 at 7:22pm

have you tried just adding this simple if after the dataobject get -

 if(!$records || $records->Count <= 0) return false;
rather then the isset() which may return true if $records is empty dataobjectset.

Avatar
zenmonkey

Community Member, 545 Posts

1 September 2009 at 1:33am

Thanks that got it.

Avatar
lanks

Community Member, 61 Posts

21 January 2010 at 8:36pm

Hi would you be able to please post the complete code to allow rating of a dataobject?

Thanks
Liam

Avatar
zenmonkey

Community Member, 545 Posts

22 January 2010 at 2:45am

Sure, it needs the DataObjectManager installed. I've also set it up that a review needs to be approved before it's published but that can be easily removed.

Attached Files
Avatar
lanks

Community Member, 61 Posts

22 January 2010 at 12:37pm

Awsome thanks Zenmonkey.