0

I have created a custom module and in the admin New/Edit form I added the image field but when I submit the form with uploading image, it won't show the image in save controller.

I used to add below code to add image field in admin from:

$fieldset->addField(
        'image',
        'image',
        array(
            'label' => __('Image'),
            'name'  => 'image',
            'class' =>'admin__control-image',
    )
 );

also in my form, I added the multipart form data as below:

protected function _prepareForm()
{
    /** @var \Magento\Framework\Data\Form $form */
    $form = $this->_formFactory->create(
        ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post' , 'enctype' => 'multipart/form-data']]
    );
    $form->setUseContainer(true);
    $this->setForm($form);
    return parent::_prepareForm();
}

How to get rid of this issue?

Thanks in advance!

0

Use below code

$fieldset->addField(
    'profile',
    'image',
    [
        'name' => 'profile',
        'label' => __('Profile Image'),
        'title' => __('Profile Image'),
        'required'  => false,
        'disabled' => $isElementDisabled
    ]
);

controller file save.php

use Magento\Framework\App\Filesystem\DirectoryList;

$profileImage = $this->getRequest()->getFiles('profile');
$fileName = ($profileImage && array_key_exists('name', $profileImage)) ? $profileImage['name'] : null;
if ($profileImage && $fileName) {
    try {
        /** @var \Magento\Framework\ObjectManagerInterface $uploader */
        $uploader = $this->_objectManager->create(
            'Magento\MediaStorage\Model\File\Uploader',
            ['fileId' => 'profile']
        );
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
        /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapterFactory */
        $imageAdapterFactory = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')
            ->create();
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(true);
        $uploader->setAllowCreateFolders(true);
        /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
        $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
            ->getDirectoryRead(DirectoryList::MEDIA);

        $result = $uploader->save(
            $mediaDirectory
                ->getAbsolutePath('Modulename/Profile')
        );
        //$data['profile'] = 'Modulename/Profile/'. $result['file'];
        $model->setProfile('Modulename/Profile'.$result['file']); //Database field name
    } catch (\Exception $e) {
        if ($e->getCode() == 0) {
            $this->messageManager->addError($e->getMessage());
        }
    }
}

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.