0

I have create one custom module to insert image from admin side in custom database same as catalog product in magento1.9

below is my controller function for insert image in custom database. this controller function is calling from phtml file using ajax and working perfectly.

Path of this controller file is local/[CompanyName]/[ModuleName]/controllers/Adminhtml/vendorProductController.php file

    public function editAction()
    {
        $vendorProductId = $this->getRequest()->getParam('id');
        $vendorProductModel = Mage::getModel('vendor/vendorProductRequestData')->load($vendorProductId);
        $vendorProductModels = Mage::getModel('vendor/vendorProductRequestImage')->load($vendorProductId,'vendor_product_request_data_id');
        $vendorProductModel->setData('image',$vendorProductModels->getImage());
        if ($vendorProductModel->getId() || $vendorProductId == 0) {
            Mage::register('vendorproduct_data', $vendorProductModel);

            $this->loadLayout();
            $this->_setActiveMenu('catalog/vendor_products');

            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Vendor Product Information'), Mage::helper('adminhtml')->__('Vendor Product Information'));
            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Data News'), Mage::helper('adminhtml')->__('Data News'));

            $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

            $this->_addContent($this->getLayout()->createBlock('vendor/adminhtml_vendorproduct_edit'))->_addLeft($this->getLayout()->createBlock('vendor/adminhtml_vendorproduct_edit_tabs'));

            $this->renderLayout();
        } else {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('vendor')->__('Vendor Product does not exist'));
            $this->_redirect('*/*/');
        }
    }
    public function saveImageAction(){
        $data = $this->getRequest()->getPost();
        $id = $data['productDataId'];
        if (isset($_FILES)) {
            if ($_FILES['image']['name']) {
                $i=0;
                foreach ($_FILES['image']['name'] as $value) {
                    if ($id) {
                        $model = Mage::getSingleton('vendor/vendorProductRequestData')->load($this->getRequest()->getParam("id"));
                        if ($model->getData('image')) {
                            $io = new Varien_Io_File();
                            $io->rm(Mage::getBaseDir('media').DS.implode(DS,explode('/',$model->getData('image'))));
                        }
                    }
                    $path = Mage::getBaseDir('media') . DS . '[CompanyName]' . DS .'ProductImage'.DS;
                    $uploader = new Varien_File_Uploader("image[$i]");
                    $uploader->setAllowedExtensions(array('jpg','png','gif'));
                    $uploader->setAllowRenameFiles(false);
                    $uploader->setFilesDispersion(false);
                    $destFile = $path.$_FILES['image']['name'][$i];
                    $filename = $uploader->getNewFileName($destFile);
                    $uploader->save($path, $filename);

                    $post_data['image']='CompanyName/ProductImage/'.$filename;
                    $mediaAttribute = array (
                        'all_images',
                        'image',
                        'thumbnail',
                        'small_image'
                    );
                    $_product = Mage::getModel("vendor/vendorProductRequestImage");
                    $_product->setData('vendor_product_request_data_id',$id);
                    $_product->setData('all_images',$post_data['image']);

                    $_product->save();

                    $i++;
                }
            }
        }
        $this->_redirectReferer();
    }

below is my Tabs.php file to call tab of custom module.

<?php
class [CompanyName]_[ModuleName]_Block_Adminhtml_VendorProduct_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{

    public function __construct()
    {
        parent::__construct();
        $this->setId('vendorproduct_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(Mage::helper('vendor')->__('Vendor Information'));
    }

    protected function _beforeToHtml()
    {
        $this->addTab('form_section', array(
            'label' => Mage::helper('vendor')->__('Vendor Product Data'),
            'title' => Mage::helper('vendor')->__('vendor Product Data'),
            'content' => $this->getLayout()->createBlock('vendor/adminhtml_vendorproduct_edit_tab_form')->toHtml(),
        ));
        $this->addTab('image_section', array(
            'label' => Mage::helper('vendor')->__('Image'),
            'title' => Mage::helper('vendor')->__('Product Image'),
            'content' => $this->getLayout()->createBlock('vendor/adminhtml_vendorproduct_edit_tab_image')->toHtml(),
        ));
        return parent::_beforeToHtml();
    }
}

Below is my image.php file (tab) through which i am displaying my phtml file to insert images from admin side

<?php

class [CompanyName]_Vendor_Block_Adminhtml_VendorProduct_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{

    public function __construct()
    {
        parent::__construct();
        $this->setUseAjax(true);

        $this->setTemplate('vendor/product.phtml');
    }

    protected function _prepareForm()
    {
        $vendorProductDetail =  Mage::registry('vendorproduct_data');

        $form = new Varien_Data_Form(array(
            'id' => 'edit_form',
            'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
            'method' => 'post',
            'enctype' => 'multipart/form-data'

        )
    );
        $this->setForm($form);


        if ( Mage::getSingleton('adminhtml/session')->getVendorData() )
        {
            $form->setValues(Mage::getSingleton('adminhtml/session')->getVendorData());
            Mage::getSingleton('adminhtml/session')->setVendorData(null);
        } elseif ( Mage::registry('vendorproduct_data') ) {
            $form->setValues(Mage::registry('vendorproduct_data')->getData());
        }
        $this->setForm($form);
        $form->setValues($vendorProductDetail->getData());
        return parent::_prepareForm();

    }

    public function getImage(){
        $id = $this->getRequest()->getParam("id");

        $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
        $imageData = Mage::getModel('vendor/vendorProductRequestImage')->getCollection()->getSelect()->where('vendor_product_request_data_id=?',$id);
        $allImage = $connection->fetchAll($imageData);

        return $allImage;
    }

    public function getSelectedImage(){
        $id = $this->getRequest()->getParam("id");

        $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
        $imageData = Mage::getModel('vendor/vendorProductRequestImage')->getCollection()->getSelect()->where('vendor_product_request_data_id=?',$id)->where('image != ?', null);

        $selectedImage = $connection->fetchRow($imageData);
        return $selectedImage;
    }
    public function getSmallImage(){
        $id = $this->getRequest()->getParam("id");

        $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
        $imageData = Mage::getModel('vendor/vendorProductRequestImage')->getCollection()->getSelect()->where('vendor_product_request_data_id=?',$id)->where('small_image != ?', null);

        $smallImage = $connection->fetchRow($imageData);
        return $smallImage;
    }
    public function getThumbImage(){
        $id = $this->getRequest()->getParam("id");

        $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
        $imageData = Mage::getModel('vendor/vendorProductRequestImage')->getCollection()->getSelect()->where('vendor_product_request_data_id=?',$id)->where('thumbnail != ?', null);

        $thumbImage = $connection->fetchRow($imageData);
        return $thumbImage;
    }

}

And phtml file to display it is below..

<table cellspacing="0"  class="data border" width="100%">
        <thead>
            <tr class="headings">
                <th><?php echo Mage::helper('vendor')->__('Image') ?></th>
                <th><?php echo Mage::helper('vendor')->__('Label') ?></th>
                <th><?php echo Mage::helper('vendor')->__('Sort Order') ?></th>
                <th><?php echo Mage::helper('vendor')->__('Base Image') ?></th>
                <th><?php echo Mage::helper('vendor')->__('Small image') ?></th>
                <th><?php echo Mage::helper('vendor')->__('Thumbnail') ?></th>
                <th><?php echo Mage::helper('vendor')->__('Exclude') ?></th>
                <th class="last"><?php echo Mage::helper('vendor')->__('Remove') ?></th>
            </tr>
        </thead>
        <tbody>
            <div id="image-result">
                <?php for($j=0;$j<count($this->getImage());$j++){ ?>
        
                <tr>
                    <?php if($i==0 && $this->getImage()[$j]['all_images']): ?>
                        <td> <?php echo "<img src='".Mage::getBaseUrl('media').trim($this->getImage()[$j]['all_images'])."' width='100px' />"; ?></td>
                        <td><input type="text" name="label" id=""></td>     
                        <td><input type="text" name="label" id=""></td>     
                        <td><input type="radio" name="image" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if($this->getImage()[$j]['all_images'] == $this->getSelectedImage()['image']){echo 'checked';}else{echo '';} ?>></td>        
                        <td><input type="radio" name="smallImg" id="" value="<?php echo $this->getImage()[$j]['all_images']?>" <?php if($this->getImage()[$j]['all_images'] == $this->getSmallImage()['small_image']){echo 'checked';}else{echo '';} ?> ></td>      
                        <td><input type="radio" name="thumbnail" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if($this->getImage()[$j]['all_images'] == $this->getThumbImage()['thumbnail']){echo 'checked';}else{echo '';} ?>  ></td>     
                        <td><input type="checkbox" name="exclude" id=""></td>       
                        <td><input type="checkbox" name="remove[]" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>"></td>        
                    <?php endif; ?>
                    <?php if($i==1 && $this->getImage()[$j]['all_images']): ?>
                        <td> <?php echo "<img src='".Mage::getBaseUrl('media').trim($this->getImage()[$j]['all_images'])."' width='100px' />"; ?></td>
                        <td><input type="text" name="label" id=""></td>     
                        <td><input type="text" name="label" id=""></td>     
                        <td><input type="radio" name="image" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if(!$this->getImage()[$j]['image']){echo '';}else{echo 'checked';} ?> ></td>     
                        <td><input type="radio" name="smallImg" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if(!$this->getImage()[$j]['small_image']){echo '';}else{echo 'checked';} ?> ></td>        
                        <td><input type="radio" name="thumbnail" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if(!$this->getImage()[$j]['thumbnail']){echo '';}else{echo 'checked';} ?> ></td>     
                        <td><input type="checkbox" name="exclude" id=""></td>       
                        <td><input type="checkbox" name="remove[]" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>"></td>        
                    <?php endif; ?>
                    <?php if($i==2 && $this->getImage()[$j]['all_images']): ?>
                        <td> <?php echo "<img src='".Mage::getBaseUrl('media').trim($this->getImage()[$j]['all_images'])."' width='100px' />"; ?></td>
                        <td><input type="text" name="label" id=""></td>     
                        <td><input type="text" name="label" id=""></td>     
                        <td><input type="radio" name="image" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if(!$this->getImage()[$j]['image']){echo '';}else{echo 'checked';} ?> ></td>     
                        <td><input type="radio" name="smallImg" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if(!$this->getImage()[$j]['small_image']){echo '';}else{echo 'checked';} ?>></td>     
                        <td><input type="radio" name="thumbnail" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>" <?php if(!$this->getImage()[$j]['thumbnail']){echo '';}else{echo 'checked';} ?> ></td>     
                        <td><input type="checkbox" name="exclude" id=""></td>       
                        <td><input type="checkbox" name="remove[]" id="" value="<?php echo $this->getImage()[$j]['all_images'] ?>"></td>        
                    <?php endif; ?>
                </tr>
                <?php
            } 
            ?>
        </div>
    </tbody>
</table>
<form id="submitForm" name="doc-form" action="<?php echo Mage::helper('adminhtml')->getUrl('adminhtml/vendorproduct/saveImage',array('form_key' => Mage::getSingleton('core/session')->getFormKey())); ?>" method="post" enctype="multipart/form-data">
    <div style="margin-top:15px;">
        <?php $id = $this->getRequest()->getParam("id"); ?>
        <label for="files"><h3>Select Images:</h3></label>
        <input type="hidden" name="productDataId" value="<?php echo $id; ?>">
        <input type="file" name="image[]" multiple style="padding:5px;" id="files"  />
        <input type="submit" name="saveImage" value="Upload Files" style="padding:5px;"/>
    </div>
</form>

<div>
    <div id="image-result">

    </div>
</div>
<!-- Jquery js -->


<script>
    var $j = jQuery.noConflict();
    $j(document).ready(function() 
    {    
$j(document).ready(function() {
    if (window.File && window.FileList && window.FileReader) {
        $j("#files").on("change", function(e) {

            var files = e.target.files,
            filesLength = files.length;
            for (var i = 0; i < filesLength; i++) {
                var f = files[i]
                var fileReader = new FileReader();
                fileReader.onload = (function(e) {
                    var file = e.target;
                    $j("<span class=\"pip\">" +
                        "<img class=\"imageThumb\" width=\"100px\" height=\"100px\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
                        "<br/><span class=\"remove\">Remove image</span>" +
                        "</span>").insertAfter("#files");
                    $j(".remove").click(function(){
                        $j(this).parent(".pip").remove();
                    });
                });
                fileReader.readAsDataURL(f);
            }
        });
    } else {
        alert("Your browser doesn't support to File API")
    }
});


$j('#submitForm').on('submit',function(e){
    e.preventDefault();
    var formData = new FormData(this);
    $j.ajax({
        type:'POST',
        url: $j(this).attr('action'),
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(data);
        },
        error: function(data){
            console.log("error");
        }
    });
});
});      
</script>

below is what it looks like edit/add image grid

below is a code in which i am adding jquery for my phtml file

<?xml version="1.0"?>
<layout version="0.1.0">
    <adminhtml_vendorproduct_edit>
        <reference name="head">
            <action method="addJs">
                <script>[folderName]/image.js</script>
            </action>                        
            <action method="addCss">
                <stylesheet>css/custom.css</stylesheet>
            </action>
        </reference>
    </adminhtml_vendorproduct_edit>
</layout>

below image is what when i browse any image to insert it in custom database after browse any image

when I click on "upload file" button it get inserted in database without refresh page using ajax. Now what I want is to display that inserted image in this grid without refreshing this page. Can anyone please help how to do this using ajax... Thanks in advance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.