Add a row count to the order sales view items table – Magento 2.4

We want to add a row count in the order sales view items table.


There are 2 ways to achieve this:

Let’s start by creating a module Vendor_RowCounter, with the required files, and shared files for both solutions:

  1. Add registration.php:
<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Vendor_RowCounter',
    __DIR__
);
  1. Add etc/module.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_RowCounter"/>
</config>
  1. Create a block file, Block/Adminhtml/Items/Column/Row.php:
<?php

declare(strict_types=1);

namespace Vendor\RowCounter\Block\Adminhtml\Items\Column;

use Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn;

class Row extends DefaultColumn
{

    /** @var int */
    private int $row = 1;

    /**
     * @return int
     */
    public function getRow(): int
    {
        return $this->row++;
    }
}
  1. Create a template file, view/adminhtml/templates/items/column/row.phtml:
<?php
use Vendor\RowCounter\Block\Adminhtml\Items\Column\Row;
/** @var Row $block */
?>

<?php if ($_item = $block->getItem()): ?>
    <div id="order_item_<?= (int) $_item->getId() ?>_row">
        <?= $block->getRow(); ?>
    </div>
<?php endif; ?>

By adding a column via sales_order_view.xml

  1. Create view/adminhtml/layout/sales_order_view.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>
        <referenceBlock name="order_items">
            <arguments>
                <argument name="columns" xsi:type="array">
                    <item name="row" xsi:type="string" translate="true">#</item>
                </argument>
            </arguments>
            <block class="Vendor\RowCounter\Block\Adminhtml\Items\Column\Row" name="column_row" template="Vendor_RowCounter::items/column/row.phtml" group="column"/>
        </referenceBlock>
        <referenceBlock name="default_order_items_renderer">
            <arguments>
                <argument name="columns" xsi:type="array">
                    <item name="row" xsi:type="string" translate="true">col-row</item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

The drawback with this approach is you won’t have control over the order of columns and a new column will be added at the end:

Leave a comment

Your email address will not be published. Required fields are marked *