How to Add a Custom Mobile Logo Field in Magento 2 Design Configuration

You run an eCommerce store and want to ensure that your brand looks great on both desktop and mobile devices. If the mobile site uses the same logo as the desktop version. The logo might not be optimized for smaller screens, leading to a poor visual experience for mobile users.

 

You have to add a custom field in the Magento admin panel to upload a specific logo for mobile devices. The benefits will be

 

1. Improved User Experience: The custom mobile logo field allows you to upload a logo specifically designed for mobile devices. This ensures that the logo looks great on smaller screens, improving the overall user experience.

 

2. Brand Consistency: By having different logos for mobile and desktop, you maintain brand consistency and ensure that your site looks professional across all devices.

 

3.Flexibility: You can easily change the mobile logo from the admin panel without needing to touch the code. This makes it simple to update the logo for different marketing campaigns or seasonal promotions.

 

In this guide, we’ll show you how to add a custom field in Content -> Design -> Config -> Header to upload a mobile logo image. Follow these steps to create a small module for this purpose.

 

Steps to Add a Custom Mobile Logo Field

 

Step 1: Module Registration

Create a registration.php file to register the module.

M2\Theme\registration.php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'M2_Theme',

    __DIR__

);

 

Step 2 Module Configuration


Define the module and its dependencies in a module.xml file.

M2\Theme\etc\module.xml


< config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" < module name="M2_Theme" setup_version="1.0.0">
< sequence>
< /sequence>
< /module>

Step 3: Dependency Injection Configuration


Configure the new field's metadata in the di.xml file.

M2\Theme\etc\di.xml

< ?xml version="1.0"?>
< config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
< preference for="Magento\Theme\Block\Html\Header\Logo"
type="M2\Theme\Block\Html\Header\Logo"/>
< type name="Magento\Theme\Model\Design\Config\MetadataProvider">
< arguments> < argument name="metadata" xsi:type="array">
< item name="path" xsi:type="string">design/header/sticky_logo_src_mob

< item name="fieldset" xsi:type="string">other_settings/header
< item name="backend_model" xsi:type="string">M2\Theme\Model\Design\Backend\Mobile
< item name="base_url" xsi:type="array">
< item name="type" xsi:type="string">media
< item name="scope_info" xsi:type="string">1
< item name="value" xsi:type="string">sticky
< /item>
< /item>
< /argument>
< /arguments>
< /type>
< /config>

Step 4 : Backend Model for Image Upload


< p>Create a backend model (Mobile.php) to handle the image upload.


< strong>M2\Theme\Model\Design\Backend\Mobile.php


< ?php
/** * Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace M2\Theme\Model\Design\Backend;
class Mobile extends Image
{
/** * The tail part of directory path for uploading
* */ const UPLOAD_DIR = 'Mobile';
/** * Return path to directory for upload file
* * @return string * @throw \Magento\Framework\Exception\LocalizedException
*/ protected function _getUploadDir()
{ return $this->_mediaDirectory->getRelativePath($this->_appendScopeInfo(static::UPLOAD_DIR));
} /** * Makes a decision about whether to add info about the scope.
* * @return boolean
*/ protected function _addWhetherScopeInfo()
{
return true;
}
/** * Getter for allowed extensions of uploaded files.
*
* @return string[]
*/
public function getAllowedExtensions()
{
return ['jpg', 'jpeg', 'gif', 'png'];
}
}

Step 5  UI Component Configuration


Add the custom field to the design configuration form in design_config_form.xml.

M2\Theme\view\adminhtml\ui_component\design_config_form.xml

< ?xml version="1.0" encoding="UTF-8"?> < form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
< fieldset name="other_settings" sortOrder="30">
< fieldset name="header">
< settings>
< level>1
< collapsible>true
< label translate="true">Header
< /settings>
< field name="header_sticky_logo_src_mob" formElement="imageUploader">
< settings>
< label translate="true">Mobile Logo Image
< componentType>imageUploader
< /settings>
< formElements>
< imageUploader>
< settings> < allowedExtensions>jpg jpeg gif png
< maxFileSize>2097152
< uploaderConfig>
< param xsi:type="string" name="url">theme/design_config_fileUploader/save
< /settings>
< /imageUploader>
< /formElements>
< /field>
< /fieldset>
< /fieldset>
< /form>

Step 6 :  Override Header Block


Override the header block to utilize the new custom field in Logo.php.

M2\Theme\Block\Html\Header\Logo.php

namespace M2\Theme\Block\Html\Header;

use Magento\Theme\ViewModel\Block\Html\Header\LogoPathResolverInterface;

class Logo extends \Magento\Framework\View\Element\Template

{

    protected $_template = 'Magento_Theme::html/header/logo.phtml';

 protected $_fileStorageHelper;

        public function __construct(

        \Magento\Framework\View\Element\Template\Context $context,

        \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageHelper,

        array $data = []

    ) {

        $this->_fileStorageHelper = $fileStorageHelper;

        parent::__construct($context, $data);

    }

               public function getMobileLogoSrc()

    {

                              $this->_data['sticky_logo_src_mob'] = $this->_scopeConfig->getValue(

                'design/header/sticky_logo_src_mob',

                \Magento\Store\Model\ScopeInterface::SCOPE_STORE

            );

        if (empty($this->_data['sticky_logo_src_mob'])) {

            $this->_data['sticky_logo_src_mob'] = $this->_getLogoUrl();

        }

        return $this->_data['sticky_logo_src_mob'];

    }

 

    protected function _getLogoUrl()

    {

        $path = null;

        /** @var LogoPathResolverInterface $logoPathResolver */

        $logoPathResolver = $this->getData('logoPathResolver');

        if ($logoPathResolver instanceof LogoPathResolverInterface) {

            $path = $logoPathResolver->getPath();

        }

        $logoUrl = $this->_urlBuilder

                ->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]) . $path;

 

        if ($path !== null && $this->_isFile($path)) {

            $url = $logoUrl;

        } elseif ($this->getLogoFile()) {

            $url = $this->getViewFileUrl($this->getLogoFile());

        } else {

            $url = $this->getViewFileUrl('images/logo.svg');

        }

        return $url;

    }

 

    /**

     * If DB file storage is on - find there, otherwise - just file_exists

     *

     * @param string $filename relative path

     * @return bool

     */

    protected function _isFile($filename)

    {

        if ($this->_fileStorageHelper->checkDbUsage() && !$this->getMediaDirectory()->isFile($filename)) {

            $this->_fileStorageHelper->saveFileToFilesystem($filename);

        }

 

        return $this->getMediaDirectory()->isFile($filename);

    }

}

 

Step 7 :  Enable and Deploy the Module


Run Magento CLI commands to enable the module and deploy static content.


bin/magento module:enable M2_Theme

bin/magento setup:upgrade

bin/magento setup:di:compile

bin/magento setup:static-deploy -f

bin/magento cache:clean

bin/magento cache:flush

 

Conclusion

Adding a custom field in the Magento 2 design configuration is a powerful way to enhance your store's functionality and user experience. It provides mobile optimization, enhanced branding, improved flexibility, simplified management, and personalization. This small customization can have a big impact on how your store is perceived and managed, making it a valuable addition to your Magento toolkit.

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.