5

I am using magento version 2.1.How to get all order status options in my custom module?

2 Answers 2

10

I got solution code as below:

    /**
     * @var Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $statusCollectionFactory
     */
    protected $statusCollectionFactory;


    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $statusCollectionFactory
     */
    public function __construct(Template\Context $context,
            \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $statusCollectionFactory
        ) 
    {       
        $this->statusCollectionFactory = $statusCollectionFactory;      
        parent::__construct($context);
    }



    /**
     * Get status options
     *
     * @return array
     */
    public function getStatusOptions()
    {       
        $options = $this->statusCollectionFactory->create()->toOptionArray();        
        return $options;
    }   
1
  • could you please add the code with complete full path, Why because, some users cant able to know the path to use this code. Thanks Commented Nov 10, 2018 at 10:08
1

If you want to get just order statuses. Use the following class.

<?php
namespace MyCompany\MyModule\Model;

class MyClass
{
    protected $orderStatus;

    public function __construct(
        \Magento\Sales\Model\Config\Source\Order\Status $orderStatus
    ){
        $this->orderStatus = $orderStatus;
    }

    public function getOrderStatuses()
    {
        return $this->orderStatus->toOptionArray();
    }
}

In case you have a drop down field in system configuration, you can directly use the aforementioned class in source_model as follows.

<field id="status" translate="label comment" type="select" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Order Status</label>
    <source_model>Magento\Sales\Model\Config\Source\Order\Status</source_model>
</field>

In case you need order statuses along with the respective states, use the following way.

<?php
namespace MyCompany\MyModule\Model;

class MyClass
{
    protected $orderStatus;

    public function __construct(
        \Magento\Sales\Model\Order\Status $orderStatus
    ){
        $this->orderStatus = $orderStatus;
    }

    public function getOrderStatuses()
    {
        $orderStatuses = $this->orderStatus->getCollection();
        $orderStatuses->joinStates();
        return $orderStatuses;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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