Jump to:

3460 Posts in 1064 Topics by 739 members

Data Model Questions

SilverStripe Forums » Data Model Questions » [SOLVED] Average Rating Function Causing Errors

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

Page: 1
Go to End
Author Topic: 1594 Views
  • zenmonkey
    Avatar
    Community Member
    528 Posts

    [SOLVED] Average Rating Function Causing Errors Link to this post

    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

  • Willr
    Avatar
    Forum Moderator
    5502 Posts

    Re: [SOLVED] Average Rating Function Causing Errors Link to this post

    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.

  • zenmonkey
    Avatar
    Community Member
    528 Posts

    Re: [SOLVED] Average Rating Function Causing Errors Link to this post

    Thanks that got it.

  • lanks
    Avatar
    Community Member
    61 Posts

    Re: [SOLVED] Average Rating Function Causing Errors Link to this post

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

    Thanks
    Liam

  • zenmonkey
    Avatar
    Community Member
    528 Posts

    Re: [SOLVED] Average Rating Function Causing Errors Link to this post

    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
  • lanks
    Avatar
    Community Member
    61 Posts

    Re: [SOLVED] Average Rating Function Causing Errors Link to this post

    Awsome thanks Zenmonkey.

    1594 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.