3

I have followed Magento2 : Admin module Image upload code to display form

to add a field for image upload , now getting an error

Fatal error: Class 'vendor\modulename\Controller\Adminhtml\modulename\LocalizedException' not found in /var/www/html/label/app/code/vendor/modulename/Controller/Adminhtml/modulename/Save.php on line 60

How to solve this ? Please help me to resolve this.. save.php

<?php
/**
 * Copyright © 2016 AionNext Ltd. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace vendor\modulename\Controller\Adminhtml\modulename;

use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \vendor\modulename\Controller\Adminhtml\modulename
{
    protected $_fileUploaderFactory;
    /**
    * @var \Magento\Framework\Filesystem
    */
    protected $filesystem;

    /**
     * @var \Magento\Backend\Helper\Js
     */
    protected $_jsHelper;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Backend\Helper\Js $jsHelper,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Registry $coreRegistry
    )
    {
        $this->_jsHelper = $jsHelper;       
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $this->filesystem = $filesystem;
        parent::__construct($context,$coreRegistry);
    }   

    /**
     * Image upload
     *
     * @return string
     */
    public function uploadFileAndGetName($input, $destinationFolder, $data)
    {
        try {  
            $media = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            if (isset($data[$input]['delete'])) {
                unlink($media->getAbsolutePath($data[$input]['value']));
            }

            $uploader = $this->_fileUploaderFactory->create(['fileId' => $input]);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $uploader->setAllowCreateFolders(true);
            $path = $media->getAbsolutePath($destinationFolder);
            $result = $uploader->save($path);
            return $destinationFolder.$result['file'];

        } catch (\Exception $e) {
            if ($e->getCode() != \Magento\Framework\File\Uploader::TMP_NAME_EMPTY) {
                throw new LocalizedException($e->getMessage());
            } else {
                if (isset($data[$input]['value'])) {
                    return $data[$input]['value'];
                }
            }
        }
        return '';
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        // check if data sent
        $data = $this->getRequest()->getPostValue();
        if ($data) { 
            $id = $this->getRequest()->getParam('label_id');
            $model = $this->_objectManager->create('vendor\modulename\Model\modulename')->load($id);
            if (!$model->getId() && $id) {
                $this->messageManager->addError(__('This item no longer exists.'));
                return $resultRedirect->setPath('*/*/');
            }


            // get image file name 
            $result = \vendor\modulename\Model\modulename::BASE_MEDIA_PATH;
            $pdtimageName = $this->uploadFileAndGetName('product_label', $result, $data);
            $catimageName = $this->uploadFileAndGetName('category_label', $result, $data);
            $data['product_label']=$pdtimageName;
            $data['category_label']=$catimageName;       
            // init model and set data

            $model->setData($data);

            // try to save it
            try {

                // save the data
                $model->save();
                $this->saveProducts($model, $data);
                // display success message
                $this->messageManager->addSuccess(__('You saved the item.'));
                // clear previously saved data from session
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);

                // check if 'Save and Continue'
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['label_id' => $model->getId()]);
                }
                // go to grid
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                // display error message
                $this->messageManager->addError($e->getMessage());
                // save data in session
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData($data);
                // redirect to edit form
                return $resultRedirect->setPath('*/*/edit', ['label_id' => $this->getRequest()->getParam('label_id')]);
            }
        }
        return $resultRedirect->setPath('*/*/');
    }

    public function saveProducts($model, $post)
    {   
        // Attach the attachments to contact
        if (isset($post['products'])) {
            $productIds = $this->_jsHelper->decodeGridSerializedInput($post['products']); 
            try {
                $oldProducts = (array) $model->getProducts($model);
                $newProducts = (array) $productIds;

                $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');
                $connection = $this->_resources->getConnection();

                $table = $this->_resources->getTableName(\vendor\modulename\Model\ResourceModel\modulename::TBL_ATT_PRODUCT);
                $insert = array_diff($newProducts, $oldProducts);
                $delete = array_diff($oldProducts, $newProducts);

                if ($delete) {
                    $where = ['label_id = ?' => (int)$model->getId(), 'product_id IN (?)' => $delete];
                    $connection->delete($table, $where);
                }

                if ($insert) {
                    $data = [];
                    foreach ($insert as $product_id) {
                        $data[] = ['label_id' => (int)$model->getId(), 'product_id' => (int)$product_id];
                    }
                    $connection->insertMultiple($table, $data);
                }
            } catch (Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the label.'));
            }
        }

    }

}

THis is my form code for image fields:

   protected function _prepareForm()
    {
        /* @var $model \vendor\Productlabel\Model\Productlabel */
        $model = $this->_coreRegistry->registry('productlabel_item');

        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(
            array(
                'data' => array(
                    'id'        => 'edit_form',
                    'action'    => $this->getData('action'),
                    'method'    => 'post',
                    'enctype'   => 'multipart/form-data',
                ),
            )
        );

        $form->setHtmlIdPrefix('label_');

        $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Product Label Information')]);

        if ($model->getId()) {
            $fieldset->addField('label_id', 'hidden', ['name' => 'label_id']);
        }

        $fieldset->addField(
            'title',
            'text',
            array(
                'name' => 'title',
                'label' => __('Title'),
                'title' => __('Title'),
                'required' => true
            )
        );

        $fieldset->addField(
            'status',
            'select',
            array(
                'label' => __('Status'),
                'title' => __('Status'),
                'name' => 'status',
                'required' => true,
                'options' => ['1' => __('Enabled'), '0' => __('Disabled')]
           )
        );
        if (!$model->getId()) {
            $model->setData('status', '1');
        }

        $fieldset->addField(
            'product_label',
            'image',
            array(
                'name' => 'product_label',
                'label' => __('Product Label'),
                'title' => __('Product Label'),
                'note' => 'Allow image type: jpg, jpeg, gif, png',
           )
        );

        $fieldset->addField(
            'category_label',
            'image',
            array(
                'name' => 'category_label',
                'label' => __('Category Label'),
                'title' => __('Category Label'),
                'required' => false,
                'note' => 'Allow image type: jpg, jpeg, gif, png',
            )
        );

        $form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }
4

1 Answer 1

5

you calling LocalizedException is directly add exception like this

        try {  
            $media = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            if (isset($data[$input]['delete'])) {
                unlink($media->getAbsolutePath($data[$input]['value']));
            }

            $uploader = $this->_fileUploaderFactory->create(['fileId' => $input]);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $uploader->setAllowCreateFolders(true);
            $path = $media->getAbsolutePath($destinationFolder);
            $result = $uploader->save($path);
            return $destinationFolder.$result['file'];

            }
            catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the News.'));
            }

possible solution for second question

make sure you added 'enctype' => 'multipart/form-data'

protected function _prepareForm()
    {
        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(
            ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'enctype' => 'multipart/form-data','method' => 'post']]
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
8
  • Ok . Thanks for your reply. Let me check this code.
    – E.B
    Commented Dec 8, 2016 at 6:30
  • Getting this error : $_FILES array is empty";i:1;s:6016:"#0 /var/www/html/label/vendor/magento/framework/File/Uploader.php(161): Magento\Framework\File\Uploader->_setUploadFileId('product_label')
    – E.B
    Commented Dec 8, 2016 at 7:08
  • @E.B check your image field name are correct product_label and category_label Commented Dec 8, 2016 at 7:16
  • Yes my image field names are product_label & category_label
    – E.B
    Commented Dec 8, 2016 at 7:19
  • can you add your form code too. because error is clearly indicating field name not correct. Commented Dec 8, 2016 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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