🔥 Introducing the Lizha Hyvä Template – Sleek, Fast, and Powerfull Buy Now 🔥

shape-img

Magento 2 extension attributes offer a flexible way to extend core and custom entities without changing their original classes. These attributes are especially useful when working with APIs, enabling additional data to be added to API responses or set via API requests. In this guide, we will walk you through how to create an extension attribute and use it within Magento 2 APIs using the Kiwi_ExtensionAttribute module.


What Are Extension Attributes?

Extension attributes are extra fields that can be added to entities such as products, orders, and customers in Magento 2. Unlike traditional EAV attributes, extension attributes do not automatically store data in the database. Instead, they are dynamically retrieved through plugins or data providers when needed.


Step-by-Step Guide to Creating an Extension Attribute in Magento 2 API

Step 1: Define the Extension Attribute
Start by creating the extension_attributes.xml file to declare the new attribute for the Magento product entity.

đź“‚ app/code/Kiwi/ExtensionAttribute/etc/extension_attributes.xml

<?xml version=”1.0″?>

<extension_attributes xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Api/etc/extension_attributes.xsd”>

    <extension_attribute for=”Magento\Catalog\Api\Data\ProductInterface” code=”custom_attribute”>

        <type>string</type>

    </extension_attribute>

</extension_attributes>


Step 2: Create a Data Interface
Define the getter and setter methods for the new extension attribute.

đź“‚ app/code/Kiwi/ExtensionAttribute/Api/Data/CustomAttributeInterface.php

<?php

namespace Kiwi\ExtensionAttribute\Api\Data;

interface CustomAttributeInterface

{

    public function getCustomAttribute();

    public function setCustomAttribute($customAttribute);

}


Step 3: Create the API Repository
Implement the repository that handles retrieving and setting the extension attribute.

đź“‚ app/code/Kiwi/ExtensionAttribute/Model/CustomAttributeRepository.php

<?php

namespace Kiwi\ExtensionAttribute\Model;

use Kiwi\ExtensionAttribute\Api\CustomAttributeRepositoryInterface;

use Magento\Catalog\Api\ProductRepositoryInterface;

use Magento\Catalog\Api\Data\ProductExtensionFactory;

class CustomAttributeRepository implements CustomAttributeRepositoryInterface

{

    protected $productRepository;

    protected $productExtensionFactory;

    public function __construct(

        ProductRepositoryInterface $productRepository,

        ProductExtensionFactory $productExtensionFactory

    ) {

        $this->productRepository = $productRepository;

        $this->productExtensionFactory = $productExtensionFactory;

    }

    public function getCustomAttribute($sku)

    {

        $product = $this->productRepository->get($sku);

        $extensionAttributes = $product->getExtensionAttributes();

        return $extensionAttributes ? $extensionAttributes->getCustomAttribute() : null;

    }

    public function setCustomAttribute($sku, $value)

    {

        $product = $this->productRepository->get($sku);

        $extensionAttributes = $product->getExtensionAttributes() ?: $this->productExtensionFactory->create();

        $extensionAttributes->setCustomAttribute($value);

        $product->setExtensionAttributes($extensionAttributes);

        $this->productRepository->save($product);

        return $product;

    }

}


Step 4: Register the API Routes
Define the endpoints for getting and setting the custom attribute.

đź“‚ app/code/Kiwi/ExtensionAttribute/etc/webapi.xml

<?xml version=”1.0″?>

<routes xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Webapi/etc/webapi.xsd”>

    <route url=”/V1/products/:sku/custom-attribute” method=”GET”>

        <service class=”Kiwi\ExtensionAttribute\Api\CustomAttributeRepositoryInterface” method=”getCustomAttribute”/>

        <resources>

            <resource ref=”Magento_Catalog::products” />

        </resources>

    </route>

    <route url=”/V1/products/:sku/custom-attribute” method=”POST”>

        <service class=”Kiwi\ExtensionAttribute\Api\CustomAttributeRepositoryInterface” method=”setCustomAttribute”/>

        <resources>

            <resource ref=”Magento_Catalog::products” />

        </resources>

        <data>

            <parameter name=”sku” force=”true”>%sku</parameter>

            <parameter name=”value” xsi:type=”string” force=”true”/>

        </data>

    </route>

</routes>


Step 5: Implement the Plugin to Inject the Attribute
A plugin is used to inject the attribute value into API responses dynamically.

đź“‚ app/code/Kiwi/ExtensionAttribute/Plugin/ProductExtension.php

<?php

namespace Kiwi\ExtensionAttribute\Plugin;

use Magento\Catalog\Api\Data\ProductInterface;

use Magento\Catalog\Api\Data\ProductExtensionFactory;

use Magento\Catalog\Api\ProductRepositoryInterface;

class ProductExtension

{

    protected $productExtensionFactory;

    public function __construct(ProductExtensionFactory $productExtensionFactory)

    {

        $this->productExtensionFactory = $productExtensionFactory;

    }

    public function afterGetById(ProductRepositoryInterface $subject, ProductInterface $product)

    {

        $extensionAttributes = $product->getExtensionAttributes() ?: $this->productExtensionFactory->create();

        $extensionAttributes->setCustomAttribute(‘Custom Value’);

        $product->setExtensionAttributes($extensionAttributes);

        return $product;

    }

}


Step 6: Test the API
Now, test the created API to get and set the custom attribute.

Get Custom Attribute

curl -X GET “https://yourstore.com/rest/V1/products/sample-sku/custom-attribute”

Response:

{

    “custom_attribute”: “Custom Value”

}

Set Custom Attribute

curl -X POST “https://yourstore.com/rest/V1/products/sample-sku/custom-attribute” \

-H “Content-Type: application/json” \

–data ‘{“value”:”New Custom Value”}’

Response:

{

    “custom_attribute”: “New Custom Value”

}


Conclusion

Magento 2’s extension attributes offer a powerful way to extend your entities dynamically without modifying core files. With this guide, you’ve successfully:

  • Defined a new extension attribute.
  • Created an API to retrieve and set the attribute.
  • Implemented a plugin to inject the attribute values into API responses.
  • Tested your API to ensure everything works as expected.

Magento 2 provides a robust foundation for creating secure online stores, but maintaining strong security requires an ongoing, proactive approach. With the ever-evolving landscape of cyber threats, it’s essential to adopt the right security measures to safeguard your online business. In this blog, Kiwi Commerce explores some effective strategies to enhance the security of your Magento 2 store and ensure your customers’ data remains protected.

1. Keep Magento and Extensions Updated

One of the most crucial aspects of Magento 2 security is keeping both the platform and all installed extensions up to date. Security patches are released regularly to address newly discovered vulnerabilities, and outdated software becomes an easy target for cyber attackers. To maintain security, schedule regular updates, test them in a staging environment, and deploy them as soon as they are confirmed to be stable.

Why It Matters:
By updating Magento and extensions promptly, you reduce the risk of known security flaws being exploited. Regular updates help ensure that your store remains protected from emerging threats.

2. Enable Two-Factor Authentication (2FA)

Magento 2 supports Two-Factor Authentication (2FA) out of the box, which adds an extra layer of security to your admin accounts. With 2FA enabled, even if an attacker obtains your password, they won’t be able to access your account without the second authentication step, which typically involves a mobile app or email.

Why It Matters:
2FA significantly enhances the security of your store by requiring more than just a password to gain access, making it much harder for attackers to infiltrate your system.

3. Use a Unique Admin URL

Default admin URLs like /admin are easy targets for attackers who scan websites for common login pages. By changing your admin URL to something unique, you make it significantly harder for automated attacks or brute-force login attempts to succeed.

Why It Matters:
A unique admin URL adds a layer of obscurity to your store’s backend, reducing the chances of cyber attackers targeting your login page.

4. Implement a Web Application Firewall (WAF)

A Web Application Firewall (WAF) serves as your first line of defence against malicious traffic. A WAF can filter out harmful requests before they reach your Magento store, blocking threats such as SQL injection, cross-site scripting (XSS), and other common attacks. Popular WAF services like Cloudflare or Sucuri can be easily integrated with Magento.

Why It Matters:
By implementing a WAF, you proactively block malicious traffic and reduce the likelihood of attacks affecting your store. It’s an essential security tool for protecting your website from a range of threats.

5. Enforce HTTPS for All Connections

Installing an SSL certificate ensures that all data exchanged between your Magento store and users is encrypted. HTTPS not only helps protect sensitive customer information but also serves as a trust signal, reassuring your visitors that their data is secure. Additionally, HTTPS is a ranking factor for search engines, which can benefit your store’s visibility.

Why It Matters:
Secure connections via HTTPS are essential for customer trust and SEO performance. Without HTTPS, your store is vulnerable to data breaches, and you could lose potential customers.

6. Strengthen Server Security

Securing your hosting server is just as important as securing your Magento 2 store. To protect against intrusions, restrict access to critical files (such as env.php), close unused ports, and configure tools like fail2ban to block suspicious IP addresses. You may also want to consider using a dedicated or cloud hosting provider that offers enhanced security options.

Why It Matters:
Securing your server ensures that attackers can’t gain access to critical files or use your server as a point of entry to compromise your store.

7. Use Strong Admin and User Credentials

Weak passwords continue to be a common cause of data breaches. Enforce strong, unique passwords for all admin accounts and user logins, combining uppercase and lowercase letters, numbers, and special characters. Additionally, conduct regular audits of user roles and permissions, removing inactive or unnecessary accounts to minimise potential attack vectors.

Why It Matters:
Strong passwords and proper access control reduce the risk of unauthorised access, making it more difficult for attackers to breach your Magento 2 store.

8. Set Correct File and Directory Permissions

Incorrect file and directory permissions can expose sensitive files to unauthorised users. Ensure that file permissions are set securely, such as 644 for files and 755 for directories. Avoid using overly permissive settings like 777, as this allows anyone to modify files.

Why It Matters:
By properly configuring file and directory permissions, you ensure that only authorised users and processes have access to critical files, preventing unauthorised modifications.

9. Monitor and Review Activity Logs

Magento 2 includes a powerful logging feature that tracks admin activities and system events. By reviewing activity logs regularly, you can spot unusual actions such as multiple failed login attempts, unauthorised file changes, or spikes in resource usage.

Why It Matters:
Regularly monitoring activity logs helps you detect abnormal behaviour before it turns into a serious issue. Proactive log monitoring is essential for identifying potential security breaches early.

10. Defend Against Brute-Force Attacks

Brute-force attacks involve hackers repeatedly attempting to guess login credentials by trying various combinations. To protect against this, limit the number of failed login attempts, enable CAPTCHA on all admin login pages, and implement CAPTCHA on customer account creation forms.

Why It Matters:
Brute-force attacks are one of the most common ways cybercriminals attempt to gain access to accounts. Limiting failed attempts and using CAPTCHA makes it much more difficult for attackers to succeed.


Final Thoughts by Kiwi Commerce

Securing your Magento 2 store is an ongoing process that requires a multi-layered approach. By implementing the strategies mentioned above, you can significantly enhance your store’s security and protect both your business and your customers from potential threats. Whether you’re updating your software, enabling two-factor authentication, or monitoring activity logs, each step plays a crucial role in safeguarding your store.

Investing in the security of your online store is not only essential for protecting sensitive data but also for maintaining customer trust and improving your store’s overall performance. Take action today with Kiwi Commerce and ensure your Magento 2 store remains safe, secure, and ready for growth.

In the fast-paced world of e-commerce, where customer expectations evolve rapidly, staying ahead requires more than just a platform—it demands a partner. Magento, part of the Adobe family, serves as that partner, empowering businesses to innovate, lead, and scale. Here’s why Magento is not just a platform but a movement, reshaping online commerce globally.


Why Choose Magento? Core Advantages by Kiwi Commerce

1. Unparalleled Customisation

Magento offers unmatched flexibility for businesses of all sizes. From start-ups to global enterprises, its open-source architecture enables developers to craft bespoke solutions tailored to unique business needs. Whether it’s custom themes, intricate workflows, or dynamic extensions, Magento delivers.

2. Seamless Scalability

Scaling is often a challenge with e-commerce success, but not with Magento. Its robust infrastructure ensures your store is prepared for growth, from handling high-traffic seasonal spikes to global expansion.

3. AI-Powered Personalisation

Modern consumers demand tailored shopping experiences. Magento, with Adobe Sensei AI, offers:

  • Real-time product recommendations.
  • Predictive customer behaviour analysis.
  • Optimised search results for higher conversions.

Revolutionising the Customer Experience

Progressive Web Apps (PWAs)

Magento’s PWA Studio transforms mobile experiences with lightning-fast load times, offline browsing, and app-like interactions. This technology boosts engagement, reduces bounce rates, and improves retention.

Omnichannel Integration

Magento connects online and offline channels seamlessly, ensuring consistent branding and customer experiences. Retailers can:

  • Sync inventory across physical and digital platforms.
  • Enable click-and-collect services.
  • Provide unified customer support.

International Commerce

Expanding globally is straightforward with Magento, which supports multi-currency, multi-language functionality, and localised tax calculations.


Real Stories: Magento in Action with Kiwi Commerce

Case Study: A Fashion Empire’s Journey

A leading fashion retailer partnered with Kiwi Commerce to leverage Magento, resulting in:

  • A 200% increase in online sales within a year.
  • Seamless integration with social platforms like Instagram and Facebook.
  • Enhanced user experiences, leading to a 50% increase in repeat customers.

Case Study: Small Business, Big Impact

A local artisan collective used Magento and Kiwi Commerce expertise to digitise their marketplace. With Magento’s intuitive admin panel and powerful marketing tools, they achieved:

  • Improved sales and customer engagement.

The Developer Edge

Streamlined Development

Magento’s command-line interface (CLI) simplifies administrative and development tasks, saving time and minimising errors.

Extensibility through Service Contracts

Developers can create scalable, upgrade-safe modules that enhance Magento’s core functionality while maintaining compatibility with future updates.


Security at Its Core

Magento ensures enterprise-level security through:

  • Regular updates and patches.
  • Compliance with global standards.
  • Robust tools like two-factor authentication (2FA) and IP whitelisting.

Looking Ahead: The Future of E-Commerce with Magento

Magento is leading the way in e-commerce innovation, embracing:

  • Headless Commerce: For faster, adaptable storefronts.
  • AI and ML Integrations: Enhancing insights and automating backend processes.
  • Sustainability Initiatives: Supporting eco-conscious businesses with tools like carbon-neutral delivery.

Why Magento and Kiwi Commerce Outshine the Competition

In the ever-expanding e-commerce space, choosing the right platform is critical. Magento, paired with Kiwi Commerce expertise, consistently outperforms competitors with:

  • Unmatched Customisation and Flexibility: An open-source architecture tailored to your unique needs.
  • Seamless Scalability: Built to grow with your business.
  • Advanced Features Out-of-the-Box: A comprehensive suite of tools without reliance on costly add-ons.
  • Global Reach: Multi-currency and multi-language capabilities.
  • Vibrant Community and Marketplace: Thousands of ready-made extensions and integrations.

Conclusion: Why Choose Magento with Kiwi Commerce?

Magento is more than just an e-commerce platform—it’s a foundation for innovation, growth, and success. Whether you’re a budding entrepreneur or a global enterprise, Magento, with Kiwi Commerce, provides the tools, expertise, and community to achieve your goals. Join us in redefining e-commerce—because with Magento and Kiwi Commerce, the possibilities are limitless.

In modern e-commerce platforms, ensuring optimal performance during high-traffic events, such as Black Friday, requires an efficient and scalable backend architecture. One of the most effective ways to achieve this is by integrating a Message Queue (MQ) system, like RabbitMQ, with Magento 2. This integration allows Magento to handle asynchronous processing, improving system efficiency, error management, and scalability. At Kiwi Commerce, we understand the significance of this integration in optimising e-commerce operations.

Understanding RabbitMQ and the Message Queue System

RabbitMQ is an open-source message broker that facilitates communication between applications or microservices by managing messages in queues. It operates using the Advanced Message Queuing Protocol (AMQP) and decouples system components, allowing smoother data flow across networks.

How RabbitMQ Works
  • Producers send messages to exchanges, which then route them to queues based on predefined rules.
  • Consumers retrieve these messages from the queues and process them.

In Magento 2, RabbitMQ handles tasks such as email notifications, order processing, and data indexing, without blocking the main application thread, resulting in greater system efficiency.

Key Components of RabbitMQ in Magento 2

  • Producers (Magento Services)
  • Exchanges (Routing hubs for messages)
  • Queues (Persistent storage for messages)
  • Consumers (Background processors)
  • Bindings (Connections between exchanges and queues)

Magento 2 Architecture with RabbitMQ Integration

Without RabbitMQ

Without RabbitMQ, Magento 2 processes tasks synchronously, meaning users must wait for each task to complete before the next one starts. For instance:

  • Checking inventory
  • Generating invoices
  • Sending order confirmation emails

These tasks often involve interacting with external services, such as email servers or payment gateways, meaning delays in any one of these steps can result in slower performance and a poor user experience.

With RabbitMQ Integration

When RabbitMQ is integrated into Magento 2, tasks such as sending emails, updating inventory, and processing payments are pushed to queues for background consumers to process later. This allows the main application to remain responsive, even under heavy load.

Architectural Breakdown

  1. Customer Frontend: The customer places an order, and the frontend of the Magento application processes the request.
  2. Magento Backend (Admin Panel): The backend handles the core business logic and communicates with the database to store order data. Tasks that need to be processed later (e.g., email confirmations, stock updates) are placed in the message queue.
  3. RabbitMQ (Message Broker): RabbitMQ’s exchange receives messages from Magento and routes them to the appropriate queues for storage until they are processed.
  4. Queue Consumers: These background processors retrieve messages from the queues and process them. For example, an EmailConsumer processes email notifications, while an OrderProcessor handles order verification, payment confirmation, or stock updates.

Setting Up RabbitMQ Integration

Step 1: Install RabbitMQ on Your Server

Before you can integrate RabbitMQ with Magento, it needs to be installed and configured on your server. Here’s how you can install RabbitMQ on AlmaLinux (or similar distributions):

bash

Copy

sudo dnf install erlang

sudo dnf install rabbitmq-server

sudo systemctl enable rabbitmq-server

sudo systemctl start rabbitmq-server

Step 2: Enable RabbitMQ in Magento

After installing RabbitMQ, enable it within Magento by configuring the message queue driver in the env.php file:

php

Copy

‘queue’ => [

    ‘driver’ => ‘rabbitmq’,

    ‘host’ => ‘localhost’,

    ‘port’ => ‘5672’,

    ‘user’ => ‘guest’,

    ‘password’ => ‘guest’,

],

Step 3: Configure Consumers in Magento

Magento’s consumers listen to RabbitMQ queues and process messages as they arrive. To create a custom consumer, define it in the queue_consumer.xml file:

xml

Copy

<?xml version=”1.0″?>

<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

       xsi:noNamespaceSchemaLocation=”urn:magento:framework:MessageQueue/etc/queue_consumer.xsd”>

    <consumer name=”vendor_module_order_processor” queue=”vendor_module_order_queue” />

</config>

Then, create the corresponding consumer class:

php

Copy

namespace Vendor\Module\Consumer;

use Magento\Framework\MessageQueue\ConsumerInterface;

use Psr\Log\LoggerInterface;

class OrderProcessor implements ConsumerInterface

{

    protected $logger;

    public function __construct(LoggerInterface $logger)

    {

        $this->logger = $logger;

    }

    public function process($message)

    {

        $this->logger->info(‘Processing order: ‘ . $message);

        // Custom processing logic, e.g., create order invoice

    }

}

Performance Improvements with RabbitMQ

By enabling asynchronous processing, RabbitMQ brings significant performance enhancements:

  • Asynchronous Processing: Resource-intensive tasks are handled by queue consumers, ensuring the front-end store remains responsive even under high load.
  • Scalability: As traffic increases, more consumers can be added to handle additional queues and higher message volumes.
  • Error Handling: Failed tasks can be retried, requeued, or logged for further investigation, preventing failures from impacting the customer experience.

Real-World Examples

Case Study 1: Legacy Order Processing
  • Challenge: A legacy order processing system could only handle 500 orders per minute.
  • Solution: RabbitMQ integration enabled asynchronous order fulfilment, leading to significant performance improvements.
Case Study 2: Handling Black Friday Traffic

One large retailer experienced a surge in traffic during Black Friday, causing delays in order processing and negatively affecting user experience.

  • Challenge: Managing high traffic during Black Friday led to slow order processing.
  • Solution: Implementing RabbitMQ allowed tasks to be offloaded to background consumers, which processed them in parallel, keeping the site responsive.
  • Outcome: The retailer managed up to five times more traffic without any significant slowdowns, resulting in higher sales and improved customer satisfaction.

Advanced Configuration: Dead Letter Exchange (DLX)

A Dead Letter Exchange (DLX) in RabbitMQ handles messages that have expired, been rejected, or cannot be processed. This mechanism ensures failed messages are rerouted for further inspection, preventing data loss and improving error recovery.

Example DLX setup:

php

Copy

$channel->exchange_declare(‘dead_letter_exchange’, ‘direct’, false, true, false);

$channel->queue_declare(‘product.queue’, false, true, false, false, false, new AMQPTable([

    ‘x-dead-letter-exchange’ => ‘dead_letter_exchange’,

    ‘x-message-ttl’ => 3600000

]));

Security Considerations

When integrating RabbitMQ with Magento 2, it is crucial to secure the communication between clients and the broker. Enabling SSL/TLS encryption ensures that messages and credentials are protected against interception.

SSL Configuration example:

xml

Copy

<amqp>

    <ssl>

        <enabled>true</enabled>

        <cacert>/path/to/ca_certificate.pem</cacert>

        <cert>/path/to/client_certificate.pem</cert>

        <key>/path/to/client_key.pem</key>

    </ssl>

</amqp>

Conclusion

By integrating RabbitMQ with Magento 2, stores can dramatically improve their backend processing capabilities, efficiently handle high traffic loads, and scale operations during peak periods. RabbitMQ’s asynchronous processing ensures that Magento remains responsive, even when dealing with resource-intensive tasks, ultimately leading to a better user experience and enhanced operational efficiency.

At Kiwi Commerce, we specialise in helping businesses integrate RabbitMQ with Magento 2 to streamline backend operations and optimise performance. If you’re looking to improve the scalability and performance of your Magento 2 store, RabbitMQ is an essential solution.

Magento 2 drives the success of many online businesses, but its advanced technology often operates behind the scenes. This guide offers an easy-to-understand look at some of the key features of Magento 2, explaining the tech that powers your store to keep everything running smoothly, even if you’re not technically inclined.

1. Cache Systems: Improving Speed and Efficiency

What Is It?
Magento 2 uses cache systems to store frequently requested data temporarily, speeding up your website’s loading time. Think of it as a digital filing system: instead of fetching the same data repeatedly, Magento pulls it from a pre-sorted “cache,” speeding up the process.

Why Does It Matter?

  • Faster Page Loads: By storing frequently accessed data, Magento ensures your site loads quickly, so customers can view products and complete transactions more easily.
  • Better User Experience: Speed is vital for keeping visitors on your site and reducing the likelihood of them leaving before making a purchase.

Types of Magento Cache:

  • Full Page Cache (FPC): Saves complete web pages, so Magento simply serves the saved page rather than rebuilding it.
  • Block Cache: Stores parts of a page, such as product lists, to avoid reloading them each time.

2. GraphQL: Streamlining Data Communication

What Is It?
GraphQL is a modern solution for data exchange between your site’s front-end and back-end. It’s more efficient than traditional APIs, allowing faster, more flexible data transfers between your website and server.

Why Does It Matter?

  • Efficient Data Requests: GraphQL only asks for the exact data needed, instead of loading unnecessary information, similar to ordering a specific item from a menu.
  • Faster Interactions: By loading only the necessary data, your store responds more quickly, providing a smoother user experience.

Benefit for Your Store:
GraphQL enhances Magento 2’s Progressive Web Application (PWA) features, delivering faster content without reloading entire pages, creating a dynamic, app-like experience for customers.

3. Progressive Web Applications (PWA): Merging Web and App Experiences

What Is It?
PWA technology allows your store to function like a mobile app without needing to download anything. Magento 2’s support for PWAs makes online shopping faster, more reliable, and more engaging, all without the need for an app installation.

Why Does It Matter?

  • Optimised for Mobile: PWAs ensure your site loads quickly on mobile devices and even works offline in areas with low connectivity.
  • Push Notifications: Engage customers with timely alerts about sales, promotions, or cart updates, just like a mobile app would.
  • Better Than Regular Websites: PWAs cache content more effectively, improving performance and giving your store an app-like experience without taking up storage.

Breaking Down the Key Magento 2 Features:

  • Cache System = Quicker Access
    Analogy: Like a librarian retrieving a book quickly, rather than waiting for it to be printed.
    User Benefit: Faster page loading, which improves customer satisfaction and engagement.
  • GraphQL = Simplified Data Requests
    Analogy: GraphQL is like a waiter taking your exact order, rather than offering a full menu.
    User Benefit: Reduced data load, making browsing and transactions faster and smoother.
  • PWA = App-Like Experience Without Downloading
    Analogy: PWAs make websites feel like apps, without requiring users to download anything.
    User Benefit: Seamless and fast performance, especially on mobile devices.

Why This Technology Matters for Online Store Owners

For merchants using Magento 2, these improvements bring numerous advantages:

  • Enhanced Customer Satisfaction: Faster load times and improved mobile functionality provide a better shopping experience.
  • Optimised Store Performance: Your site runs more reliably on all devices and platforms.
  • Time and Cost Savings: Pre-built features like GraphQL save development time, making future upgrades easier.

At Kiwi Commerce, we specialise in helping you harness the power of Magento 2’s advanced technology. Our expertise ensures your store is optimised for performance, speed, and customer engagement, helping your business thrive online.

Magento and Shopify are two of the most popular eCommerce platforms, each offering unique strengths. Choosing the right platform is a crucial decision for any online business. To help you decide which is the best fit for your store, let’s compare Magento and Shopify across several key aspects.


1. Ease of Use: Shopify Wins for Beginners

  • Shopify:
    Known for its intuitive interface, Shopify is ideal for beginners. It requires no coding knowledge to set up and manage a store. With its drag-and-drop features, customisation is quick and straightforward.
  • Magento:
    Magento is more complex and is best suited for developers or businesses with technical support. It offers unparalleled customisation, but the steep learning curve may intimidate beginners.

Verdict: Shopify is the easier choice for those just starting their eCommerce journey.


2. Customisation: Magento Offers More Control

  • Shopify:
    Shopify provides a range of themes and apps for customisation, but advanced modifications often require coding. It may not handle the requirements of large or highly customised stores as well.
  • Magento:
    As an open-source platform, Magento gives developers full control to create unique designs and implement advanced features. Its flexibility makes it a go-to for businesses seeking a tailored solution.

Verdict: Magento is ideal for businesses needing complete control and extensive customisation.


3. Pricing: Shopify is Budget-Friendly, Magento is Flexible

  • Shopify:
    Shopify operates on a fixed pricing structure with monthly plans. However, costs can rise with additional apps and transaction fees.
  • Magento:
    Magento Open Source is free to download, but you’ll need to cover hosting, domain, and development costs. Magento Commerce (Adobe Commerce) is a premium option for large enterprises.

Verdict: Shopify is more predictable in terms of cost, while Magento offers flexibility but may require a higher initial investment.


4. Features: Magento Leads in Advanced Tools

  • Shopify:
    Shopify offers essential eCommerce features like payment gateways, SEO tools, and analytics, making it a strong choice for small to medium-sized businesses.
  • Magento:
    Magento stands out with advanced tools such as multi-store management, B2B functionality, and unlimited product options. These features make it well-suited for large, complex operations.

Verdict: Magento takes the lead for feature-heavy, scalable stores.


5. SEO Capabilities: Both Are Strong

  • Shopify:
    Shopify simplifies SEO with built-in tools and automatic sitemaps. However, its URL structure has limited customisation options.
  • Magento:
    Magento excels in SEO with advanced features, offering full control over meta tags, URL structures, and redirects. It’s a great choice for businesses with a strong focus on search engine optimisation.

Verdict: Magento offers more flexibility for SEO, but Shopify’s built-in tools are easier to use.


6. Support: Shopify Has Better Customer Support

  • Shopify:
    Shopify provides 24/7 customer support via live chat, email, and phone, making it ideal for quick problem resolution.
  • Magento:
    Magento relies heavily on its community for support. Dedicated customer support is only available with paid plans like Adobe Commerce.

Verdict: Shopify wins in customer support with its accessible, round-the-clock assistance.


7. Scalability: Magento is Built for Growth

  • Shopify:
    Shopify performs well for small to medium-sized stores, but handling large-scale operations can pose challenges.
  • Magento:
    Magento is designed for scalability, supporting high traffic, complex catalogues, and multiple stores with ease.

Verdict: Magento is the better choice for businesses planning significant growth.


Which Platform Should You Choose?

  • Choose Shopify if:
    You’re a small to medium-sized business looking for an easy-to-use platform with a fixed budget. Shopify’s simplicity and customer support make it an excellent choice for those just starting.
  • Choose Magento if:
    You’re a larger business requiring advanced features, scalability, and complete control over your store’s design and functionality. Magento’s flexibility is unmatched for complex operations.

Conclusion

Both Magento and Shopify are powerful eCommerce platforms, but the right choice depends on your business goals, technical expertise, and budget. Shopify is perfect for beginners and small businesses, while Magento excels for large-scale, feature-heavy stores.

At Kiwi Commerce, we specialise in helping businesses make the most of their chosen platform. Whether you select Magento or Shopify, our team is here to support your eCommerce journey.

Upgrading your Magento 2 store is essential for maintaining security, improving performance, and accessing the latest features. However, this process requires careful planning to avoid downtime or data loss. In this blog, Kiwi Commerce provides a detailed, step-by-step guide to safely upgrading your Magento 2 store.

Step 1: Back Up Your Store

Creating a comprehensive backup is the first and most critical step. This ensures you can restore your store if anything goes wrong during the upgrade. Key components to back up include:

  • Database Backup: Export your database to secure customer, product, and sales data.
  • File Backup: Save all store files, including themes, extensions, and configurations. Store them in a remote repository or locally. Don’t forget to back up media files to a Content Delivery Network (CDN) or another convenient location.

Backup composer.json: Use the command:
bash
Copy code
cp composer.json composer.json.bak

You can perform backups manually or use hosting tools provided by your hosting provider.


Step 2: Check System Requirements

Each Magento 2 version has specific system requirements for PHP, MySQL, and other dependencies. Review the Magento 2 System Requirements to ensure your server environment is compatible.


Step 3: Enable Maintenance Mode

Activating maintenance mode restricts user access during the upgrade, ensuring customers do not encounter errors. Use the following command:

bash

Copy code

php bin/magento maintenance:enable

Step 4: Upgrade Your Magento 2 Store

Follow these steps to upgrade your Magento 2 store using Composer:

Run the Composer require command:
bash
Copy code
composer require magento/<product> <version> –no-update

  1. Replace:
    • <product> with either product-community-edition or product-enterprise-edition, depending on your installation.
    • <version> with the target Magento version.

Update dependencies:
bash
Copy code
composer update

Run setup commands to upgrade the database schema, compile dependencies, and regenerate static content:
bash
Copy code
php bin/magento setup:upgrade  

php bin/magento setup:di:compile  

php bin/magento setup:static-content:deploy

Step 5: Test the Upgrade in a Staging Environment

Before making the upgraded store live, test it thoroughly in a staging environment.

  • Core Features: Verify the checkout process, product pages, navigation, and the admin panel.
  • Extensions: Ensure all third-party extensions are compatible with the new Magento version. Upgrade any incompatible extensions.
  • Customisations: Test custom themes and code for compatibility.

Step 6: Resolve Issues

If you encounter issues during the upgrade:

  • Magento Logs: Review logs in the var/log and var/report directories for detailed error messages.
  • Composer Errors: Fix any dependency conflicts identified by Composer.

Step 7: Disable Maintenance Mode

Once the upgrade is successful and tested, disable maintenance mode using the command:

bash

Copy code

php bin/magento maintenance:disable

Step 8: Reindex and Clear Cache

Reindex and clear your cache to ensure optimal performance. Use the following commands:

bash

Copy code

php bin/magento indexer:reindex  

php bin/magento cache:clean

Step 9: Monitor Your Store

After upgrading, closely monitor your store to identify and resolve potential issues:

  • Performance: Check page load times and server response times.
  • Functionality: Ensure both customer-facing and admin features are working correctly.
  • Error Logs: Regularly review error logs to address any outstanding issues.

Conclusion

Upgrading your Magento 2 store is essential for maintaining a competitive edge in the e-commerce market. By following these steps, you can minimise risks and ensure a smooth transition. With proper preparation and testing, your store will be ready to take full advantage of the latest features and enhanced performance offered by Magento 2.

Stay ahead in e-commerce with Kiwi Commerce’s trusted expertise in Magento development and support.

Magento is a powerful e-commerce platform, widely chosen for its flexibility and scalability. However, the complexity of Magento 2 also brings potential challenges for developers and store owners. Without proper planning and technical implementation, the benefits of Magento can be easily undermined by common development mistakes. These errors can affect the site’s performance, security, SEO rankings, and overall user experience.

This blog explores some of the most common Magento development mistakes from a technical perspective, and offers actionable solutions to ensure the platform functions at its highest potential.

1. Neglecting Mobile Optimisation

Mobile shopping continues to rise, with the majority of consumers now shopping on smartphones and tablets. Magento’s default templates are responsive, but failing to make the most of mobile-first development can lead to missed sales opportunities.

Technical Issue: Lack of mobile optimisation can lead to slow page loads, poor layout, and a frustrating user experience on mobile devices.

Best Practices:

  • Custom Mobile Theme Development: If your business requires a unique look, consider developing a custom mobile theme that adapts seamlessly to mobile screens.
  • Mobile-first Design: Optimise your CSS and HTML structure for mobile devices first. This helps avoid issues like long load times on smaller screens.
  • Touch-Friendly Elements: Ensure elements like buttons, navigation menus, and forms are touch-friendly and easy to interact with on mobile.

2. Inadequate Site Speed Optimisation

Site speed is a critical factor in both user experience and SEO. Magento is feature-rich, which means it has the potential to be slow if not properly optimised. High load times can lead to a higher bounce rate and a reduction in conversions.

Technical Issue: Out-of-the-box Magento installations often do not fully optimise site speed, especially on larger stores with numerous products and categories.

Best Practices:

  • Enable Full Page Cache (FPC): Use Magento’s full-page caching feature to reduce the number of requests to the server. Enabling FPC speeds up page loading by serving static content to returning visitors.
  • Optimise Images: Use tools like ImageMagick or external services like TinyPNG to compress and optimise images for quicker loading times. Magento allows the use of WebP images for even better compression.
  • Leverage Varnish Cache: Varnish is a web accelerator that can be installed on the server to cache dynamic content. It works in tandem with Magento’s caching mechanisms to significantly improve site performance.
  • Use a Content Delivery Network (CDN): A CDN caches content across multiple servers, which reduces latency and ensures faster delivery of your assets to users based on their geographic location.

3. Failure to Implement Security Best Practices

Magento stores can become prime targets for cyber-attacks, making security a top priority. Magento’s built-in security features can be very effective when configured properly, but many store owners overlook important security measures.

Technical Issue: Using outdated Magento versions or failing to apply security patches leaves stores open to exploits.

Best Practices:

  • Regularly Update Magento: Always apply the latest Magento updates and security patches. Magento’s security team regularly releases updates that fix known vulnerabilities.
  • Implement Two-Factor Authentication (2FA): Add an extra layer of security to your Magento admin panel by enabling 2FA. This adds an extra step when logging in and reduces the risk of unauthorised access.
  • Use a Secure Hosting Environment: Choose a secure hosting solution that supports Magento and complies with security standards such as PCI DSS. Ensure that the server is configured with proper firewall and intrusion detection systems.
  • Encrypt Sensitive Data: Ensure that sensitive data such as payment details are encrypted using SSL (Secure Socket Layer) certificates. Magento supports SSL out-of-the-box, but the configuration must be checked regularly.

4. Improper SEO Configurations

Magento provides several SEO features to help optimise your store for search engines. However, many Magento store owners fail to leverage these features fully, which can impact their rankings and organic traffic.

Technical Issue: Poorly optimised product pages, missing meta tags, and improper use of URLs can hinder your store’s SEO performance.

Best Practices:

  • Optimise URLs for SEO: Use clean, descriptive URLs that include relevant keywords. Magento automatically creates URLs, but they often require customisation to improve readability and SEO.
  • Meta Tags: Ensure that each product and category page includes relevant and unique meta titles, descriptions, and keywords. These meta tags should accurately reflect the content and be optimised for search queries.
  • Rich Snippets for Products: Use Magento’s structured data capabilities (e.g. schema.org markup) to provide search engines with additional information about products such as price, availability, and ratings.
  • Sitemap Generation: Use Magento’s built-in functionality or a plugin to automatically generate XML sitemaps and submit them to Google Search Console. This ensures your site’s pages are indexed correctly.

5. Complex User Experience (UX) and Checkout Process

A complicated and confusing user experience can drive potential customers away, especially in the checkout phase. Magento’s default checkout process can be streamlined, but customisation is often needed to simplify the process.

Technical Issue: A cluttered or lengthy checkout process can increase cart abandonment rates and reduce conversions.

Best Practices:

  • Simplified Checkout: Customise your checkout process to reduce friction. Magento allows for the creation of a one-page checkout, which can be further enhanced with features like guest checkout and payment integration.
  • Progressive Disclosure: Use progressive disclosure on forms to only show necessary fields based on previous user input. For example, hide the shipping address fields until the user selects a shipping option.
  • Auto-fill Forms: Implement auto-fill for returning customers and use geolocation to pre-populate addresses. This saves time and improves the overall experience.

6. Lack of Testing and Quality Assurance (QA)

Magento stores, especially those with large inventories, can be complex, and minor issues can lead to a poor user experience or even cause the store to break.

Technical Issue: Not thoroughly testing the store during development can result in broken functionalities or performance issues after deployment.

Best Practices:

  • Testing Across Browsers and Devices: Ensure that your Magento store is fully functional across all browsers (Chrome, Firefox, Safari, etc.) and mobile devices. This can be done using browser testing tools like BrowserStack.
  • Load Testing: Simulate high-traffic scenarios to check how your store performs under stress. This helps to identify performance bottlenecks before peak shopping periods, such as Black Friday or Christmas.
  • Test Payment Gateways: Regularly test payment gateway integrations, especially when adding new payment methods or updating payment providers, to ensure smooth transactions.

7. Overlooking Integrations with Third-Party Tools

Magento can be integrated with a variety of third-party tools, from ERP and CRM systems to email marketing platforms and analytics tools. However, failing to integrate effectively with these systems can result in inefficiencies and missed opportunities for automation.

Technical Issue: Not connecting your Magento store to external tools, or relying on outdated integrations, can slow down operations and reduce the overall effectiveness of your store.

Best Practices:

  • ERP Integration: Ensure that your Magento store is integrated with your ERP system, such as Microsoft Dynamics or SAP, to automate inventory management, order processing, and customer relationship management (CRM).
  • Email Marketing Integration: Use tools like Mailchimp or Klaviyo to integrate email marketing with your store. This enables you to set up automated email campaigns, personalised offers, and cart recovery emails.
  • Google Analytics Integration: Set up Google Analytics and Magento’s built-in reporting features to track important KPIs such as conversion rates, sales, and customer behaviour.

8. Not Using a Version Control System

Magento development often involves multiple developers working on a project. Without a version control system (VCS), managing changes to the codebase can become chaotic, leading to code conflicts and a disorganised workflow.

Technical Issue: Working on Magento codebase without version control can lead to problems like lost code, hard-to-track changes, and difficulty when rolling back to a previous version.

Best Practices:

  • Implement Git: Use Git, one of the most widely-used version control systems, to manage changes to your Magento store’s codebase. Git helps track modifications and allows for collaborative development.
  • Use Branching and Merging: Make use of branches for new features or bug fixes, and merge them back into the main production branch after thorough testing.
  • Versioning and Deployment: Implement a clear versioning system and use continuous integration/continuous deployment (CI/CD) tools to streamline deployment processes.

Conclusion: Optimising Magento for E-commerce Success

Avoiding these common Magento development mistakes requires a careful and methodical approach. By following best practices related to mobile optimisation, site speed, security, SEO, UX, and testing, Magento store owners can build a more secure, faster, and more user-friendly platform.

To achieve long-term success with Magento, businesses should ensure they are leveraging the platform’s features to their fullest potential and using the right integrations to enhance their store’s capabilities. Whether you’re working with in-house developers or third-party agencies, investing time in optimising your Magento store will result in a better overall customer experience, improved performance, and higher sales.

To stay ahead of your competitors, avoid these common pitfalls, and ensure your Magento store is running at peak performance.

In today’s competitive online marketplace, choosing the right e-commerce platform is essential for the success of your business. With numerous options available, Magento stands out as a top contender for businesses looking to build robust, scalable, and flexible online stores. Whether you’re a small start-up or a large enterprise, Magento offers a range of benefits that can help your e-commerce business thrive.

In this blog, we’ll explore the 5 key benefits of using Magento for your e-commerce business, and how it can provide the tools you need to deliver an exceptional online shopping experience.


1. Scalability for Business Growth

As your business grows, your e-commerce platform needs to scale accordingly. One of the standout features of Magento is its scalability, making it an ideal choice for businesses that anticipate growth or need to handle large product inventories, high traffic volumes, or expanding customer bases.

  • Handle High Traffic and Large Catalogues: Magento’s open-source architecture allows businesses to grow without compromising on performance. The platform can handle thousands of products and customers, which is perfect for businesses with ever-expanding product ranges.
  • Flexible Architecture: Magento’s modular design makes it easy to scale both vertically (increasing server capacity) and horizontally (distributing the load across multiple servers).

For businesses looking to grow and scale efficiently, Magento ensures you won’t have to switch platforms as you expand—keeping long-term costs low and operations smooth.


2. Customisation and Flexibility

Magento offers an unparalleled level of customisation, allowing you to tailor your online store to meet the unique needs of your business. Whether you need custom product pages, unique pricing rules, or a distinctive checkout experience, Magento offers the flexibility to design a store that aligns perfectly with your brand and business goals.

  • Custom Design and Themes: Magento provides extensive options for theme development and custom design features. You can create a website that matches your brand identity while providing a seamless user experience.
  • Third-Party Integration: Magento’s flexibility allows easy integration with third-party tools and services such as ERP systems, payment gateways, shipping providers, and CRM solutions.

If your business requires special features or integrations, Magento’s open-source nature means you can develop and implement almost anything your team needs.


3. SEO Benefits for Better Visibility

Search engine optimisation (SEO) is crucial for any e-commerce website, and Magento is built with SEO in mind. With Magento, businesses have access to a wide range of features that enhance their online visibility and improve search engine rankings.

  • Optimised URL Structure: Magento enables businesses to create SEO-friendly URLs with customisable meta tags, descriptions, and titles for each product, category, and page.
  • Rich Snippets and Schema Markup: Magento supports schema markup, which allows you to display rich snippets in search engine results—improving your click-through rates and visibility.
  • Mobile-Friendly: Magento’s mobile-first approach ensures that your store is responsive and optimised for mobile devices, a key ranking factor for SEO.

With these built-in features, Magento helps your store rank higher in search engine results, making it easier for potential customers to find your products and services online.


4. Enhanced Security Features

Security is one of the top concerns for any e-commerce business, especially when it comes to handling sensitive customer information such as credit card details and personal data. Magento’s robust security features ensure that both you and your customers are protected from online threats.

  • PCI Compliance: Magento is PCI-DSS compliant, meaning it meets the rigorous security standards required for handling credit card transactions.
  • Two-Factor Authentication (2FA): Magento allows you to set up two-factor authentication for admin users, providing an additional layer of security to prevent unauthorised access to your backend.
  • Regular Security Patches: Magento frequently releases security patches to address vulnerabilities, ensuring your store stays protected against emerging threats.

With Magento, you can have peace of mind knowing that your store is equipped with the latest security measures to safeguard your customers and business.


5. Cost-Effective and Open Source

Magento’s open-source platform makes it an affordable option for businesses of all sizes. Unlike many proprietary solutions that require expensive licences and ongoing fees, Magento allows you to build and customise your e-commerce store without incurring hefty upfront costs.

  • No Licensing Fees: Since Magento Open Source is free to use, you only pay for hosting, development, and customisation costs. This makes it a highly cost-effective option for businesses that want to control their budget.
  • Wide Developer Community: Magento has a large, active community of developers, designers, and experts who contribute to the platform, meaning you can find a wealth of resources and support without having to rely on a single vendor.
  • Community Extensions: Many extensions and plugins are available through the Magento marketplace, some of which are free or reasonably priced, helping you enhance your store’s functionality without breaking the bank.

Magento’s low entry cost, combined with its scalability and flexibility, makes it a great choice for both small businesses and large enterprises alike.


Conclusion: Magento Empowers E-Commerce Success

Magento is an exceptional e-commerce platform that offers businesses the tools they need to succeed in the competitive online marketplace. From scalability and customisation to SEO benefits and robust security, Magento enables you to create a personalised and secure shopping experience for your customers.

Whether you are just starting your e-commerce journey or are looking to upgrade your existing store, Magento provides the features and flexibility needed for long-term growth and success.At KiwiCommerce, we specialise in building customised Magento stores that meet your unique business needs. Our team of experts can help you make the most of the platform’s features to ensure your online store is a success.

This article will help you to add your own indexer in Magento 2. Magento 2 has made performance improvements that now allow you to declare one or more shared indexers. You can add a custom indexer using the steps below:

  1. Create indexer class
  2. Create etc/indexer.xml file.
  3. Create etc/mview.xml file.

Example of a custom indexer implementation

In order to push best-selling products to the top of a category listing, you need to process the statistics related to sales which will help in changing the product position dynamically.

1. Create indexer class

Your custom indexer class should implement \Magento\Framework\Indexer\ActionInterface and the indexer should be able to perform three types of operations:

  • executeRow($id) – Processing a single entry from a dictionary.
  • executeList($ids) – Processing a set of dictionary entries.
  • executeFull() – Processing all entities from a specific dictionary.

Create an Indexer folder inside your module’s model folder.

Example: KiwiCommerce\Demo\Model\Indexer;

After creating the Indexer folder, create an indexer class file inside it.

Example:

class CustomIndexer implements \Magento\Framework\Indexer\ActionInterface, \Magento\Framework\Mview\ActionInterface
{
	public function executeFull(); //Should take into account all placed orders in the system

	public function executeList($ids); //Works with a set of placed orders (mass actions and so on)

	public function executeRow($id); //Works in runtime for a single order using plugins

	public function execute($ids); //Used by mview, allows you to process multiple placed orders in the "Update on schedule" mode 	
}

2. Create etc/indexer.xml file.

Create the indexer.xml file inside the etc folder of the module.

Example: KiwiCommerce\Demo\etc\indexer.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
   <indexer id="kiwicommerce_indexer" view_id="kiwicommerce_indexer" class="KiwiCommerce\Demo\Model\Indexer\CustomIndexer">
       <title translate="true">Custom Indexer</title>
       <description translate="true">Custom Indexer Description </description>
   </indexer>
</config>

3. Create etc/mview.xml file.

Next, you need to create an mview.xml file inside the etc folder of the module.

Example: KiwiCommerce\Demo\etc\mview.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Mview/etc/mview.xsd">
   <view id="kiwicommerce_indexer" class="KiwiCommerce\Demo\Model\Indexer\CustomIndexer" group="indexer">
       <subscriptions>
           <table name="sales_order" entity_column="entity_id" />
       </subscriptions>
   </view>
</config>

Now when an order is placed, the custom indexer calculates the sorting order of the products and stores this data in the index table so that it can be used in product displaying logic.

You can verify your index on Index Management.

To check the Indexer:

  • Log in to the Magento Admin.
  • Navigate to System > Index Management.

Facing issues with Magento 2 flow or require expertise and support? Connect with us.

It is true that when it comes to building an eCommerce store, Magento would be the first and only choice due to its ability to be customised in order to meet every requirement the owners may have. Sometimes you may want to play with the variety of colours showing, and for that you need to add a colour picker in the Magento 2 System configuration.

At first it may seem a big task and pretty difficult to achieve, however it is really simple. Below are the exact steps to do this:

  • Step 1: Create Attribute
  • Step 2: Create pickcolors.js, color.html, di.xml files
  • Step 3: Create Pool Modifier Class – Style.php

Note: Replace KiwiCommerce/Attributes from entries in this article to your module name.

Step 1: Create Attribute

Create a product attribute for color with the data given below:

attribute code: my_color

Step 2: Create pickcolors.js, color.html, di.xml files

First of all, create pickcolors.js in your module at the path given below and add the following code:

app/code/KiwiCommerce/Attributes/view/base/web/js/form/element/pickcolors.js

define([
    'Magento_Ui/js/form/element/abstract',
    'mageUtils',
    'jquery',
    'jquery/colorpicker/js/colorpicker'
], function (Abstract, utils, $) {
    'use strict';
    return Abstract.extend({
        defaults: {
            placeholder: $.mage.__('Select Colors'),
            elementTmpl: 'KiwiCommerce_Attributes/form/element/color',
            links: {
                value: '${ $.provider }:${ $.dataScope }'
            }
        },
        /**
         * Calls 'initObservable' of parent
         *
         * @returns {Object} Chainable.
         */
        initObservable: function () {
            this._super()
                .observe('disabled visible value')
                .observe('addText');

            return this;
        },
        /**
         * Initializes regular properties of instance.
         *
         * @returns {Abstract} Chainable.
         */
        initConfig: function () {
            var uid = utils.uniqueid(),
                valueUpdate;
            this._super();
            valueUpdate = this.showFallbackReset ? 'afterkeydown' : this.valueUpdate;
            _.extend(this, {
                uid: uid,
                noticeId: 'notice-' + uid,
                valueUpdate: valueUpdate
            });
            console.log(this);
            return this;
        },
        /**
         * Initialize ColorPicker
         *
         * @returns {boolean}
         */
        initColorPicker: function() {
            var self = this;
            $('[data-role="color-picker"]').ColorPicker({
                color: self.value(),
                onShow: function (colpkr) {
                    $(colpkr).fadeIn(200);
                    return false;
                },
                onHide: function (colpkr) {
                    $(colpkr).fadeOut(200);
                    return false;
                },
                onChange: function (hsb, hex) {
                    $('#color-121').css('backgroundColor', '#' + hex);
                    self.userChanges();
                    self.value('#' + hex);
                    self.hasChanged();
                }
            });
            return false;
        },
        /**
         * Validates itself by it's validation rules using validator object.
         * If validation of a rule did not pass, writes it's message to
         * 'error' observable property.
         *
         * @returns {Object} Validate information.
         */
        validate: function () {
            var value   = this.value(),
                result  = this.checkColor(value),
                message = !this.disabled() && this.visible() ? result.message : '',
                isValid = this.disabled() || !this.visible() || result.passed;

            this.error(message);
            this.bubble('error', message);

            if (!isValid) {
                this.source.set('params.invalid', true);
            }

            return {
                valid: false,
                target: this
            };
        },
        checkColor: function(value) {
            var result = {message: $.mage.__('Color is not valid'), passed:false};
            if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value)) {
                result = { message: '', passed: true };
            }
            return result;
        }
    });
});

Create color.html in your module at the path given below and add the following code:
app/code/KiwiCommerce/Attributes/view/base/web/template/form/element/color.html

<div class="swatches-visual-col col-default">
   <div class="swatch_window" style="background: #000000"
        data-bind="
        style: {'background-color': value},
        'aria-describedby': noticeId,
        id: uid, disabled: disabled,
        attr: {title: placeholder},
        hasFocus: focused
   "></div>
</div>

Create di.xml in your module at the path given below and add the following code:

app/code/KiwiCommerce/Attributes/etc/adminhtml/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">
   <virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
       <arguments>
           <argument name="modifiers" xsi:type="array">
               <item name="styles" xsi:type="array">
                   <item name="class" xsi:type="string">KiwiCommerce\Attributes\Ui\Modifier\Product\Style</item>
                   <item name="sortOrder" xsi:type="number">25</item>
               </item>
           </argument>
       </arguments>
   </virtualType>
</config>

Step 3: Create Pool Modifier Class – Style.php

Now, create the class Pool Modifier in your module at the path given below and add the following code:

app/code/KiwiCommerce/Attributes/Ui/Modifier/Product/Style.php

<?php
namespace KiwiCommerce\Attributes\Ui\Modifier\Product;

use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;

class Style extends AbstractModifier
{
   public function modifyMeta(array $meta)
   {
       // Color attribute
       $code = 'my_color';
       // Change component js
       $meta['product-details']['children']['container_' . $code]['children'] = array_replace_recursive(
           $meta['product-details']['children']['container_' . $code]['children'], [
           $code => [
               'arguments' => [
                   'data' => [
                       'config' => [
                           'component' => 'KiwiCommerce_Attributes/js/form/element/pickcolors'
                       ]
                   ]
               ]
           ]
       ]);
       return $meta;
   }

   public function modifyData(array $data)
   {
       return $data;
   }
}

Woohoo, now clear the cache and the result will be displayed as shown in the image below:
Product edit page:

If colour is one of the required attributes then you will see an error message while saving the configuration:

That’s it and you can even customize and use this code to place a colour picker anywhere in Magento. Feel free to reach out to us if you find any issues or errors while implementing this code. Wonderful, colourful Magento! ?

No doubt when things revolve around a jQuery widget in Magento 2, it becomes more tricky and takes hours to see final results on screen. To help when this is the case, we at KiwiCommerce are going to teach you how to create a jQuery widget in Magento 2 following a set of simple steps mentioned below:

  1. Set up a module and select any PHTML file for calling custom jQuery widget.
  2. Create a custom jQuery widget.
  3. data-mage-init attribute for calling the newly created custom widget.
  4. Clear cache and check the form.

1. Set up a module and select any PHTML file for calling custom jQuery widget.

To start you need to create a module and override any phtml file to call your custom widget. In this example, we have the contact phtml file:
app\design\frontend\VendorName\ModuleName\Magento_Contact\templates\form.phtml

2. Create a custom jQuery widget.

The next step is to create a custom js file for creating a custom jquery widget:
app\code\VendorName\Modulename\view\frontend\web\js\kiwicount.js

And below is the basic code structure:

define([
   'jquery',
   'underscore',
   'jquery/ui',
   'Magento_Ui/js/modal/confirm',
   'mage/translate'
], function ($, _) {
   'use strict';

   $.widget('mage.kiwicount',{

	// Your custom code and custom methods will be here 	

 });

    return $.mage.kiwicount;

});

In the define section, state the jquery name that you want or you can simply put jQuery in the define section.
We will be using only jQuery and jQueryUi and as a result we will remove the extra define code from Js. Your code will now look like the below:

define([
   'jquery',
   'jquery/ui'
], function ($, _) {
   'use strict';

   $.widget('mage.kiwicount',{

	// Your custom code and custom methods will be here 	

 });

    return $.mage.kiwicount;

});

3. data-mage-init attribute for calling your custom Widget.

Now let’s get back to our file:
app\design\frontend\VendorName\ModuleName\Magento_Contact\templates\form.phtml

In this file we need to check the number of characters for the text area field and to do so we need to call our custom jQuery widget as shown in below code:

<textarea name="comment" id="comment" title="<?= $block->escapeHtmlAttr(__('Comment')) ?>" class="input-text"
 data-mage-init='{"KiwiCommerce_LoginAsCustomer/js/kiwicount": {"maxlen":"150","messagebox":"charNum"}
}'></textarea>

<span id="charNum"></span>

Where : KiwiCommerce_LoginAsCustomer/js/kiwicount is the path of JS file
Maxlen variable to pass in jquery widget as config array we can get all these arguments there using config.maxlen

Coming back to our custom widget js file, apply the code for validation and receive the argument:

define([
   'jquery'
], function ($, _) {
   'use strict';

   $.widget('mage.kiwicount',{

       _create: function(config,element) {

           this._case = $(this.element);
           $(this._case).keyup(function () {
               var max = config.maxlen;
               var len = $(this.element).length;
               if (len >= max) {
                   $('#'+config.messagebox).text(' you have reached the limit');
               } else {
                   var char = max - len;
                  $('#'+config.messagebox).text(char + ' characters left');

               }
           });
       }
   });

    return $.mage.kiwicount;

});

In the above code snippet, we have added a _create function which is a constructor. However, we only need to check the length of the element so we have directly received the constructor.
We also have two objects, named as config and element:

Config :
The argument which is sent with the variable to this custom jquery widget:
We can access all passing argument using config.messagebox where messagebox is the variable name.

Element :
All property of the current element from where it is called, in our case we have the element <textarea>.
We can use any property of the element using: this.element

4. Clear the cache and flush and check you phtml page(Contact page)

Clear the cache :

php bin\magento cache:clear
or
php bin\magento c:c

Clear the flush:

php bin\magento cache:flush
or
php bin\magento c:f

After that you will be able to find the changes of character limit Jquery widget working on contact us page textarea.

You now know how to create a jQuery widget specifically in Magento 2. If you get stuck while creating this widget we at KiwiCommerce will be happy to help you out. Feel free to reach out to us. ?

Search