1

How to upload two image form field in custom module?

in form field i have two image upload 1. featured image 2. icon image.

i m confused that in module controller file how to code two image uploader?

here is my code..

app\code\community\Mt\Service\controllers\Adminhtml\ServiceController.php

<?php

class Mt_Service_Adminhtml_ServiceController extends Mage_Adminhtml_Controller_Action {

    protected function _initAction() {
        $this->loadLayout()->_setActiveMenu("service/service")->_addBreadcrumb(Mage::helper("adminhtml")->__("Service  Manager"), Mage::helper("adminhtml")->__("Service Manager"));
        return $this;
    }

    public function indexAction() {
        $this->_title($this->__("Service"));
        $this->_title($this->__("Manager Service"));

        $this->_initAction();
        $this->renderLayout();
    }

    public function editAction() {
        $this->_title($this->__("Service"));
        $this->_title($this->__("Service"));
        $this->_title($this->__("Edit Item"));

        $id = $this->getRequest()->getParam("id");
        $model = Mage::getModel("service/service")->load($id);
        if ($model->getId()) {
            Mage::register("service_data", $model);
            $this->loadLayout();
            $this->_setActiveMenu("service/service");
            $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Service Manager"), Mage::helper("adminhtml")->__("Service Manager"));
            $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Service Description"), Mage::helper("adminhtml")->__("Service Description"));
            $this->getLayout()->getBlock("head")->setCanLoadExtJs(true);
            $this->_addContent($this->getLayout()->createBlock("service/adminhtml_service_edit"))->_addLeft($this->getLayout()->createBlock("service/adminhtml_service_edit_tabs"));
            $this->renderLayout();
        } else {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("service")->__("Item does not exist."));
            $this->_redirect("*/*/");
        }
    }

    public function newAction() {

        $this->_title($this->__("Service"));
        $this->_title($this->__("Service"));
        $this->_title($this->__("New Item"));

        $id = $this->getRequest()->getParam("id");
        $model = Mage::getModel("service/service")->load($id);

        $data = Mage::getSingleton("adminhtml/session")->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        }

        Mage::register("service_data", $model);

        $this->loadLayout();
        $this->_setActiveMenu("service/service");

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

        $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Service Manager"), Mage::helper("adminhtml")->__("Service Manager"));
        $this->_addBreadcrumb(Mage::helper("adminhtml")->__("Service Description"), Mage::helper("adminhtml")->__("Service Description"));


        $this->_addContent($this->getLayout()->createBlock("service/adminhtml_service_edit"))->_addLeft($this->getLayout()->createBlock("service/adminhtml_service_edit_tabs"));

        $this->renderLayout();
    }

    public function saveAction() {

        $post_data = $this->getRequest()->getPost();
        if ($post_data) {
            try {
                //Featured save image
                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::getModel("service/service")->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 . 'service' . DS . 'service' . DS;
                                $uploader = new Varien_File_Uploader('image');
                                $uploader->setAllowedExtensions(array('jpg', 'png', 'gif'));
                                $uploader->setAllowRenameFiles(true);
                                $uploader->setFilesDispersion(false);
                                $destFile = $path . $_FILES['image']['name'];
                                $filename = $uploader->getNewFileName($destFile);
                                $uploader->save($path, $filename);

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

                $model = Mage::getModel("service/service")
                        ->addData($post_data)
                        ->setId($this->getRequest()->getParam("id"))
                        ->save();

                Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Service was successfully saved"));
                Mage::getSingleton("adminhtml/session")->setServiceData(false);

                if ($this->getRequest()->getParam("back")) {
                    $this->_redirect("*/*/edit", array("id" => $model->getId()));
                    return;
                }
                $this->_redirect("*/*/");
                return;
            } catch (Exception $e) {
                Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
                Mage::getSingleton("adminhtml/session")->setServiceData($this->getRequest()->getPost());
                $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
                return;
            }
        }
        $this->_redirect("*/*/");
    }

    public function deleteAction() {
        if ($this->getRequest()->getParam("id") > 0) {
            try {
                $model = Mage::getModel("service/service");
                $model->setId($this->getRequest()->getParam("id"))->delete();
                Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Item was successfully deleted"));
                $this->_redirect("*/*/");
            } catch (Exception $e) {
                Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
                $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
            }
        }
        $this->_redirect("*/*/");
    }

    public function massRemoveAction() {
        try {
            $ids = $this->getRequest()->getPost('service_ids', array());
            foreach ($ids as $id) {
                $model = Mage::getModel("service/service");
                $model->setId($id)->delete();
            }
            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Item(s) was successfully removed"));
        } catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
        }
        $this->_redirect('*/*/');
    }

    /**
     * Export order grid to CSV format
     */
    public function exportCsvAction() {
        $fileName = 'service.csv';
        $grid = $this->getLayout()->createBlock('service/adminhtml_service_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
    }

    /**
     *  Export order grid to Excel XML format
     */
    public function exportExcelAction() {
        $fileName = 'service.xml';
        $grid = $this->getLayout()->createBlock('service/adminhtml_service_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
    }

}

Here is Form.php app\code\community\Mt\Service\Block\Adminhtml\Service\Edit\Tab\Form.php

<?php

class Mt_Service_Block_Adminhtml_Service_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form {

    protected function _prepareForm() {

        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset("service_form", array("legend" => Mage::helper("service")->__("Item information")));


        $fieldset->addField("name", "text", array(
            "label" => Mage::helper("service")->__("Service Name"),
            "class" => "required-entry",
            "required" => true,
            "name" => "name",
        ));

        $fieldset->addField("description", "editor", array(
            "label" => Mage::helper("service")->__("Description"),
            "name" => "description",
            'style' => 'height:15em',
            'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
            'wysiwyg' => true,
        ));

        $fieldset->addField('image', 'image', array(
            'label' => Mage::helper('service')->__('Featured Image'),
            'name' => 'image',
            'note' => '(*.jpg, *.png, *.gif)',
        ));

        $fieldset->addField('iconimage', 'image', array(
            'label' => Mage::helper('service')->__('Icon Image'),
            'name' => 'image',
            'note' => '(*.jpg, *.png, *.gif)',
        ));

        $fieldset->addField('backgroundcolor', 'text', array(
          'label'     => Mage::helper('service')->__('Background Color'),
          'name'      => 'backgroundcolor',
          'class'     => 'color {required:true, adjust:true, hash:true} validate-hex',
          'required'  => true,

        ));


        $fieldset->addField('status', 'select', array(
            'label' => Mage::helper('service')->__('Status'),
            'values' => Mt_Service_Block_Adminhtml_Service_Grid::getValueArray6(),
            'name' => 'status',
        ));
     /*    
        $fieldset->addField("instagramurl", "text", array(
            "label" => Mage::helper("service")->__("Instagram Url"),
            "name" => "instagramurl",
        ));
    */


        if (Mage::getSingleton("adminhtml/session")->getServiceData()) {
            $form->setValues(Mage::getSingleton("adminhtml/session")->getServiceData());
            Mage::getSingleton("adminhtml/session")->setServiceData(null);
        } elseif (Mage::registry("service_data")) {
            $form->setValues(Mage::registry("service_data")->getData());
        }
        return parent::_prepareForm();
    }

}

here is rendere image file. app\code\community\Mt\Service\Block\Adminhtml\Renderer\Image.php

<?php

class Mt_Service_Block_Adminhtml_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {

    public function render(Varien_Object $row) {
        $mediaurl = '';
        $value = $row->getData($this->getColumn()->getIndex());
        if ($value) {
            $mediaurl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . $value;
        } else {
            $mediaurl = $this->getSkinUrl() . '/service/service.png';
        }
        return '<p style="text-align:center;padding-top:5px;"><img src="' . $mediaurl . '"  style="width:80px;height:80px;text-align:center;"/></p>';
    }

}

Like This..

enter image description here

  • Both Image Name Should Store in Database Also – Rushikesh Solanki May 12 '17 at 13:58
  • You need to put your image upload code for both of your image fields in app\code\community\Mt\Service\controllers\Adminhtml\ServiceController.php::saveAction() – Jaimin Sutariya May 12 '17 at 14:03
  • ok, but how to write that code in same function? – Rushikesh Solanki May 15 '17 at 4:34
  • Select inner try catch block, press ctrl+c and then press ctrl+v, change your file field name in new code, update store path and it will do. – Jaimin Sutariya May 15 '17 at 6:11
  • i have do same thing but not work – Rushikesh Solanki May 15 '17 at 6:13
4

First update your Form.php file

$fieldset->addField('iconimage', 'image', array(
            'label' => Mage::helper('service')->__('Icon Image'),
            'name' => 'image',
            'note' => '(*.jpg, *.png, *.gif)',
        ));

to

$fieldset->addField('iconimage', 'image', array(
            'label' => Mage::helper('service')->__('Icon Image'),
            'name' => 'iconimage',
            'note' => '(*.jpg, *.png, *.gif)',
        ));

Now update your controller code saveAction()

public function saveAction() {
    $post_data = $this->getRequest()->getPost();
    if ($post_data) {
        try {
            //Featured save image
            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::getModel("service/service")->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 . 'service' . DS . 'service' . DS;
                            $uploader = new Varien_File_Uploader('image');
                            $uploader->setAllowedExtensions(array('jpg', 'png', 'gif'));
                            $uploader->setAllowRenameFiles(true);
                            $uploader->setFilesDispersion(false);
                            $destFile = $path . $_FILES['image']['name'];
                            $filename = $uploader->getNewFileName($destFile);
                            $uploader->save($path, $filename);

                            $post_data['image'] = 'service/service/' . $filename;
                        }
                    }
                }
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        //save image
        // Icon Image Save
        try {
                if ((bool) $post_data['iconimage']['delete'] == 1) {
                    $post_data['iconimage'] = '';
                } else {
                    unset($post_data['iconimage']);
                    if (isset($_FILES)) {
                        if ($_FILES['iconimage']['name']) {
                            if ($this->getRequest()->getParam("id")) {
                                $model = Mage::getModel("service/service")->load($this->getRequest()->getParam("id"));
                                if ($model->getData('iconimage')) {
                                    $io = new Varien_Io_File();
                                    $io->rm(Mage::getBaseDir('media') . DS . implode(DS, explode('/', $model->getData('iconimage'))));
                                }
                            }
                            $path = Mage::getBaseDir('media') . DS . 'service' . DS . 'service' . DS;
                            $uploader = new Varien_File_Uploader('iconimage');
                            $uploader->setAllowedExtensions(array('jpg', 'png', 'gif'));
                            $uploader->setAllowRenameFiles(true);
                            $uploader->setFilesDispersion(false);
                            $destFile = $path . $_FILES['iconimage']['name'];
                            $filename = $uploader->getNewFileName($destFile);
                            $uploader->save($path, $filename);

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

            $model = Mage::getModel("service/service")
                    ->addData($post_data)
                    ->setId($this->getRequest()->getParam("id"))
                    ->save();

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Service was successfully saved"));
            Mage::getSingleton("adminhtml/session")->setServiceData(false);

            if ($this->getRequest()->getParam("back")) {
                $this->_redirect("*/*/edit", array("id" => $model->getId()));
                return;
            }
            $this->_redirect("*/*/");
            return;
        } catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
            Mage::getSingleton("adminhtml/session")->setServiceData($this->getRequest()->getPost());
            $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
            return;
        }
    }
    $this->_redirect("*/*/");
}
  • Why it does not work ? If I add text or any other than file or image field type it works and in post there is everything except images or files :( HELP – Rob D. A. Feb 1 at 22:50
  • @RobD.A. It is due to PHP global variables. $_POST handles all input data while $_FILES handles files data. – Jaimin Sutariya Feb 3 at 6:26
  • 1
    Yes, i know that. Last night i finally managed to make it work so now each field is sending and then controller is saving data in table. Funny thing is i tried all those things before and then it just started to work so it seems i was missing some thing. Will analyse it today again then will post final solution – Rob D. A. Feb 3 at 10:27

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.