['state', 'required', 'when' => function ($model) {
return $model->country != null;
}, 'enableClientValidation' => false],
Why does country
attribute is updated to have null
value when I added this code? I figured out that my rules above is not working because country
is somewhere set to NULL
ONLY when I add those code in my model rules.
on my controller I set data using this :
$model = Country::findOne($country_id);
$model->load(Yii::$app->request->post());
On my view I only have this customized html, Im not using the view of yii2
<form ='form1'>
<input name="Country[country_name]" type="text"/>
</form>
<form ='form2'>
<input name="Country[state_name]" type="text"/>
</form>
Since you didn't post enough code for anyone to tell what you have, this is as close as I can get. I may update this answer if you add more code. We need to see more of your model, controller, and view.
In the view file, it would help so I can see what ID's are being assigned to your inputs, which would allow me to provide more detailed code. So for right now, you need to look at your form and look at the ID's on the input elements. Replace REPLACEHERE
in the javascript below with whatever your ID's start with.
model
['state_name', 'required', 'when' => function($model) {
return !empty($model->country_name);
}, 'whenClient' => "isCountryEmpty"
],
place at the bottom of your view file:
<?php $this->registerJs('
function isCountryEmpty (attribute, value) {
return ($("#REPLACEHERE-country_name").val().length > 0) ? true : false;
};
jQuery( "#REPLACEHERE-country_name" ).keyup(function() {
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-state_name");
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-country_name");
});
jQuery( "#REPLACEHERE-state_name" ).keyup(function() {
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-state_name");
$("#w0").yiiActiveForm("validateAttribute", "REPLACEHERE-country_name");
});
'); ?>
The whenClient in the model tells it to run client validation and calls the isStateEmpty function in the javascript. The other 2 javascripts detect changes on the state
and country
inputs. On keyup
they trigger the Yii ActiveForm javascript to re-validate.
Hope that helps you out!
Edit
After you added your view's code, your names are incorrect. In your view, you have state_name
and country_name
but in your model you used only state
. I have updated my code above to reflect that.
If your not using the Yii form, you will not get client validations. Those are bound by specialized Yii ID's attached to the elements when ActiveForm creates your form.