How To

How to Add Image Field on CMS Page in Magento 2?

Hello Magento Friends,

In this blog, I will guide you through the steps to add an image field to a CMS page in Magento 2.

In Magento 2, the CMS (Content Management System) plays a vital role in managing static pages, such as homepages, about us pages, and contact pages. By default, Magento 2 provides text fields for content editing on CMS pages. However, in some cases, you might want to include images to enrich the content and provide a visually appealing experience for your customers. 

Let’s look at the steps for how to add an image field on the CMS page in Magento 2.

Steps to Add Image Field on CMS Page in Magento 2:

Step 1: In the first step, we need to create a db_schema.xml file inside the extension at the following path.

{{magento_root}}/app/code/Vendor/Module/etc/db_schema.xml

Now add the code as follows.

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="cms_page" resource="default" engine="innodb" comment="Cms Page">
        <column length="255" name="custom_image" nullable="false" xsi:type="varchar"/>
    </table>
</schema>

Step 2: After that, we need to create a cms_page_form.xml to define the CMS page form with the image field File inside the extension at the following path.

{{magento_root}}/app/code/Vendor/Module/view/adminhtml/ui_component/cms_page_form.xml

Then include the below-mentioned code

<?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="content">
        <field name="custom_image" formElement="imageUploader">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="label" xsi:type="string" translate="true">Page Image</item>
                    <item name="formElement" xsi:type="string">imageUploader</item>
                    <item name="source" xsi:type="string">page</item>
                    <item name="sortOrder" xsi:type="number">30</item>
                    <item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
                    <item name="required" xsi:type="boolean">false</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

Step 3: After that, we need to register the observer in the event.xml file in the observer File inside the extension at the following path.

{{magento_root}}/app/code/Vendor/Module/etc/events.xml

And add the below piece of code

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="cms_page_prepare_save">
        <observer name="custom_cms_image" instance="Vendor\Module\Observer\SaveCustomImage" />
    </event>
</config>

Step 4: Finally, we need to Save that uploaded image in the observer File inside the extension at the following path.

{{magento_root}}/app/code/Vendor/Module/Observer/SaveCustomImage.php

Now add the code as mentioned below

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;

class SaveCustomImage implements ObserverInterface
{
    protected $dataPersistor;
    protected $uploaderFactory;
    protected $filesystem;

    public function __construct(
        DataPersistorInterface $dataPersistor,
        UploaderFactory $uploaderFactory,
        Filesystem $filesystem)
    {
        $this->dataPersistor = $dataPersistor;
        $this->uploaderFactory = $uploaderFactory;
        $this->filesystem = $filesystem;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $data = $this->dataPersistor->get('cms_page');
        if (!$data) {
            return;
        }

        $image = $data['custom_image'] ?? null;
        if ($image) {
            $uploader = $this->uploaderFactory->create(['fileId' => 'custom_image']);
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $mediaDirectory = $this->filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
            $result = $uploader->save($mediaDirectory->getAbsolutePath('custom_cms_images'));
            $data['custom_image'] = 'custom_cms_images' . $result['file'];
        }

        $observer->getPage()->addData($data);
    }
}

Output:

Conclusion:

You have successfully added an image field to your CMS page in Magento 2. You can also Add Custom Button in Backend CMS Page Section in Magento 2. Share this tutorial with your friends, and stay updated with us for more such tutorials.

Happy Coding!

Click to rate this post!
[Total: 3 Average: 1]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

9 hours ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

2 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

4 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

5 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

5 days ago

8 Best Social Login Apps for Shopify Store in 2024

Running an eCommerce business can be incredibly demanding, leaving entrepreneurs little time to focus on…

5 days ago