1

Here I am trying to save the image name which will be stored in the URl_TYPE_Media banner/Banner/image , but image name is not saving in DB. below code is what i have done so far. I am new to magento2

Form.php

<?php

namespace Zyxware\Banner\Block\Adminhtml\Banner\Edit;

/**
 * Adminhtml Add New Row Form.
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;

    /**
     * @param \Magento\Backend\Block\Template\Context $context,
     * @param \Magento\Framework\Registry $registry,
     * @param \Magento\Framework\Data\FormFactory $formFactory,
     * @param \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
     * @param \Zyxware\Banner\Model\Status $options,
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
        array $data = []
    ) {
        $this->_wysiwygConfig = $wysiwygConfig;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Prepare form.
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        $dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
        $model = $this->_coreRegistry->registry('banner_data');
        $form = $this->_formFactory->create(
            ['data' => [
                            'id' => 'edit_form',
                            'enctype' => 'multipart/form-data',
                            'action' => $this->getData('action'),
                            'method' => 'post'
                        ]
            ]
        );

        if ($model->getbannerId()) {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Edit banner'), 'class' => 'fieldset-wide']
            );
            $fieldset->addField('banner_id', 'hidden', ['name' => 'banner_id']);
        } else {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Add banner'), 'class' => 'fieldset-wide']
            );
        }

        $fieldset->addField(
            'name',
            'text',
            [
                'name' => 'name',
                'label' => __('Name'),
                'id' => 'name',
                'title' => __('Name'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );

        $wysiwygConfig = $this->_wysiwygConfig->getConfig(['tab_id' => $this->getTabId()]);

        $fieldset->addField(
            'content',
            'editor',
            [
                'name' => 'content',
                'label' => __('Content'),
                'style' => 'height:36em;',
                'required' => true,
                'config' => $wysiwygConfig
            ]
        );


        $fieldset->addField(
            'image',
            'image',
            array(
                'name' => 'image',
                'label' => __('Image'),
                'title' => __('Image'),
                'required' => true
            )
        );
        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

Save.php

<?php
namespace Zyxware\Banner\Controller\Adminhtml\Banner;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \Zyxware\Banner\Model\BannerFactory
     */
    var $gridFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Zyxware\Banner\Model\BannerFactory $gridFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Zyxware\Banner\Model\BannerFactory $gridFactory
    ) {
        parent::__construct($context);
        $this->gridFactory = $gridFactory;
    }

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        if (!$data) {
            $this->_redirect('banner/banner/addrow');
            return;
        }
        try {
            $rowData = $this->gridFactory->create();
            $rowData->setData($data);
            if (isset($data['id'])) {
                $rowData->setEntityId($data['id']);
            }
            $rowData->save();
            $this->messageManager->addSuccess(__('Banner has been successfully saved.'));
        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
        $this->_redirect('banner/banner/index');
    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Zyxware_Banner::save');
    }
}

0

1 Answer 1

1

I got the solution for my question. The solution is posted below in case if anyone need any help feel free to comment below . Create a function for image in Save.php and call it inside the execute function

 private function _processbanner_image($data, $model){

        try{


            $media_dir_obj = $this->_objectManager->get('Magento\Framework\Filesystem')
                                                    ->getDirectoryRead(DirectoryList::MEDIA);                                                                        
            $media_dir = $media_dir_obj->getAbsolutePath();


            if(!empty($_FILES['image']['name'])){

                $Uploader = $this->_objectManager->create(
                                               'Magento\MediaStorage\Model\File\Uploader',
                                                ['fileId' => 'image']);

                $Uploader->setAllowCreateFolders(true);
                $Uploader->setAllowRenameFiles(true);

                $banner_dir = $media_dir.'/zyxware/banner/banner/image';                                
                $result = $Uploader->save($banner_dir);

                unset($result['tmp_name']);
                unset($result['path']);

                $data['image'] = $Uploader->getUploadedFileName();

            }else{

                if(isset($data['image']['delete'])){

                    $data['image'] = '';

                }else{

                    if($model->getId()) {

                        if($model->getImage() != ''){                                        
                            $data['image'] = $model->getImage();
                        }

                    }else{
                        $data['image'] = '';
                    }
                }
            }

            if(isset($data['image']))
                return $data['image'];    


        } catch (\Exception $e) {

                $this->messageManager->addError(
                        __($e->getMessage())
                );                                
        }      

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.