Back to Top

How to add Invoice id prefix in Magento2

Updated 23 February 2024

Here we learn, How to add prefix in invoice increment id.

We also have a separate module for adding prefixes to an Order ID, Invoice ID, Shipment ID and Credit Memo ID.
Magento2 custom order prefix: This module is the single best module and super useful when the admin wants to add the prefixes to an Order ID, Invoice ID, Shipment ID, Credit Memo ID from their end. For more information, you can check it on our store.

Some time we need to update invoice increment_id(#00000001) according to our requirement. If we want to add Invoice id prefix in Magento 2, then below is the solution for that.

1. Create events.xml file, for e.g: Webkul/Custom/etc/events.xml add the below code.

<?xml version="1.0"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Custom
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_invoice_save_commit_after">
        <observer name="update_invoice" instance="Webkul\Custom\Observer\ChangeInvoicePrefix" />
    </event>
</config>

2. Now, create Observer file, for e.g: Webkul/Custom/Observer/ChangeInvoicePrefix.php

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Custom
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\Custom\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ResourceConnection;

class ChangeInvoicePrefix implements ObserverInterface
{
    /**
     * Function to change invoice prefix
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        $invoice = $observer->getEvent()->getInvoice();
        $prefix = 'HELLO-';
        if (!str_contains($incrementId, $prefix)) {
            $invoice->setData("increment_id", $prefix.$incrementId)->save();
        }
    }
}

Other Related Blogs

  1. How to programmatically create invoice in magento2. Check it here.
  2. How to add custom footer in Magento 2 PDF Invoice. Check it here.

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

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


6 comments

  • Nil
    • Akash Panwar (Moderator)
  • Omar
    • Akash Panwar (Moderator)
  • Pranav
    • Mahesh Singh (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home