Reputation:
model code :
[['thumbnail_image'], 'required', 'message' => 'Please upload an image.'],
view:
$form->field($model, 'thumbnail_image')->fileInput(['accept' => 'image/*', 'onchange' => 'readURL(this)'])->label('Thumbnail Image', ['class' => 'control-label thumbnail-image-class'])
File input forces uploading file with every update. even thumb image value available but it gives error to thumb image is required.
Upvotes: 2
Views: 555
Reputation: 1757
[['thumbnail_image'], 'required', 'message' => 'Please upload an image.', 'when' => function($model) {
return ($model->thumbnail_image) ? 0:1;
}, 'whenClient' => "function (attribute, value) {
if ($('#thumb_id').val() == '') {
return 1;
} else {
return 0;
}
}"],
Upvotes: 1
Reputation:
I fixed issue with conditional validation of YII2. we have to check on update record that thumb image exist or not. 0 for no required
[['thumbnail_image'], 'required', 'message' => 'Please upload an image.', 'when' => function($model) {
return ($model->thumbnail_image) ? 0:1;
}, 'whenClient' => "function (attribute, value) {
if ($('#thumb_id').val() == '') {
return 1;
} else {
return 0;
}
}"],
Upvotes: 1
Reputation: 1314
Use ImageValidator to validate images and uploadRequired
property
[['thumbnail_image'], 'file', 'uploadRequired' => true', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
And read carefully http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html to properly implement file uploading
Upvotes: 0