5

I'm trying to add an image upload field to the admin module form so admin users can have a profile picture, I've managed to add a column in the database through the installSchema but can't work out how to add the upload button and save the image on the frontend.

Can anyone point me in the right direction?

1 Answer 1

7

Add Below code in n _prepareForm() function inside

app/code/Namespace/Module/Block/Adminhtml/Module/Edit/Tab/Main.php

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

Now in execute() method of your save controller file. use below code to save and upload image.

app/code/Namespace/Module/Controller/Adminhtml/Index/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());
        }
    }
}
1
  • 1
    perfect answer with explanation!!! +1 made my day :) Jun 2, 2020 at 8:48

Your Answer

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

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