I have a junction table Znw
with 2 ids (a_id
& wz_id
), and a form with 2 select boxes according. I would like to check in the rules, if fieldn
of the corresponding model a
have the same value as field
of the corresponding model wz
.
Rules:
[['a_id', 'wz_id'], 'compareFields', 'on' => 'createwz', 'params' => []],
custom validation function (now only to check if the correct value is found):
public function compareFields($attribute, $params) {
$this->addError($attribute, $this->a->fieldn);
return false;
}
relation a
:
public function getA() {
return $this->hasOne(\app\models\A::className(), ['id' => 'a_id']);
}
this relation is otherwise working well in views etc.
relation wz
:
public function getWz() {
return $this->hasOne(\app\models\Wz::className(), ['id' => 'wz_id']);
;}
controller:
public function actionCreatewz() {
$model = new Znw;
$a = A::find()->where(['id' => $_GET['Znw']['a_id']])->one();
$model->scenario = 'createwz';
try {
if ($model->load($_POST) && $model->save()) {
return $this->redirect(Url::previous());
} elseif (!\Yii::$app->request->isPost) {
$model->load($_GET);
}
} catch (\Exception $e) {
$msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
$model->addError('_exception', $msg);
}
return $this->render('createwz', [
'model' => $model,
'a' => $a,
]);
}
if I'm adding $this->wz->field
to the custom validation function, it shows the right value. If I'm adding $this->a->fieldn
, then I'm getting the following error:
Trying to get property of non-object
however, in the $_POST request both ids (a_id
& wz_id
) are there with the right value, so I should be able to see corresponding a
model attribute. Why am I getting this error instead? Can you please point me to the right direction? Thanks in advance!