Magento – how to change magento order number

magento-2.1magento2order-statusorders

how to make magento generate order number by year and month and increment number
for example if we in August 2017 so the order numbers to be 1708001 , 1708002 , 1708003 , 1708004 , 1708005 , 1708006 , 1708007
and so on
thanks

Best Answer

I'm not sure if this would cause issues (the first of which if you have more than 1000 orders in a month also could cause duplicates).

The way i would probably start going about it however would be to create a custom cron job that sets the increment ID based on the current date etc and runs something like below at the start of each month:

Instance:

<?php
namespace Harri\OrderUpdate\Cron;

class Updater {

    protected  _resource;

    public function __construct(Context $context,
         \Magento\Framework\App\ResourceConnection $resource)
    {
        $this->_resource = $resource;                  
        parent::__construct($context);
    }

    public function execute() {
        $connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

        $ordernumber = date("y") . date("m") . "001";

        $sql = 'ALTER TABLE sequence_order_1 AUTO_INCREMENT=' . $ordernumber;

        $connection->query($sql);
    }
}

The above file 'Harri/OrderUpdate/Cron/Updater.php' is very rough but should build your order id based on the date and update the database so the next order starts with this ID.

Cron Tab:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default"> <!-- Doesn't need to be unique -->
    <job name="order_updater" instance="Harri\OrderUpdate\Cron\Updater" method="execute">
        <schedule>0 0 1 * *</schedule>
    </job>
</group>
</config>

Above file 'Harri/OrderUpdate/etc/crontab.xml' is configured to run the file above at the start of each month.

See here about cron with Magento. http://devdocs.magento.com/guides/v2.0/config-guide/cron/custom-cron-ref.html

Related Topic