I have got difficult form in yii2 view, where some fields show or hide. It decide from user field choises, select options in the form. I write this frontend logic with custom jq
You can set your active field using this code: (not active record
, activefield
exactly)
$activeField = $form->field($model, 'someField');
$activeField->enableClientValidation=false;
$activeField ->enableAjaxValidation=false;
You can try setting default values for attributes that aren't set:
[
// set "username" and "email" as null if they are empty
[['username', 'email'], 'default'],
// set "level" to be 1 if it is empty
['level', 'default', 'value' => 1],
]
more info here
You can also use conditional client-side validation with "whenClient"
option when defining you validators:
From the manual:
If you also need to support client-side conditional validation, you should configure the whenClient property which takes a string representing a JavaScript function whose return value determines whether to apply the rule or not. For example,
[ ['state', 'required', 'when' => function ($model) { return $model->country == 'USA'; }, 'whenClient' => "function (attribute, value) { return $('#country').val() == 'USA'; }"], ]
To remove a field from validation:
$('#yourFormID').yiiActiveForm('remove', 'yourinputID');
To add a field to validation list:
$('#yourFormID').yiiActiveForm('add', {
id: 'country',
name: 'yourinputID',
container: '.field-inputID', //or your cllass container
input: '#yourinputID',
error: '.help-block', //or your class error
validate: function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {message: "Validation Message Here"});
}
});
And don't forget conditional validation in your model. More info
To disable client side validation. Begin your active form like this.
ActiveForm::begin(['enableClientValidation'=>false]);
$form->field($model, 'youAttribute', ['enableClientValidation' => false])->textInput();
The ActiveField
class has a property enableClientValidation
, you can simply set this property to false
if you want to disable clientValidation form some fields.
For your Form, use whenClient:
['name', 'required', 'when' => {serverSide Condition),
'whenClient' => "ut_utils.isAttributeVisible",
],
['name', 'string', 'min' => 2, 'max' => 28],
['name', 'trim'],
And in ut_utils (JS):
/**
* Useful for FE validation (whenClient) to validate only if visible (ie valid input)
*
* @param attribute Obj containing all sorts of info about attr including container name :-)
* @param value
*/
isAttributeVisible: function (attribute, value) {
return $(attribute.container).is(':visible');
},
You will need to add 'when' to validate serverside too you can add specific logic here or use a scenario to exclude attributes from being validated ...