I have a form, where the first step is to choose city (City is a related model and has an attribute of population min. and max. e.g. 10.000 - 12.000). In the 2nd step the user has to fill population (e.g. 11.000). Now in rules I'm checking if the user has filled the right number of population (if it's between min. and max. population of City). Create new record is working. But I have a problem with Update action. Because if I already have a number in population (11.000) and I have a City
attached and I would like to change city to something else where population should be e.g. between 5.000 and 7.000, validation of population in my model fails, because it is validated based on the old City (of course until all values pass the validation city_id
won't be updated). Can you please point me to the right direction? Should I maybe update city_id
in my model before validation (is it possible)? Thank you!
form:
<?= $form->field($model, 'city_id')->dropDownList(
\yii\helpers\ArrayHelper::map(app\models\City::find()->all(), 'id', 'name')); ?>
<?= $form->field($model, 'population')->textInput(['maxlength' => true]) ?>
model rules:
...
['population', 'validatePopulation'],
...
public function getCity() {
return $this->hasOne(\app\models\City::className(), ['id' => 'city_id']);
}
public function validatePopulation($attribute, $params, $validator) {
if ($this->population < $this->city->population_min) {
$this->addError($attribute, 'Population has to be larger than ' . $this->city->population_min);
} elseif ($this->population > $this->city->population_max) {
$this->addError($attribute, 'Population has to be smaller than ' . $this->city->population_max);
}
}