Magento 2从myaccount页面取消订单

时间:2016-02-11 15:24:55

标签: magento magento2 magento-2.0

以编程方式取消magento 2中的顺序:

我在magento 1中实施了模块,我将从客户的帐户页面取消挂单。

请参考下面我在magento 1中实现的代码:

$order = Mage::getModel('sales/order')->load($orderId);
$order_status=$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();

我想在magento 2中实现相同的功能。有谁知道如何实现它?

我在magento 2中加载了订单ID的订单,但我无法取消订单。

2 个答案:

答案 0 :(得分:2)

您应该使用API​​(更多关于magento2 API concepts),例如如何在您的班级中使用它:

<?php

use Magento\Sales\Api\OrderManagementInterface;

class A
{
    /**
     * @var OrderManagementInterface
     */
    private $orderManagement;

    /**
     * @param OrderManagementInterface $orderManagement
     */
    public function __construct(OrderManagementInterface $orderManagement)
    {
        $this->orderManagement = $orderManagement;
    }

    public function cancelOrderOne()
    {
        $orderId = 1;
        $isCanceled = $this->orderManagement->cancel($orderId);
    }
}

答案 1 :(得分:0)

请查看下面的代码,它还将验证订单的用户关联

<?php
 Nmaespace\Modulename\Controller\Action;

class Cancelorder  extends \Magento\Framework\App\Action\Action
{
  protected $orderManagement;
  public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Sales\Api\OrderManagementInterface $orderManagement

) {
    $this->orderManagement = $orderManagement;
    parent::__construct($context); 
}

public function execute()
{
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $customerSession = $objectManager->get('Magento\Customer\Model\Session');
        if(!$customerSession->isLoggedIn()) {
                $this->_redirect('/');
                die;
        }

        /*get request params */
        $get_customer_id = $customerSession->getCustomer()->getId();

        $get_order_id = $this->getRequest()->getParam('order_id');
        /*get request params */
        //die;
        $order = $objectManager->create('Magento\Sales\Model\Order')->load($get_order_id);
        $getcustomerid = $get_customer_id;
        $orderdata  = $order->getData();
        $order_status = $orderdata["status"];
        //print_r($orderdata);
        $cus_id =  $orderdata["customer_id"];
        if($getcustomerid != $cus_id){
            echo "We cant Cancel this order at this time" ;
            //die("go back");
        }
        if($order_status == "pending"){
            $this->orderManagement->cancel($get_order_id); 
            echo "Order Cancelled successfully" ;
        }
        else{
            echo "We cant Cancel this order at this time" ;

        }
}


}