Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 42 ยท Projects

Project: Extending Products with a Custom Attribute

Add a custom product attribute in Magento with a data patch, show it with a plugin, layout XML and a ViewModel template, and rehearse every step in runnable PHP stand-ins.

Almost every Magento store wants to add something to products: a "New" badge, a warranty length, an eco label. This project builds exactly that. You will create a custom product attribute with a data patch, expose it as a small badge in category listings with a plugin, and show it on the product page with layout XML, a ViewModel and a PHTML template.

It touches four ideas from earlier lessons at once: EAV, plugins, layouts and blocks with templates. Magento cannot run on this site, so the real PHP, XML and PHTML below are read-only. After each part there is a runnable plain-PHP stand-in (a mini EAV store on SQLite, an interceptor, a template renderer). The stand-ins are not Magento code. They let you see the behavior without a server, and each one says what it imitates.

What you will build

The module is called Acme_ProductBadge. Merchants pick a badge (None, New, Sale) in the product form. Customers see it as a small label on product tiles and on the product page.

flowchart LR
    P["Data patch<br/>creates attribute acme_badge"] --> DB["EAV tables<br/>(value per product and store)"]
    DB --> VM["ViewModel<br/>reads the value"]
    VM --> T["Product page<br/>layout + template"]
    DB --> PL["Plugin on the listing block"]
    PL --> L["Category listing<br/>badge HTML"]

One attribute, two output paths: a plugin for listing tiles and layout plus a template for the product page.

Files you will create:

TEXT
app/code/Acme/ProductBadge/
  registration.php
  etc/module.xml
  etc/frontend/di.xml
  Setup/Patch/Data/AddBadgeAttribute.php
  Model/Attribute/Source/Badge.php
  Plugin/AddBadgeToListing.php
  ViewModel/Badge.php
  view/frontend/layout/catalog_product_view.xml
  view/frontend/templates/badge.phtml

The skeleton files (registration.php, module.xml) are covered in Your First Module. Here we focus on the new parts.

Step 1: the attribute, created by a data patch

Product attributes are rows in the EAV tables, so you create one with EavSetup, inside a data patch. A patch is a class that Magento runs once and records in the patch_list table so it never runs twice.

PHP
<?php
declare(strict_types=1);

namespace Acme\ProductBadge\Setup\Patch\Data;

use Acme\ProductBadge\Model\Attribute\Source\Badge;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class AddBadgeAttribute implements DataPatchInterface
{
    public function __construct(
        private readonly ModuleDataSetupInterface $moduleDataSetup,
        private readonly EavSetupFactory $eavSetupFactory
    ) {
    }

    public function apply(): self
    {
        $this->moduleDataSetup->getConnection()->startSetup();

        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->addAttribute(Product::ENTITY, 'acme_badge', [
            'type' => 'varchar',
            'label' => 'Badge',
            'input' => 'select',
            'source' => Badge::class,
            'required' => false,
            'user_defined' => true,
            'global' => ScopedAttributeInterface::SCOPE_STORE,
            'visible' => true,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'group' => 'General',
        ]);

        $this->moduleDataSetup->getConnection()->endSetup();

        return $this;
    }

    public static function getDependencies(): array
    {
        return [];
    }

    public function getAliases(): array
    {
        return [];
    }
}

Points worth noticing:

  • type is the storage type. A varchar attribute stores its values in catalog_product_entity_varchar, one row per product, attribute and store.
  • input => select plus a source model makes the admin show a dropdown. The source class extends Magento\Eav\Model\Entity\Attribute\Source\AbstractSource and returns the options from getAllOptions().
  • global is the scope. SCOPE_STORE lets each store view override the value; SCOPE_GLOBAL would force one value everywhere.
  • A patch should be idempotent in spirit: Magento will not run it twice, but writing code that tolerates a re-run helps when you test.
  • If the attribute should be grouped with other fields in the product form, you may also assign it to an attribute set; check how your Magento version handles group for existing sets.

After adding the files you run bin/magento setup:upgrade, which applies new patches. Then the attribute appears in the product form.

Here is the stand-in. It models the pieces that matter: an attribute table, a value table keyed by product, attribute and store, and a patch runner that records applied patches.

PHP A mini EAV store and a patch runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second run is skipped because the name is recorded, which is how real patches behave. Product 1 shows new in store 1 (default value) and sale in store 2 (store-level override). Real Magento's scope fallback is richer, but the idea is the same.

Step 2: a plugin for the listing tiles

Category pages render each tile through a block. A plugin can append the badge to a block method's output without touching core. The method used here, getProductDetailsHtml() on Magento\Catalog\Block\Product\ListProduct, is a public method that returns the HTML of the details area of one tile; confirm that it exists with that signature in your version before relying on it.

XML
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\ListProduct">
        <plugin name="acme_product_badge_listing"
                type="Acme\ProductBadge\Plugin\AddBadgeToListing"/>
    </type>
</config>

Save this as etc/frontend/di.xml: the badge only matters on the storefront, so the narrowest area is the right one (see Areas and Configuration Files).

PHP
<?php
declare(strict_types=1);

namespace Acme\ProductBadge\Plugin;

use Acme\ProductBadge\ViewModel\Badge;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\Product;

class AddBadgeToListing
{
    public function __construct(private readonly Badge $badge)
    {
    }

    public function afterGetProductDetailsHtml(
        ListProduct $subject,
        string $result,
        Product $product
    ): string {
        return $this->badge->renderFor($product) . $result;
    }
}

This is an after plugin, the least invasive kind: it receives the original result and returns a new one. An around plugin would be overkill here (see Plugin Best Practices and Pitfalls). The plugin does not call getData() itself; it delegates to the ViewModel, so listing and product page share one source of truth.

Step 3: the ViewModel

A ViewModel is a plain class that implements ArgumentInterface. It keeps logic out of the template.

PHP
<?php
declare(strict_types=1);

namespace Acme\ProductBadge\ViewModel;

use Magento\Catalog\Model\Product;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Block\ArgumentInterface;

class Badge implements ArgumentInterface
{
    private const LABELS = ['new' => 'New', 'sale' => 'Sale'];

    public function __construct(private readonly Escaper $escaper)
    {
    }

    public function getLabel(Product $product): ?string
    {
        $code = (string) $product->getData('acme_badge');

        return self::LABELS[$code] ?? null;
    }

    public function renderFor(Product $product): string
    {
        $label = $this->getLabel($product);
        if ($label === null) {
            return '';
        }

        return '<span class="acme-badge">' . $this->escaper->escapeHtml($label) . '</span>';
    }
}

Two details matter. First, the stored value is only a code; the visible text comes from a fixed map, so unknown or tampered values display nothing. Second, anything that reaches HTML goes through the Escaper, as explained in Blocks, ViewModels and PHTML Templates.

One practical note: product attributes are only loaded into a product on a listing if the attribute is flagged for it (for example used_in_product_listing). Without that flag, getData('acme_badge') can be empty in category tiles. Add 'used_in_product_listing' => true to the attribute definition for this project.

Step 4: layout and template for the product page

Layout XML puts a block into the product page, passes it the ViewModel and names the template.

XML
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="product.info.main">
            <block class="Magento\Catalog\Block\Product\View"
                   name="acme.product.badge"
                   template="Acme_ProductBadge::badge.phtml"
                   before="-">
                <arguments>
                    <argument name="view_model" xsi:type="object">Acme\ProductBadge\ViewModel\Badge</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>

The file name catalog_product_view.xml is the layout handle for the product page. before="-" puts the block first inside the container. The template is short because the ViewModel does the thinking:

PHP
<?php
/** @var \Magento\Catalog\Block\Product\View $block */
/** @var \Acme\ProductBadge\ViewModel\Badge $viewModel */
$viewModel = $block->getData('view_model');
$badge = $viewModel->renderFor($block->getProduct());
?>
<?php if ($badge !== ''): ?>
    <div class="acme-badge-wrap"><?= /* @noEscape */ $badge ?></div>
<?php endif; ?>

The @noEscape comment tells code checkers that this output is already escaped inside the ViewModel. That is acceptable only because renderFor() escapes everything itself; never use it on raw data. A later hardening step is to move the markup into the template and expose only getLabel(), so the template escapes with $escaper->escapeHtml() directly. Then the plugin needs its own small string.

The output path in plain PHP

This stand-in imitates the interceptor and a template. A tiny Interceptor calls an after plugin, a Badge ViewModel escapes the label, and a render function plays the role of the PHTML file. Real Magento generates interceptor classes and reads the plugin list from di.xml.

PHP Plugin plus ViewModel on a product tile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice what happens to the tampered product: the stored value is not in the label map, so it produces no badge, and the name is escaped. Maps for codes and an escaper for text are two layers of protection.

Testing and shipping the module

After the files are in place, a typical run looks like this (read-only commands, see Custom CLI Commands for the command line itself):

Terminal
bin/magento module:enable Acme_ProductBadge
bin/magento setup:upgrade
bin/magento cache:flush

In production mode you would also compile and deploy static content, as described in Deployment and Upgrades. Then edit a product, choose a badge, save, and check a category page and the product page. If the full page cache is on, remember that saving a product invalidates the cache tags attached to that product (see Indexers and Caching).

Ideas to extend the project:

  • Add a Sale badge rule that is computed from a special price instead of stored by hand.
  • Expose the attribute through the REST API with an extension attribute, using what you learn in Service Contracts and Repositories.
  • Add a system configuration switch to turn the badge off for a store view (see System Configuration).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the attribute created in a data patch instead of by editing core files?

    A data patch lives in your module, is applied by setup:upgrade, and is recorded so it does not run again.
  2. 2. What does the scope value SCOPE_STORE mean for the attribute?

    Store scope allows a different value per store view, with the default value as the fallback.
  3. 3. Why does the badge plugin use an after method rather than an around method?

    The plugin just prepends HTML to a result that already exists, so no control over the original call is needed.
  4. 4. Why does the ViewModel map stored codes to labels instead of printing the stored value?

    A fixed map limits what can ever be shown, and escaping protects whatever text is shown.

Summary

  • A custom product attribute is created by an EavSetup call inside a data patch, then applied with bin/magento setup:upgrade.
  • Values live in EAV value tables per product, attribute and store view, with the default value as fallback.
  • A small after plugin on a listing block method can add output without changing core classes; confirm the target method in your version.
  • A ViewModel holds the logic and escaping; layout XML adds the block to catalog_product_view and passes the ViewModel as an argument.
  • Flag the attribute for listings (used_in_product_listing) if tiles need it.
  • Prefer code-to-label maps and the Escaper so stored data can never inject markup.

Next, react to orders instead of products in Project: Order Events and Notifications.