I have a custom module which manage to upload the banners.
Everything working fine except image validation.
Below is my code for the image in
app/code/E25media/Bannersmanager/Block/Adminhtml/Banners/Edit/Tab/Main.php
<?php
namespace E25media\Bannermanager\Block\Adminhtml\Banners\Edit\Tab;
class Main extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface
{
/* -- some code here */
protected function _prepareForm()
{
/* -- some code here */
$fieldset->addType('image', '\E25media\Bannermanager\Block\Adminhtml\Banners\Helper\Image');
$fieldset->addField('banner_image_mobile', 'image', array(
'name' => 'banner_image_mobile',
'class' => 'required-entry required-file',
'label' => __('Mobile Banner Image'),
'title' => __('Mobile Banner Image'),
'required' => true,
'disabled' => $isElementDisabled));
/* -- some code here */
}
My form file upload is look like this. enter image description here
But i can submit the form without uploading the image.
How to validate the image file ?
1 Answer 1
Try this.
Use javascript to add the class.
$fieldset->addField(
'banner_image_mobile',
'image',
[
'name' => 'banner_image_mobile',
'label' => __('Mobile Banner Image'),
'title' => __('Mobile Banner Image'),
'note' => __('Size: 164px x 24px, Allowed File Types : (JPG,JPEG,PNG), Max Size:2MB.'),
'path'=> $model->getImagePath(),
'required' => true,
'value' => $model->getImagePath()
]
)->setAfterElementHtml('
<script>
require([
"jquery",
], function($){
$(document).ready(function () {
if($("#page_banner_image_mobile").attr("value")){
$("#page_banner_image_mobile").removeClass("required-file");
}else{
$("#page_banner_image_mobile").addClass("required-file");
}
$( "#page_banner_image_mobile" ).attr( "accept", "image/x-png,image/gif,image/jpeg,image/jpg,image/png" );
});
});
</script>
');
-
thanks for your answer.I am getting this error Parse error: syntax error, unexpected ''disabled'' (T_CONSTANT_ENCAPSED_STRING), expecting ')' in D:\xampp\htdocs\tork\app\code\E25media\Bannermanager\Block\Adminhtml\Banners\Edit\Tab\Main.php on line 159Mujahidh– Mujahidh2018年05月09日 07:06:49 +00:00Commented May 9, 2018 at 7:06
-
check my updated answer and compare with your current code.Chirag Patel– Chirag Patel2018年05月09日 07:20:10 +00:00Commented May 9, 2018 at 7:20
-
@Mujahidh still getting error?Chirag Patel– Chirag Patel2018年05月09日 08:40:38 +00:00Commented May 9, 2018 at 8:40
-
still allow me to submit the form without upload the imageMujahidh– Mujahidh2018年05月09日 09:59:24 +00:00Commented May 9, 2018 at 9:59
-
I think there is a problem with your field id mentioned in script, alert in JavaScript code and check field id is correct or not, because this code working for me.Chirag Patel– Chirag Patel2018年05月09日 10:02:53 +00:00Commented May 9, 2018 at 10:02
Explore related questions
See similar questions with these tags.