1

I try to save multi select it will throw the error

Something went wrong while saving

Notice: Array to string conversion in /project/vendor/magento/framework/DB/Adapter/Pdo/Mysql.php on line 2930

class Categorylist implements ArrayInterface
{
    protected $_categoryFactory;
    protected $_categoryCollectionFactory;

    public function __construct(
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    )
    {
        $this->_categoryFactory = $categoryFactory;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
    }

    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        return $collection;
    }

    public function toOptionArray()
    {
        $arr = $this->_toArray();
        $ret = [];

        foreach ($arr as $key => $value)
        {
            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }

        return $ret;
    }

    private function _toArray()
    {
        $categories = $this->getCategoryCollection(true, false, false, false);

        $catagoryList = array();
        foreach ($categories as $category)
        {
            $catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
        }

        return $catagoryList;
    }

    private function _getParentName($path = '')
    {
        $parentName = '';
        $rootCats = array(1,2);

        $catTree = explode("/", $path);
        // Deleting category itself
        array_pop($catTree);

        if($catTree && (count($catTree) > count($rootCats)))
        {
            foreach ($catTree as $catId)
            {
                if(!in_array($catId, $rootCats))
                {
                    $category = $this->_categoryFactory->create()->load($catId);
                    $categoryName = $category->getName();
                    $parentName .= $categoryName . ' -> ';
                }
            }
        }

        return $parentName;
    }
}

Main.php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $catConfig = $objectManager->create('Namespace\Module\Model\Module\Source\Categorylist');
        $catOptions = $catConfig->toOptionArray();

        $fieldset->addField(
            'categories',
            'multiselect',

            [
                'name' => 'categories[]',
                'label' => __('Product Categories'),
                'title' => __('Product Categories'),
                'note' => __('Add Product Categories(s), on which this cashback offer is availed.(Add ,(comma) separated Categories)'),
                'required' => false,
                 'values' => $catOptions
            ]
        );

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\ModuleName\Model\ModuleName');
            $id = $this->getRequest()->getParam('ModuleName_id');
            if ($id) {
                $curSet = $model->load($id);
            }

            $data['payment_methods'] = !empty($data['payment_methods']) ? implode(',', $data['payment_methods']) : NULL;
            $data['store_ids'] = !empty($data['store_ids']) ? implode(',', $data['store_ids']) : NULL;

            $this->_eventManager->dispatch(
                'ModuleName_prepare_save',
                ['ModuleName' => $model, 'request' => $this->getRequest()]
            );

            if (!$this->dataProcessor->validate($data)) {
                return $resultRedirect->setPath('*/*/edit', ['ModuleName_id' => $model->getId(), '_current' => true]);
            }
            $model->setData($data);
            try {               
                $model->save();
                $this->messageManager->addSuccess(__('ModuleName was saved.'));
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['ModuleName_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 ModuleName.'));
            }

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

1 Answer 1

1

You must convert values to a string before saving Model. Add this to your model class Namespace\ModuleName\Model\ModuleName

or you can change your post data to a string before add to model like

$data['store_ids'] = !empty($data['store_ids']) ? implode(',', $data['store_ids']) : NULL;

enter code here

public function beforeSave()
{
    $data = $this->getData('categories');
    if (is_array($data)) {
        $data = array_filter($data);
        $this->setData('categories', implode(',', $data));
    }

    return parent::beforeSave();
}
7
  • Where i need to add this
    – Magento 2
    Commented Dec 15, 2017 at 5:51
  • Your model class
    – HoangHieu
    Commented Dec 15, 2017 at 5:55
  • I have edited the code if your model extend AbstractModel
    – HoangHieu
    Commented Dec 15, 2017 at 5:57
  • Same error i got whre i need to add this function '
    – Magento 2
    Commented Dec 15, 2017 at 6:04
  • what your model to save? where class? could you show me ??
    – HoangHieu
    Commented Dec 15, 2017 at 6:06

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.