2

This is my function, if i update it without image it throws the an error . Update with image it works Fine. How to fix this

**

1 exception(s):
    Exception #0 (Exception): Notice: Array to string conversion in /var/www/html/magento/project/vendor/magento/framework/Data/Form/Element/Image.php on line 51

**

Save.php

public function execute()
{
    $data = $this->getRequest()->getPostValue();


    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($data) {
        $model = $this->_objectManager->create('Namespace\Banner\Model\Banner');

        $id = $this->getRequest()->getParam('banner_id');
        if ($id) {
            $model->load($id);
            //$model->setCreatedAt(date('Y-m-d H:i:s'));
        }
        if(!isset($data['image']['delete']) || ( isset($data['image']['delete'])$data['image']['delete'] != '1')){

        try{
            $uploader = $this->_objectManager->create(
                'Magento\MediaStorage\Model\File\Uploader',
                ['fileId' => 'image']
            );
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
            $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
            $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                ->getDirectoryRead(DirectoryList::MEDIA);
            $result = $uploader->save($mediaDirectory->getAbsolutePath('banner'));
                if($result['error']==0)
                {
                    $data['image'] = 'banner' . $result['file'];
                }
        } catch (\Exception $e) {
            //unset($data['image']);
            $this->messageManager->addException($e, __('$e->getMessage()'));
        }
    }
        //var_dump($data);die;
        if(isset($data['image']['delete']) && $data['image']['delete'] == '1')
            $data['image'] = '';

        $model->setData($data);

        try {
            $model->save();
            $this->messageManager->addSuccess(__('The Banner has been saved.'));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['banner_id' => $model->getId(), '_current' => true]);
            }
            return $resultRedirect->setPath('*/*/');
        } 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 Banner.'));
        }

        $this->_getSession()->setFormData($data);
        return $resultRedirect->setPath('*/*/edit', ['banner_id' => $this->getRequest()->getParam('banner_id')]);
    }
    return $resultRedirect->setPath('*/*/');
}

Edit.php

public function execute()
    {
        // 1. Get ID and create model
        $id = $this->getRequest()->getParam('banner_id');
        $model = $this->_objectManager->create('Namespace\Banner\Model\Banner');

        // 2. Initial checking
        if ($id) {
            $model->load($id);
            if (!$model->getId()) {
                $this->messageManager->addError(__('This item no longer exists.'));
                /** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();

                return $resultRedirect->setPath('*/*/');
            }
        }

        // 3. Set entered data if was error when we do save
        $data = $this->_objectManager->get('Magento\Backend\Model\Session')->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        }

        // 4. Register model to use later in blocks
        $this->_coreRegistry->register('banner', $model);

        // 5. Build edit form
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->_initAction();
        $resultPage->addBreadcrumb(__('Namespace'), __('Namespace'));
        $resultPage->addBreadcrumb(
            $id ? __('Edit Item') : __('New Item'),
            $id ? __('Edit Item') : __('New Item')
        );
        $resultPage->getConfig()->getTitle()->prepend($id ? __('Edit Item') : __('New Item'));
        //$resultPage->getConfig()->getTitle()->prepend($model->getId() ? $model->getTitle() : __('New Item'));

        return $resultPage;
    }
1
  • did you get any solution for this. Commented Nov 13, 2017 at 14:53

4 Answers 4

3
+50

You can keep with below code and check,

You can check your code with below way, 1. If new image assigned, then go to if condition

(isset($_FILES['image']) && !empty($_FILES['image']['name']) ) 

and

If you are update image value go to else condtions,

So you dont need to worry about your field with no image.

<?php
public function execute()
{
    $data = $this->getRequest()->getPostValue();

    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($data) {
        $model = $this->_objectManager->create('Namespace\Banner\Model\Banner');

        $id = $this->getRequest()->getParam('banner_id');
        if ($id) {
            $model->load($id);
            //$model->setCreatedAt(date('Y-m-d H:i:s'));
        }
        if (isset($_FILES['image']) && !empty($_FILES['image']['name']) ) {

            try{
                $uploader = $this->_objectManager->create(
                    'Magento\MediaStorage\Model\File\Uploader',
                    ['fileId' => 'image']
                );
                $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
                $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
                $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                    ->getDirectoryRead(DirectoryList::MEDIA);
                $result = $uploader->save($mediaDirectory->getAbsolutePath('banner'));
                    if($result['error']==0)
                    {
                        $data['image'] = 'banner' . $result['file'];
                    }
            } catch (\Exception $e) {
                //unset($data['image']);
                $this->messageManager->addException($e, __('$e->getMessage()'));
            }
        }else {
                if (isset($data['image']) && isset($data['image']['value'])) {
                    if (isset($data['image']['delete'])) {
                        $data['image'] = '';
                    } elseif (isset($data['image']['value'])) {
                        $data['image'] = $data['image']['value'];
                    } else {
                        $data['image'] = '';
                    }
                }
            }

        $model->setData($data);

        try {
            $model->save();
            $this->messageManager->addSuccess(__('The Banner has been saved.'));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['banner_id' => $model->getId(), '_current' => true]);
            }
            return $resultRedirect->setPath('*/*/');
        } 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 Banner.'));
        }

        $this->_getSession()->setFormData($data);
        return $resultRedirect->setPath('*/*/edit', ['banner_id' => $this->getRequest()->getParam('banner_id')]);
    }
    return $resultRedirect->setPath('*/*/');
}
2
  • Please let me know if you have query. Commented Aug 8, 2017 at 13:42
  • You can use $this->getRequest()->getFiles() in magento instead of $_FILES.
    – fudu
    Commented Nov 13, 2019 at 9:09
1

Your up-loader cpde should be under:

if(!isset($data['image']['delete']) || ( isset($data['image']['delete'])$data['image']['delete'] != '1')){

    $uploader = $this->_objectManager->create(
                    'Magento\MediaStorage\Model\File\Uploader',
                    ['fileId' => 'image']
                );
                $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
                $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
                $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                    ->getDirectoryRead(DirectoryList::MEDIA);
                $result = $uploader->save($mediaDirectory->getAbsolutePath('banner'));
                    if($result['error']==0)
                    {
                        $data['image'] = 'banner' . $result['file'];
                    }   
}
4
  • Can you please update Full function
    – Magento 2
    Commented Aug 2, 2017 at 15:35
  • syntax error, unexpected '$data' (T_VARIABLE)
    – Magento 2
    Commented Aug 2, 2017 at 15:37
  • Check my updated question i got this error syntax error, unexpected '$data' (T_VARIABLE)
    – Magento 2
    Commented Aug 8, 2017 at 4:53
  • Still i got a same error Exception #0 (Exception): Notice: Array to string conversion
    – Magento 2
    Commented Aug 8, 2017 at 5:01
0

Your error comes from the method getElementHtml() from line:

if ((string)$this->getValue()) {

where value is your image. There should be string (path to image) not an array. You should debug from where come array-type value and what is it?

You can try this code, I think it should work, but I not able to test it without a whole module:

public function execute()
{
    $data = $this->getRequest()->getPostValue();
    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($data) {
        $model = $this->_objectManager->create('Namespace\Banner\Model\Banner');
        $id = $this->getRequest()->getParam('banner_id');
        if ($id) {
            $model->load($id);
            //$model->setCreatedAt(date('Y-m-d H:i:s'));
        }

        if (!empty($data['image']) && (!isset($data['image']['delete']) ||
            (isset($data['image']['delete']) && $data['image']['delete'] != '1'))
        ) {
            try {
                $uploader = $this->_objectManager->create(
                    'Magento\MediaStorage\Model\File\Uploader',
                    ['fileId' => 'image']
                );
                $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
                $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
                $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                    ->getDirectoryRead(DirectoryList::MEDIA);
                $result = $uploader->save($mediaDirectory->getAbsolutePath('banner'));
                if ($result['error'] == 0) {
                    $data['image'] = 'banner' . $result['file'];
                }
            } catch (\Exception $e) {
                //unset($data['image']);
                $this->messageManager->addException($e, __('$e->getMessage()'));
            }
        } elseif (isset($data['image']['delete']) && $data['image']['delete'] == '1') {
            $data['image'] = '';
        }

        $model->addData($data);

        try {
            $model->save();
            $this->messageManager->addSuccess(__('The Banner has been saved.'));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['banner_id' => $model->getId(), '_current' => true]);
            }

            return $resultRedirect->setPath('*/*/');
        } 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 Banner.'));
        }

        $this->_getSession()->setFormData($data);

        return $resultRedirect->setPath('*/*/edit', ['banner_id' => $this->getRequest()->getParam('banner_id')]);
    }

    return $resultRedirect->setPath('*/*/');
}
0

Just insert given below code before '$model->setData($data);' in your 'save.php' file.

if(isset($data['image_url']['value']))
{
    $data['image_url'] = $data['image_url']['value'];
}

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.