0

i'm new in magento 2 I want to save some data into custom table after customer click place order I'm done it in magento 1 Below is my magento 1 code :

config.xml : app\code\local\Sprint\Migs\etc

 <events>
      <sales_model_service_quote_submit_after>
        <observers>
          <sprint_migs_saveSiteID>
            <type>singleton</type>
            <class>Sprint_Migs_Model_Observer</class>
            <method>saveSiteID</method>
          </sprint_migs_saveSiteID>
        </observers>
      </sales_model_service_quote_submit_after>
</events>

Observer.php : app\code\local\Sprint\Migs\Model

public function saveSiteID($observer){
    $post = Mage::app()->getFrontController()->getRequest()->getPost();
    if(isset($post['payment']['method'])){
        if ($post['payment']['method'] == "migs"){

            $order                  = $observer->getEvent()->getOrder();
            $merchantTransactionID  = $observer->getEvent()->getOrder()->getIncrementId();
            $siteId                 = $post['payment']['site_id'];
            $transactionType        = Mage::getStoreConfig('payment/migs/transactionType');
            $currency               = 'IDR';
            $amount                 = Mage::helper('migs')->getTotalPrice($merchantTransactionID);

            $data       = array("merchantTransactionID" => $merchantTransactionID,"siteId" => $siteId,"transactionType" => $transactionType,"currency" => $currency,"amount" => $amount);  
            Mage::helper('migs')->insertMigsData($data);
        }
    }
}

}

Data.php : app\code\local\Sprint\Migs\Helper

<?php

class Sprint_Migs_Helper_Data extends Mage_Core_Helper_Abstract {

    public function getTotalPrice($transactionNo="") {
        if ($transactionNo != ""){
            $order              = Mage::getModel('sales/order')->loadByIncrementId($transactionNo);
            $baseCode           = Mage::app()->getBaseCurrencyCode();      
            $allowedCurrencies  = Mage::getModel('directory/currency')->getConfigAllowCurrencies(); 
            $rates              = Mage::getModel('directory/currency')->getCurrencyRates($baseCode, array_values($allowedCurrencies));
            if($baseCode == 'IDR') {
                $TotalWithPeriod = explode('.', $order->getBaseGrandTotal());
                $totalPrice     = $TotalWithPeriod[0];
            }
            else {
                $totalPriceRate = $order->getBaseGrandTotal()*$rates['IDR'];
                $TotalWithPeriod = explode('.', $totalPriceRate);
                $totalPrice = $TotalWithPeriod[0];
            }
        }else{
            $session = Mage::getSingleton('checkout/session')->getLastRealOrderId();
            $order = Mage::getModel('sales/order')->loadByIncrementId($session);
            $baseCode = Mage::app()->getBaseCurrencyCode();
            $allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies(); 
            $rates = Mage::getModel('directory/currency')->getCurrencyRates($baseCode, array_values($allowedCurrencies));
            if($baseCode == 'IDR') {
                $TotalWithPeriod = explode('.', $order->getBaseGrandTotal());
                $totalPrice = $TotalWithPeriod[0];
            }
            else {
                $totalPriceRate = $order->getBaseGrandTotal()*$rates['IDR'];
                $TotalWithPeriod = explode('.', $totalPriceRate);
                $totalPrice = $TotalWithPeriod[0];
            }
        }

        return $totalPrice;
    }

    public function getUrlData( $st ){
        $st = strtolower($st);
        $url = array(
            'development' => 'https://training.doappx.com/sprintAsia/api/webAuthorization.cfm',
            'production' => 'https://acquire.doappx.com/sprint/doacquire/api/webAuthorization.cfm'
        );
        return $url[ $st ];
    }

    public function getSiteID($merchantTransactionID) {
        $resource               = Mage::getSingleton('core/resource');
        $read                   = $resource->getConnection('core_read');
        $sql                    = ("SELECT siteId FROM sprint_migs WHERE merchantTransactionID = '".$merchantTransactionID."'");
        $result                 = $read->fetchRow($sql);
        $siteID                 = $result['siteId'];
        return $siteID;
    }

    public function insertMigsData($data){
        $resource   = Mage::getSingleton('core/resource');
        $write      = $resource->getConnection('core_write');
        $table      = Mage::getSingleton( 'core/resource' )->getTableName( 'sprint_migs' ); 
        $write->insert($table, $data);
    }

    public function updateMigsData($data,$where) {
        $resource   = Mage::getSingleton('core/resource');
        $write      = $resource->getConnection('core_write');
        $table      = Mage::getSingleton( 'core/resource' )->getTableName( 'sprint_migs' ); 
        $write->update($table, $data, $where);
    }

    public function generateInvoice( $order ){
        $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
        if (!$invoice->getTotalQty()) {
            Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
        }
        $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
        $invoice->register();
        $transactionSave = Mage::getModel('core/resource_transaction')
                ->addObject($invoice)
                ->addObject($invoice->getOrder());

        $transactionSave->save();
    }
}

how can i do it in magento 2 ?

1

you can do this by creating an observer

[Namespace]/[Modulename]/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="obeserver_name" instance="[Namespace]\[Modulename]\Observer\AfterOrderPlaced" />
    </event>
</config>

[Namespace]/[Modulename]/Observer/AfterOrderPlaced

<?php
namespace [Namespace]\[Modulename]\Observer;

use Magento\Framework\Event\ObserverInterface;

class AfterOrderPlaced implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        array $data = []
    )
    {
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /** @var \Magento\Sales\Model\Order $order */
        $order = $observer->getEvent()->getOrder();
        $order_status=$order->getStatus();
        //DO YOUR CUSTOM CODE HERE

    }
}

Hope that Helps.

  • How to set it to custom table after an event triggers. – Prathap Gunasekaran Oct 4 '18 at 11:10
  • Hi @PrathapGunasekaran, did got the answer for save it custom table – shivashankar m Mar 19 '19 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.