I have been playing with Yii2 and I am stuck at rules. The functionality I am trying to achieve:
User is presented with a form where he can add points to different statistics. However, he has only limited amount of points he can add. Same like in almost any role-playing game, where you can increase some stats when you level up.
For example we have these stats:
strength
, agility
, vitality
and the user can add up to 3 points.
How do I make the rules, so they allow adding max of 3 points, but once the 3 points are used, they refuse adding any more?
So if he adds 3 points to strength
the max for agility
and vitality
is 0. Or if he adds 2 points to strength
, the max for agility
and vitality
is 1, but once he adds the one point the rest goes to 0?
Edit: I am currently playing with something like:
["strength", "integer", "min" => 0 , "max" => $free_points, "when" => function($model) {
return $model->vitality == 0 && $model->agility == 0}],
Currently my problem is making it into a version that would adapt to the number of free points.
Edit2: I am trying to write a custom validator. What I can't find is how to get the value from the form... My non-working code (some variables are named just to show what I am trying to achieve):
public function validatePoints($attribute, $params)
{
$free_points = Technology::findOne(Yii::$app->user->identity->technology)->free_points;
$used_points = 0;
foreach($params as $value){
$used_points += $value;
}
if(($assigned_points + $used_points) > $free_points){
$this->addError($attribute, Yii::t('user', "You can not use more points than you have free points."));
return false;
}
return true;
}