Magento – Convert \Magento\Quote\Model\Quote to \Magento\Sales\Model\Order: Magento 2

magento2quotesales-order

I have a custom module that creates and displays the quote details. I need to display the items in a quote similar to the items grid in view order page in Magento 2 sales module.

I have created a cutom block for getting the items: Items.php as which is calling the items collection.

class Items extends \NameSpace\Moudle\Block\Adminhtml\Items\AbstractItems {

/**
 * Retrieve quote items collection
 *
 * @return Collection
 */
public function getItemsCollection() { 
    return $this->getQuote()->getItemsCollection();
  }
}

In my AbstractItems class I m trying to get the quote using the magento quote module like below,

/**
 * Retrieve current quote from registry
 * @return Magento\Sales\Model\Order
 */
public function getQuote() {

    $quoteId = $this->quotes->getParam('quote_id');

    //To get the quote object instance.
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $options = $objectManager->create('Magento\Quote\Model\Quote');
    $_quote = $options->load($quoteId);
    return $_quote;
}

The issue here is that the above function is returning a quote isntance whereas I need an order since. I need an order instance since I need to call the methods such as displaySubtotalInclTax() and formatBasePricePrecision() to get the prices of the items.
However, a quote instance does not have the above methods due to which I am getting an "Invalid method" error.

Is there any way to convert the Magento\Quote\Model\Quote into Magento\Sales\Model\Order instance.

PS: I know the using objectManager directly is not recommended and I have plans to change it once I get the item details.

Please, can anyone help.

Best Answer

You can use like this in your function

    protected $quoteRepository;
public function __construct(\Magento\Framework\Model\Context $context, 
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
    )
{       
    $this->quoteRepository = $quoteRepository;
    parent::__construct($context, $registry);
}

public yourfunction(){
    $quote = $this->quoteRepository->getActive($id);
      $quote->collectTotals();
      $count = (int)$quote->getitemsQty();
      $total = $quote->getgrandTotal();
}
Related Topic