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've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

[SOLVED] Doing Calculations in Silverstripe on database columns


Go to End


2 Posts   997 Views

Avatar
Optic Blaze

Community Member, 190 Posts

6 October 2015 at 4:21am

Hi there,

I have created a data object called players, created a model admin interface for it and now want to create a page that shows the results from the data that has been captured. I realize that i will need a ResultsPage class and assume that i will have to create a function in the controller that queries the Player class and then loops over the data from each player. I want to do calculations on thse database columns. So for example, for each player i want to calculate the number of (tries * 5) + (number of conversions *2) and get a total called PlayerScore, which i need to be able to show in my ResultsPage.ss template...how do i do that?

I have the following:

//// Player Class ///
class Player extends DataObject {
	static $db = array(
	'PlayerName'=>'Varchar(50)',
	'DateJoined'=> 'Year',
	'Tries'=>'Int',
	'Conversions'=>'Int',
	);

//// Results Page//
class ResultsPage extends Page {
}

class ResultsPage_Controller extends Page_Controller {

function playerstats() {
 $player = Player::get();
foreach($player as $x) {
$tries = $x[tries]*5;
$conversions = $x[conversions]*2;
$PlayerScore = $tries + $conversions;
return $PlayerScore;
}
}
}

 

Thanks

Avatar
Optic Blaze

Community Member, 190 Posts

6 October 2015 at 9:59am

Edited: 06/10/2015 10:01am

I figured it out


	// Function that creates player stats
	function playerstats() {
	$players = Player::get();

		$playerlist = new ArrayList();
		foreach($players as $item) {
			
		//Declare variables and do calculations on them
		$playername = $item->PlayerName;
		$tries = $item->Tries*5;
		$conversions = $item->Conversions*2;
		$penalties = $item->Penalties*3;
		$dropgoals = $item->DropGoals*3;
			
		//Build new array with calculated data
		$playerlist->push(
			new ArrayData(array(
			'Player' => $playername,
			'Tries' => $tries,
			'Conversions' => $conversions,
			'Penalties' => $penalties ,
			'DropGoal' =>$dropgoals ,
			'Total' => $tries+$conversions+$penalties+$dropgoals
			))
		);
		}
		return $playerlist;
	}

 

And in the .ss template you do the following:

<% loop $playerstats.Sort(Total,DESC) %>

Name: $Player: $Tries | $Penalties | $DropGoal | $Total <br>

<% end_loop %>