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
- How to programmatically create invoice in magento2. Check it here.
- How to add custom footer in Magento 2 PDF Invoice. Check it here.
6 comments
Hi,
Now, I have updated the event. Now, ‘sales_order_invoice_save_commit_after’ will be used. So, you will not get the problem for frontend. You can check the below updated code of observer:
Omar, I have updated the event. Now, ‘sales_order_invoice_save_commit_after’ will be used. You can check the below updated code of observer: