1

I have a custom grid. Need to upload product images from admin form of the custom module.

Here is the grid Edit file at

app\code\local\Cpstest\ProductComment\Block\Adminhtml\Cps\Edit\Form.php

<?php
class Cpstest_ProductComment_Block_Adminhtml_Cps_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    public function __construct()
    {
        parent::__construct();

        $this->setId('cpstest_productcomment_cps_form');
        $this->setTitle($this->__('Product Comments Information'));
    }

    protected function _prepareForm()
    {
        $model = Mage::registry('cpstest_productcomment');

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

        $fieldset = $form->addFieldset('base_fieldset', array(
            'legend'    => Mage::helper('adminhtml')->__('Product Comments Information'),
            'class'     => 'fieldset-wide',
        ));

        if ($model->getId()) {
            $fieldset->addField('id', 'hidden', array(
                'name' => 'id',
            ));
        }

        $fieldset->addField('name', 'text', array(
            'name'      => 'name',
            'label'     => Mage::helper('adminhtml')->__('Customer Name'),
            'title'     => Mage::helper('adminhtml')->__('Customer Name'),
            'required'  => true,
            'class'     =>'input-text required-entry validate-no-html-tags',
        ));

        ...

        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

Here is the controller SaveAction:

public function saveAction()
{
    if ($postData = $this->getRequest()->getPost()) {
        $model = Mage::getSingleton('cpstest_productcomment/cps');
        $model->setData($postData);

        try {
            $model->save();
            Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The comment has been saved.'));
            $this->_redirect('*/*/');
            return;
        } catch (Mage_Core_Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('An error occurred while saving this comment.'));
        }
        Mage::getSingleton('adminhtml/session')->setCpsData($postData);
        $this->_redirectReferer();
    }
}
  • do you just want to display image or you want to update image ? – Murtuza Zabuawala May 23 '17 at 4:59
  • Hi @MurtuzaZabuawala , I would like to upload new product images from the grid edit page. I was able to add the 'browse' button, but the images are not being uploaded and saved. – bestwebdevs May 25 '17 at 17:03
2

You can add image field by below code.

$fieldset->addField('image', 'image', array(
    'label'     => Mage::helper('catalog')->__('Image'),
    'required'  => false, // Make true if required field
    'name'      => 'image',
));

Add below code to your saveAction

public function saveAction()
{
    if ($postData = $this->getRequest()->getPost()) {
        try {
            if ((bool)$post_data['image']['delete']==1) {
                $post_data['image']='';
            } else {
                unset($post_data['image']);
                if (isset($_FILES)) {
                    if ($_FILES['image']['name']) {
                        if ($this->getRequest()->getParam("id")) {
                            $model = Mage::getSingleton('cpstest_productcomment/cps')->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 . 'Cpstest' . DS .'ProductComment'.DS;
                        $uploader = new Varien_File_Uploader('image');
                        $uploader->setAllowedExtensions(array('jpg','png','gif'));
                        $uploader->setAllowRenameFiles(false);
                        $uploader->setFilesDispersion(false);
                        $destFile = $path.$_FILES['image']['name'];
                        $filename = $uploader->getNewFileName($destFile);
                        $uploader->save($path, $filename);

                        $post_data['image']='Cpstest/ProductComment/'.$filename;
                        $mediaAttribute = array (
                            'image',
                            'thumbnail',
                            'small_image'                  
                        );
                        $_product = Mage::getModel("catalog/product")->load();
                        $_product->addImageToMediaGallery($path.$filename, $mediaAttribute, true, false);
                        $_product->save();
                    }
                }
            }
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            return;
        }

        $model = Mage::getSingleton('cpstest_productcomment/cps');
        $model->setData($postData);

        try {
            $model->save();
            Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The comment has been saved.'));
            $this->_redirect('*/*/');
            return;
        } catch (Mage_Core_Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('An error occurred while saving this comment.'));
        }
        Mage::getSingleton('adminhtml/session')->setCpsData($postData);
        $this->_redirectReferer();
    }
}
  • Hi @Jaimin, thanks for help. I tried this solution and added the print screen to my question. It displays a button to upload an image, but looks like it doesn't work, the image is not being uploaded. – bestwebdevs May 23 '17 at 16:59
  • Can you share your controller saveAction code? – Jaimin Sutariya May 23 '17 at 17:14
  • Hi @Jaimin, I have added it to my question. – bestwebdevs May 23 '17 at 23:45
  • 1
    @bestwebdevs, for saving image, you can use saveAction from Sathish's answer. Also please add your grid image renderer code to the question to check on which path you are saving your images. – Jaimin Sutariya May 24 '17 at 4:49
  • Here you are using product image. Do you want to upload your images to products? – Jaimin Sutariya May 25 '17 at 9:52
2

You need to alter your controller to save image or delete images (unset images) like below.

public function saveAction()
{
    if ($postData = $this->getRequest()->getPost()) {
        try {
            if ((bool)$post_data['image']['delete']==1) {
                $post_data['image']='';
            } else {
                unset($post_data['image']);
                if (isset($_FILES)) {
                    if ($_FILES['image']['name']) {
                        if ($this->getRequest()->getParam("id")) {
                            $model = Mage::getSingleton('cpstest_productcomment/cps')->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 . 'Cpstest' . DS .'ProductComment'.DS;
                        $uploader = new Varien_File_Uploader('image');
                        $uploader->setAllowedExtensions(array('jpg','png','gif'));
                        $uploader->setAllowRenameFiles(false);
                        $uploader->setFilesDispersion(false);
                        $destFile = $path.$_FILES['image']['name'];
                        $filename = $uploader->getNewFileName($destFile);
                        $uploader->save($path, $filename);

                        $post_data['image']='Cpstest/ProductComment/'.$filename;
                    }
                }
            }
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            return;
        }

        $model = Mage::getSingleton('cpstest_productcomment/cps');
        $model->setData($postData);

        try {
            $model->save();
            Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The comment has been saved.'));
            $this->_redirect('*/*/');
            return;
        } catch (Mage_Core_Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('An error occurred while saving this comment.'));
        }
        Mage::getSingleton('adminhtml/session')->setCpsData($postData);
        $this->_redirectReferer();
    }
}

for adding image in edit view, as per jaimin sutariya said. you can add image field set

$fieldset->addField('image', 'image', array(
    'label' => Mage::helper('catalog')->__('Image'),
    'name' => 'image',
    'required'  => false, // Make true if required field
    'note' => '(*.jpg, *.png, *.gif)',
));
  • Hi @Sathish, I tried but the image was not uploaded. – bestwebdevs May 23 '17 at 18:08
  • how you checked? on folder or db? try to debug using var_dump($_FILES); posted or not? – Sathish May 23 '17 at 18:14
  • I checked the database table catalog_product_entity_media_gallery and also the folder. – bestwebdevs May 23 '17 at 18:25
  • can you share more detail like model, config and schema details? – Sathish May 23 '17 at 18:29
  • I have added more details @Satish. And as an additional info - here is how the grid works: when you press on any row of the grid (besides 'product front url' and 'product back-end url') it redirects to grid edit page. – bestwebdevs May 23 '17 at 20:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.