2

We have customized the My Account dashboard with our own design. Now we wanted to implement the profile picture option while the customer do the registration.

After the registration, in My Account dashboard, we want to show that image as in below attachment marked as red.

enter image description here How can I do this in Magento 2?

Any help will be appreciated.

  • do you want something like that? fmeextensions.com/… – Waqar Ali Nov 4 at 10:51
  • @WaqarAli, Please suggest me any free extensions – Siva Nov 6 at 15:30
  • you just need profile picture? – Waqar Ali Nov 7 at 4:14
  • @WaqarAli, Yes, you're right. Once customer upload the profile picture. I want to show the picture at marked place as in question. – Siva Nov 7 at 5:21
  • i will answer as soon as possible.. are you aware with Module Development? – Waqar Ali Nov 7 at 5:27
1

I've created custom module here for profile picture

You can try to download and install module in your app/code directory and run below commands

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:clean
php bin/magento cache:flush

Hope this will help you!

  • 1
    Thank you so much Kishan – Siva yesterday
  • 1
    You're most welcome :) – Kishan Savaliya yesterday
1

Please try to install below module URL, which have provide to upload your profile pic...

https://github.com/php-cuong/magento2-customer-avatar

  • I have tried this but its not working. Please suggest alternate one.. If its free extension that would be better – Siva Nov 4 at 11:40
  • After installing this module, I'm getting the picture upload option in Account information menu but I can't upload the image. Any help will be appreciated – Siva Nov 6 at 15:43
  • have you get any error ? – Anas Mansuri Nov 7 at 5:08
  • I couldn't see any error but still I can't upload the picture. – Siva Nov 7 at 5:22
  • can you please check log. – Anas Mansuri Nov 7 at 5:26
0

In Your

Vendor/Module/etc/frontend/layout/customer_Account.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1columns" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Customer My Account (All Pages)" design_abstraction="custom">
    <body>
        <attribute name="class" value="account"/>
        <referenceBlock name="content">
             <block class="Vednor\Module\Block\CustomAvatar" name="customer_custom" before="customer_account_navigation"   template="Vednor_Module::customavatar.phtml"/>
        </referenceBlock>

    </body>
</page>

In your

Vendor/Module/etc/frontend/templates/customeravatar.phtml

<div class="main_profile_sidebar_container">
  <div class="profile_sidebar_container">
    <form action="<?php echo $this->getUrl() . 'myaccountpages/customavatar'; ?>" enctype="multipart/form-data"  method="post">
      <div class="user-account">
        <div class="avatar">
          <label for="profile_picture">
            <img id="preview" src="<?php echo $avatar['link']; ?>" alt="">
          </label>
          <input id="profile_picture" requried type="file" name="profile_picture" value="<?php echo $avatar['name']; ?>"  />
        </div>

      </div>
    </form>
  </div>
</div>

In your UpgradeSchema.php

use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;

/**
 * Class Upgrade Data
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;

    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * Cunstructor
     * @param CustomerSetupFactory
     * @param AttributeSetFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory  = $attributeSetFactory;
    }

    /**
     * Adding Custom Attribute to Magento
     * @param ModuleDataSetupInterface
     * @param ModuleContextInterface
     * @return null
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet     = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
        $customerSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'profile_picture',
            [
                'type'         => 'text',
                'label'        => 'Profile Picture',
                'input'        => 'text',
                'required'     => false,
                'visible'      => true,
                'user_defined' => true,
                'sort_order'   => 1000,
                'position'     => 1000,
                'system'       => 0,
            ]
        );
        $Attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'profile_picture')
            ->addData([
                'attribute_set_id'   => 1,
                'attribute_group_id' => 1,
                'used_in_forms'      => ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout'],
            ]);

        $Attribute->save();
        $setup->endSetup();
    }
}

In your Controller to Save Image in Database

Vendor/Module/Controller/Index.php

use Magento\Customer\Model\Customer;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\Session;

/**
 * Class Index
 */
class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var String
     */
    const CUSTOM_CUSTOMER_ATTR = 'profile_picture';

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var CustomerFactory
     */
    private $customerFactory;

    /**
     * @param \Magento\Framework\App\Action\Context
     * @param CustomerFactory
     * @param Customer
     * @param Session
     * @param \Vendor\Module\\Model\ImageUploader
     * @param \Magento\Framework\Message\ManagerInterface
     * @param \Magento\Framework\View\Result\PageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        Session $customerSession,
        CustomerFactory $customerFactory,
        \Vendor\Module\Model\ImageUploader $imageUploader,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->customerFactory   = $customerFactory;
        $this->customerSession   = $customerSession;
        $this->messageManager    = $messageManager;
        $this->imageUploader     = $imageUploader;
        parent::__construct($context);
    }
    /**
     * Save Cutomer Image
     *
     * @return PageFactory
     */
    public function execute()
    {
        $resultRedirect          = $this->resultRedirectFactory->create();
        $uploader                = get_object_vars($this->getRequest()->getFiles());
        $data['profile_picture'] = $uploader['profile_picture'];
        if (!empty($data['profile_picture']['name']) && !empty($data['profile_picture']['tmp_name'])) {
            $data['image'] = $data['profile_picture']['name'];
            $this->imageUploader->saveFileToTmpDir($data['profile_picture']);
            if ($this->customerSession->isLoggedIn()) {
                $profilePicture = $data['image'];
                $customerId     = $this->customerSession->getCustomer()->getId();
                $customer       = $this->customerFactory->create()->load($customerId);
                $customer->setProfilePicture($profilePicture);
                $customer->save();
                $this->imageUploader->moveFileFromTmp($profilePicture);
                $this->messageManager->addSuccessMessage('Avatar Has Been Updated Successfully');
                $resultRedirect->setUrl($this->_redirect->getRefererUrl());
                return $resultRedirect;
            }
        } else {
            $this->messageManager->addWarning('No image has been Selected');
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }

    }
}

In Your

\Vendor\Module\Model\ImageUploader.php

class ImageUploader
{
    /**
     * Core file storage database
     *
     * @var \Magento\MediaStorage\Helper\File\Storage\Database
     */
    protected $coreFileStorageDatabase;

    /**
     * Media directory object (writable).
     *
     * @var \Magento\Framework\Filesystem\Directory\WriteInterface
     */
    protected $mediaDirectory;

    /**
     * Uploader factory
     *
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    private $uploaderFactory;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * Base tmp path
     *
     * @var string
     */
    protected $baseTmpPath;

    /**
     * Base path
     *
     * @var string
     */
    protected $basePath;

    /**
     * Allowed extensions
     *
     * @var string
     */
    protected $allowedExtensions;

    /**
     * @var File
     */
    private $io;

    /**
     * ImageUploader constructor
     *
     * @param \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase
     * @param \Magento\Framework\Filesystem $filesystem
     * @param \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Psr\Log\LoggerInterface $logger
     * @param string $baseTmpPath
     * @param string $basePath
     * @param string[] $allowedExtensions
     */
    public function __construct(
        \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Filesystem\Io\File $io,
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Psr\Log\LoggerInterface $logger,
        $baseTmpPath,
        $basePath,
        $allowedExtensions
    ) {
        $this->coreFileStorageDatabase = $coreFileStorageDatabase;
        $this->mediaDirectory          = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $this->uploaderFactory         = $uploaderFactory;
        $this->storeManager            = $storeManager;
        $this->logger                  = $logger;
        $this->io                      = $io;
        $this->baseTmpPath             = $baseTmpPath;
        $this->basePath                = $basePath;
        $this->allowedExtensions       = $allowedExtensions;
    }

    /**
     * Set base tmp path
     *
     * @param string $baseTmpPath
     *
     * @return void
     */
    public function setBaseTmpPath($baseTmpPath)
    {
        $this->baseTmpPath = $baseTmpPath;
    }

    /**
     * Set base path
     *
     * @param string $basePath
     *
     * @return void
     */
    public function setBasePath($basePath)
    {
        $this->basePath = $basePath;
    }

    /**
     * Set allowed extensions
     *
     * @param string[] $allowedExtensions
     *
     * @return void
     */
    public function setAllowedExtensions($allowedExtensions)
    {
        $this->allowedExtensions = $allowedExtensions;
    }

    /**
     * Retrieve base tmp path
     *
     * @return string
     */
    public function getBaseTmpPath()
    {
        return $this->baseTmpPath;
    }

    /**
     * Retrieve base path
     *
     * @return string
     */
    public function getBasePath()
    {
        return $this->basePath;
    }

    /**
     * Retrieve base path
     *
     * @return string[]
     */
    public function getAllowedExtensions()
    {
        return $this->allowedExtensions;
    }

    /**
     * Retrieve path
     *
     * @param string $path
     * @param string $imageName
     *
     * @return string
     */
    public function getFilePath($path, $imageName)
    {
        return rtrim($path, '/') . '/' . ltrim($imageName, '/');
    }

    /**
     * Checking file for moving and move it
     *
     * @param string $imageName
     *
     * @return string
     *
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function moveFileFromTmp($imageName)
    {
        $baseTmpPath      = $this->getBaseTmpPath();
        $basePath         = $this->getBasePath();
        $baseImagePath    = $this->getFilePath($basePath, $imageName);
        $baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);
        try {
            $this->coreFileStorageDatabase->copyFile(
                $baseTmpImagePath,
                $baseImagePath
            );
            $this->mediaDirectory->renameFile(
                $baseTmpImagePath,
                $baseImagePath
            );
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __($e . 'Something went wrong while saving the file(s).')
            );
        }

        return $imageName;
    }

    /**
     * Checking file for save and save it to tmp dir
     *
     * @param string $fileId
     *
     * @return string[]
     *
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function saveFileToTmpDir($fileId)
    {
        $baseTmpPath = $this->getBaseTmpPath();
        $directory   = $this->mediaDirectory->getAbsolutePath($baseTmpPath);
        if ($this->io->checkAndCreateFolder($directory)) {
            $uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
            $uploader->setAllowedExtensions($this->getAllowedExtensions());
            $uploader->setAllowRenameFiles(true);
            $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
            if (!$result) {
                throw new \Magento\Framework\Exception\LocalizedException(
                    __('File can not be saved to the destination folder.')
                );
            }
        }
        $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']);
        $result['path']     = str_replace('\\', '/', $result['path']);
        $result['url']      = $this->storeManager
            ->getStore()
            ->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . $this->getFilePath($baseTmpPath, $result['file']);
        $result['name'] = $result['file'];
        if (isset($result['file'])) {
            try {
                $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
                $this->coreFileStorageDatabase->saveFile($relativePath);
            } catch (\Exception $e) {
                $this->logger->critical($e);
                throw new \Magento\Framework\Exception\LocalizedException(
                    __($e . 'Something went wrong while saving the file(s).')
                );
            }
        }
        return $result;
    }
}

For Further Assitance you can contact me

  • I have created a module and put your code but when i run the compile commands, getting the below error. – Siva Nov 8 at 10:51
  • Class Vendor\Module\Model\ImageUploader does not exist Class Butterfly\Imageupload\Controller\Index\Index\Interceptor generation error: The requested class did not generate properly, because t he 'generated' directory permission is read-only. If --- after running the 'bin/magento setup:di:compile' CLI command when the 'generated ' directory permission is set to write – Siva Nov 8 at 10:52
  • Dear you have to change Vendor/Module to Butterfly/Imageupload – Waqar Ali Nov 8 at 10:53
  • where ever there is Vendor/Module Change this – Waqar Ali Nov 8 at 10:54
  • I have changed them but still getting this error when I'm going to compile – Siva Nov 8 at 10:55

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.