Order Export Per store View in magento 2












0















I am using magento 2.1.5, i have created custom module for order export csv. but i created this export option in mass action.



enter image description here



and i did code like this:



 use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
use MagentoBackendAppActionContext;
use MagentoSalesModelResourceModelOrderCollectionFactory;
use MagentoUiComponentMassActionFilter;
use MagentoFrameworkAppResourceConnection;
use MagentoFrameworkAppDeploymentConfig;
use MagentoFrameworkConfigConfigOptionsListConstants;
use MagentoFrameworkAppFilesystemDirectoryList;
class MassExport extends
MagentoSalesControllerAdminhtmlOrderAbstractMassAction
{
const ENCLOSURE = '"';
const DELIMITER = ',';

protected $_directoryList;
public $_resource;
private $deploymentConfig;
private $objectManager;
public function __construct(Context $context,
ResourceConnection $resource,
Filter $filter, CollectionFactory $collectionFactory,DeploymentConfig
$deploymentConfig,DirectoryList $directory_list)
{

$this->_resource = $resource;
parent::__construct($context , $filter);
$this->deploymentConfig = $deploymentConfig;
$this->collectionFactory = $collectionFactory;
$this->_directoryList = $directory_list;
$this->objectManager = MagentoFrameworkAppObjectManager::getInstance();

}
/**
* Cancel selected orders
*
* @param AbstractCollection $collection
* @return MagentoBackendModelViewResultRedirect
*/
protected function massAction(AbstractCollection $collection)
{

if (!file_exists($this->_directoryList->getRoot().'/pub/media/OrderExport')) {
mkdir($this->_directoryList->getRoot().'/pub/media/OrderExport', 0777, true);
}

$todayDate = date('Y_m_d_H_i_s', time());
$fileName = $this->_directoryList->getRoot().'/pub/media/OrderExport/OrderExport'.$todayDate.'.csv';


$fp = fopen($fileName, 'w');
$this->writeHeadRow($fp);

$countOrderExport = 0;
foreach ($collection->getItems() as $_order) {

$orderId = $_order->getId();
if ($orderId) {
$order = $this->objectManager->create('MagentoSalesModelOrder')->load($_order->getId());
$this->writeOrder($order, $fp);
$incId = $order->getIncrementId();
$countOrderExport++;
}
}
fclose($fp);

$this->downloadCsv($fileName);
$this->messageManager->addSuccess(__('We Exported %1 order(s).', $countOrderExport));

//$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('sales/*/');
//return $resultRedirect;
}


public function downloadCsv($file)
{

if (file_exists($file)) {
//set appropriate headers
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();flush();
readfile($file);
}
}

protected function writeHeadRow($fp)
{
fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
}

protected function getHeadRowValues()
{
return array(
'Order Number',
'Order Date',
'Order Status',
'Order Purchased From',
'Order Payment Method',
'Order Shipping Method',
'po_number',
'c_market_price',
'Order Subtotal',
'Order Tax',
'Order Shipping',
'Order Discount',
'Order Grand Total',
'Order Paid',
'Order Refunded',
'Order Due',
'Total Qty Items Ordered',
'Customer Name',
'Customer Email',
'Shipping Name',
'Shipping Company',
'Shipping Street',
'Shipping Zip',
'Shipping City',
'Shipping State',
'Shipping State Name',
'Shipping Country',
'Shipping Country Name',
'Shipping Phone Number',
'Billing Name',
'Billing Company',
'Billing Street',
'Billing Zip',
'Billing City',
'Billing State',
'Billing State Name',
'Billing Country',
'Billing Country Name',
'Billing Phone Number',
'Order Item Increment',
'Item Name',
'Item Status',
'Item SKU',
'Item Options',
'original_price',
'Item Selling Price',
'Item Qty Ordered',
'Item Qty Invoiced',
'Item Qty Shipped',
'Item Qty Canceled',
'Item Qty Refunded',
'Item Tax',
'Item Discount',
'Item Total',
'price_per_lb',
'Coupon Code',
'GST Number',
'premium_care',

);
}

protected function writeOrder($order, $fp)
{
$common = $this->getCommonOrderValues($order);


$orderItems = $order->getAllVisibleItems();
$itemInc = 0;
$item = "";
foreach ($orderItems as $item)
{
// if (!$item->isDummy()) {
$record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
// }
}

}

protected function getCommonOrderValues($order)
{
$shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
$billingAddress = $order->getBillingAddress();

$payment = $order->getPayment();
$method = $payment->getMethodInstance();
$methodTitle = $method->getTitle();

$total_item_qty = $this->getTotalQtyItemsOrdered($order);

$priceHelper = $this->objectManager->create('MagentoFrameworkPricingHelperData');
$objDate = $this->objectManager->create('MagentoFrameworkStdlibDateTimeTimezoneInterface');
$country_name = $this->objectManager->create('MagentoDirectoryModelCountry');
//echo $order->getData('price_per_lb'); exit;
return array(
$order->getIncrementId(),
$objDate->date(new DateTime($order->getCreatedAt()))->format('m-d-Y'),
$order->getStatus(),
$order->getData('store_name'),
$methodTitle,
$order->getData('shipping_method'),
$order->getData('po_number'),

$order->getData('c_market_price'),
number_format($order->getData('subtotal'), 2, '.',''),
number_format($order->getData('tax_amount'), 2, '.',''),
number_format($order->getData('shipping_amount'), 2, '.',''),
number_format($order->getData('discount_amount'), 2, '.',''),
number_format($order->getData('grand_total'), 2, '.',''),
number_format($order->getData('total_paid'), 2, '.',''),
number_format($order->getData('total_refunded'), 2, '.',''),
number_format($order->getData('total_due'), 2, '.',''),
$total_item_qty,
$order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
$order->getData('customer_email'),
$shippingAddress ? $shippingAddress->getName() : '',
$shippingAddress ? $shippingAddress->getData("company") : '',
$shippingAddress ? $shippingAddress->getData("street") : '',
$shippingAddress ? $shippingAddress->getData("postcode") : '',
$shippingAddress ? $shippingAddress->getData("city") : '',
$shippingAddress ? $shippingAddress->getRegion() : '',
$shippingAddress ? $shippingAddress->getRegion() : '',
$shippingAddress ? $shippingAddress->getdata("country_id") : '',
$shippingAddress ? $shippingAddress->getData("country_id") : '',
$shippingAddress ? $shippingAddress->getData("telephone")."/".$shippingAddress->getData("fax") : '',
$order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
$billingAddress->getData("company"),
$billingAddress->getData("street"),
$billingAddress->getData("postcode"),
$billingAddress->getData("city"),
$billingAddress->getRegionCode(),
$billingAddress->getRegion(),
$billingAddress->getData("country_id"),
$country_name->load($billingAddress->getData("country_id"))->getName(),
$billingAddress->getData("telephone")."/".$billingAddress->getData("fax")
);

}

protected function getOrderItemValues($item, $order, $itemInc=1)
{
$custom_option = "";
if($item->hasProductOptions()){
if (array_key_exists("options",$item->getData('product_options'))){
$option_coll = $item->getData('product_options')['options'];
foreach ($option_coll as $cptions) {
$custom_option .= strip_tags($cptions['label']).";";
}
}
}

//$priceOrder = $this->getPricePer($item);
//$product = $this->objectManager->get('MagentoCatalogModelProduct')->load($item->getId());
//$offerinfo = $product->getResource()->getAttribute("offer")->getFrontend()->getValue($product);
//unset($product);
//echo "suman"; die;
//print_r($item->getPricePerLb()); exit;
return array(
$itemInc,
$item->getName(),
$item->getStatus(),
$item->getSku(),
$custom_option,
$item->getOriginalPrice(),
$item->getPrice(),
(int)$item->getQtyOrdered(),
(int)$item->getQtyInvoiced(),
(int)$item->getQtyShipped(),
(int)$item->getQtyCanceled(),
(int)$item->getQtyRefunded(),
$order->getData('tax_amount'),
abs($item->getData('discount_amount')),
$item->getData('row_total') - $item->getDiscountAmount(),
abs($item->getPricePerLb()),

$order->getCouponCode(),
$order->getBillingAddress()->getData('vat_id')
);


}

protected function getTotalQtyItemsOrdered($order)
{

$qty = 0;

$orderedItems = $order->getAllVisibleItems();
foreach ($orderedItems as $qitem)
{
//if (!$item->isDummy()) {
$qty += (int)$qitem->getQtyOrdered();
//}
}

return $qty;

}


Code of Sales_order_grid is:



<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../../../../Ui/etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<!-- add export mass action -->
<massaction name="listing_massaction">
<action name="export">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Export Order</item>
<item name="message" xsi:type="string" translate="true">Export selected orders?</item>
</item>
<item name="type" xsi:type="string">export</item>
<item name="label" xsi:type="string" translate="true">Export</item>
<item name="url" xsi:type="url" path="orderexport/order/massExport"/>
</item>
</argument>
</action>
</massaction>
</listingToolbar>




Now i want to create one button in top like same as create new order, and want to give option to export csv as per store view.



for creating button i add xml code in sales_order_grid.xml



    <argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Export Order</item>
<item name="message" xsi:type="string" translate="true">Export selected orders?</item>
</item>
<item name="type" xsi:type="string">export</item>
<item name="label" xsi:type="string" translate="true">Export</item>
<item name="url" xsi:type="url" path="orderexport/order/orderExport"/>
</item>
</argument>


Now how can i give the option of all the stores, and how i set the condition to export selected stores csv?









share



























    0















    I am using magento 2.1.5, i have created custom module for order export csv. but i created this export option in mass action.



    enter image description here



    and i did code like this:



     use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
    use MagentoBackendAppActionContext;
    use MagentoSalesModelResourceModelOrderCollectionFactory;
    use MagentoUiComponentMassActionFilter;
    use MagentoFrameworkAppResourceConnection;
    use MagentoFrameworkAppDeploymentConfig;
    use MagentoFrameworkConfigConfigOptionsListConstants;
    use MagentoFrameworkAppFilesystemDirectoryList;
    class MassExport extends
    MagentoSalesControllerAdminhtmlOrderAbstractMassAction
    {
    const ENCLOSURE = '"';
    const DELIMITER = ',';

    protected $_directoryList;
    public $_resource;
    private $deploymentConfig;
    private $objectManager;
    public function __construct(Context $context,
    ResourceConnection $resource,
    Filter $filter, CollectionFactory $collectionFactory,DeploymentConfig
    $deploymentConfig,DirectoryList $directory_list)
    {

    $this->_resource = $resource;
    parent::__construct($context , $filter);
    $this->deploymentConfig = $deploymentConfig;
    $this->collectionFactory = $collectionFactory;
    $this->_directoryList = $directory_list;
    $this->objectManager = MagentoFrameworkAppObjectManager::getInstance();

    }
    /**
    * Cancel selected orders
    *
    * @param AbstractCollection $collection
    * @return MagentoBackendModelViewResultRedirect
    */
    protected function massAction(AbstractCollection $collection)
    {

    if (!file_exists($this->_directoryList->getRoot().'/pub/media/OrderExport')) {
    mkdir($this->_directoryList->getRoot().'/pub/media/OrderExport', 0777, true);
    }

    $todayDate = date('Y_m_d_H_i_s', time());
    $fileName = $this->_directoryList->getRoot().'/pub/media/OrderExport/OrderExport'.$todayDate.'.csv';


    $fp = fopen($fileName, 'w');
    $this->writeHeadRow($fp);

    $countOrderExport = 0;
    foreach ($collection->getItems() as $_order) {

    $orderId = $_order->getId();
    if ($orderId) {
    $order = $this->objectManager->create('MagentoSalesModelOrder')->load($_order->getId());
    $this->writeOrder($order, $fp);
    $incId = $order->getIncrementId();
    $countOrderExport++;
    }
    }
    fclose($fp);

    $this->downloadCsv($fileName);
    $this->messageManager->addSuccess(__('We Exported %1 order(s).', $countOrderExport));

    //$resultRedirect = $this->resultRedirectFactory->create();
    //$resultRedirect->setPath('sales/*/');
    //return $resultRedirect;
    }


    public function downloadCsv($file)
    {

    if (file_exists($file)) {
    //set appropriate headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();flush();
    readfile($file);
    }
    }

    protected function writeHeadRow($fp)
    {
    fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
    }

    protected function getHeadRowValues()
    {
    return array(
    'Order Number',
    'Order Date',
    'Order Status',
    'Order Purchased From',
    'Order Payment Method',
    'Order Shipping Method',
    'po_number',
    'c_market_price',
    'Order Subtotal',
    'Order Tax',
    'Order Shipping',
    'Order Discount',
    'Order Grand Total',
    'Order Paid',
    'Order Refunded',
    'Order Due',
    'Total Qty Items Ordered',
    'Customer Name',
    'Customer Email',
    'Shipping Name',
    'Shipping Company',
    'Shipping Street',
    'Shipping Zip',
    'Shipping City',
    'Shipping State',
    'Shipping State Name',
    'Shipping Country',
    'Shipping Country Name',
    'Shipping Phone Number',
    'Billing Name',
    'Billing Company',
    'Billing Street',
    'Billing Zip',
    'Billing City',
    'Billing State',
    'Billing State Name',
    'Billing Country',
    'Billing Country Name',
    'Billing Phone Number',
    'Order Item Increment',
    'Item Name',
    'Item Status',
    'Item SKU',
    'Item Options',
    'original_price',
    'Item Selling Price',
    'Item Qty Ordered',
    'Item Qty Invoiced',
    'Item Qty Shipped',
    'Item Qty Canceled',
    'Item Qty Refunded',
    'Item Tax',
    'Item Discount',
    'Item Total',
    'price_per_lb',
    'Coupon Code',
    'GST Number',
    'premium_care',

    );
    }

    protected function writeOrder($order, $fp)
    {
    $common = $this->getCommonOrderValues($order);


    $orderItems = $order->getAllVisibleItems();
    $itemInc = 0;
    $item = "";
    foreach ($orderItems as $item)
    {
    // if (!$item->isDummy()) {
    $record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
    fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
    // }
    }

    }

    protected function getCommonOrderValues($order)
    {
    $shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
    $billingAddress = $order->getBillingAddress();

    $payment = $order->getPayment();
    $method = $payment->getMethodInstance();
    $methodTitle = $method->getTitle();

    $total_item_qty = $this->getTotalQtyItemsOrdered($order);

    $priceHelper = $this->objectManager->create('MagentoFrameworkPricingHelperData');
    $objDate = $this->objectManager->create('MagentoFrameworkStdlibDateTimeTimezoneInterface');
    $country_name = $this->objectManager->create('MagentoDirectoryModelCountry');
    //echo $order->getData('price_per_lb'); exit;
    return array(
    $order->getIncrementId(),
    $objDate->date(new DateTime($order->getCreatedAt()))->format('m-d-Y'),
    $order->getStatus(),
    $order->getData('store_name'),
    $methodTitle,
    $order->getData('shipping_method'),
    $order->getData('po_number'),

    $order->getData('c_market_price'),
    number_format($order->getData('subtotal'), 2, '.',''),
    number_format($order->getData('tax_amount'), 2, '.',''),
    number_format($order->getData('shipping_amount'), 2, '.',''),
    number_format($order->getData('discount_amount'), 2, '.',''),
    number_format($order->getData('grand_total'), 2, '.',''),
    number_format($order->getData('total_paid'), 2, '.',''),
    number_format($order->getData('total_refunded'), 2, '.',''),
    number_format($order->getData('total_due'), 2, '.',''),
    $total_item_qty,
    $order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
    $order->getData('customer_email'),
    $shippingAddress ? $shippingAddress->getName() : '',
    $shippingAddress ? $shippingAddress->getData("company") : '',
    $shippingAddress ? $shippingAddress->getData("street") : '',
    $shippingAddress ? $shippingAddress->getData("postcode") : '',
    $shippingAddress ? $shippingAddress->getData("city") : '',
    $shippingAddress ? $shippingAddress->getRegion() : '',
    $shippingAddress ? $shippingAddress->getRegion() : '',
    $shippingAddress ? $shippingAddress->getdata("country_id") : '',
    $shippingAddress ? $shippingAddress->getData("country_id") : '',
    $shippingAddress ? $shippingAddress->getData("telephone")."/".$shippingAddress->getData("fax") : '',
    $order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
    $billingAddress->getData("company"),
    $billingAddress->getData("street"),
    $billingAddress->getData("postcode"),
    $billingAddress->getData("city"),
    $billingAddress->getRegionCode(),
    $billingAddress->getRegion(),
    $billingAddress->getData("country_id"),
    $country_name->load($billingAddress->getData("country_id"))->getName(),
    $billingAddress->getData("telephone")."/".$billingAddress->getData("fax")
    );

    }

    protected function getOrderItemValues($item, $order, $itemInc=1)
    {
    $custom_option = "";
    if($item->hasProductOptions()){
    if (array_key_exists("options",$item->getData('product_options'))){
    $option_coll = $item->getData('product_options')['options'];
    foreach ($option_coll as $cptions) {
    $custom_option .= strip_tags($cptions['label']).";";
    }
    }
    }

    //$priceOrder = $this->getPricePer($item);
    //$product = $this->objectManager->get('MagentoCatalogModelProduct')->load($item->getId());
    //$offerinfo = $product->getResource()->getAttribute("offer")->getFrontend()->getValue($product);
    //unset($product);
    //echo "suman"; die;
    //print_r($item->getPricePerLb()); exit;
    return array(
    $itemInc,
    $item->getName(),
    $item->getStatus(),
    $item->getSku(),
    $custom_option,
    $item->getOriginalPrice(),
    $item->getPrice(),
    (int)$item->getQtyOrdered(),
    (int)$item->getQtyInvoiced(),
    (int)$item->getQtyShipped(),
    (int)$item->getQtyCanceled(),
    (int)$item->getQtyRefunded(),
    $order->getData('tax_amount'),
    abs($item->getData('discount_amount')),
    $item->getData('row_total') - $item->getDiscountAmount(),
    abs($item->getPricePerLb()),

    $order->getCouponCode(),
    $order->getBillingAddress()->getData('vat_id')
    );


    }

    protected function getTotalQtyItemsOrdered($order)
    {

    $qty = 0;

    $orderedItems = $order->getAllVisibleItems();
    foreach ($orderedItems as $qitem)
    {
    //if (!$item->isDummy()) {
    $qty += (int)$qitem->getQtyOrdered();
    //}
    }

    return $qty;

    }


    Code of Sales_order_grid is:



    <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:noNamespaceSchemaLocation="../../../../Ui/etc/ui_configuration.xsd">
    <listingToolbar name="listing_top">
    <!-- add export mass action -->
    <massaction name="listing_massaction">
    <action name="export">
    <argument name="data" xsi:type="array">
    <item name="config" xsi:type="array">
    <item name="confirm" xsi:type="array">
    <item name="title" xsi:type="string" translate="true">Export Order</item>
    <item name="message" xsi:type="string" translate="true">Export selected orders?</item>
    </item>
    <item name="type" xsi:type="string">export</item>
    <item name="label" xsi:type="string" translate="true">Export</item>
    <item name="url" xsi:type="url" path="orderexport/order/massExport"/>
    </item>
    </argument>
    </action>
    </massaction>
    </listingToolbar>




    Now i want to create one button in top like same as create new order, and want to give option to export csv as per store view.



    for creating button i add xml code in sales_order_grid.xml



        <argument name="data" xsi:type="array">
    <item name="config" xsi:type="array">
    <item name="confirm" xsi:type="array">
    <item name="title" xsi:type="string" translate="true">Export Order</item>
    <item name="message" xsi:type="string" translate="true">Export selected orders?</item>
    </item>
    <item name="type" xsi:type="string">export</item>
    <item name="label" xsi:type="string" translate="true">Export</item>
    <item name="url" xsi:type="url" path="orderexport/order/orderExport"/>
    </item>
    </argument>


    Now how can i give the option of all the stores, and how i set the condition to export selected stores csv?









    share

























      0












      0








      0








      I am using magento 2.1.5, i have created custom module for order export csv. but i created this export option in mass action.



      enter image description here



      and i did code like this:



       use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
      use MagentoBackendAppActionContext;
      use MagentoSalesModelResourceModelOrderCollectionFactory;
      use MagentoUiComponentMassActionFilter;
      use MagentoFrameworkAppResourceConnection;
      use MagentoFrameworkAppDeploymentConfig;
      use MagentoFrameworkConfigConfigOptionsListConstants;
      use MagentoFrameworkAppFilesystemDirectoryList;
      class MassExport extends
      MagentoSalesControllerAdminhtmlOrderAbstractMassAction
      {
      const ENCLOSURE = '"';
      const DELIMITER = ',';

      protected $_directoryList;
      public $_resource;
      private $deploymentConfig;
      private $objectManager;
      public function __construct(Context $context,
      ResourceConnection $resource,
      Filter $filter, CollectionFactory $collectionFactory,DeploymentConfig
      $deploymentConfig,DirectoryList $directory_list)
      {

      $this->_resource = $resource;
      parent::__construct($context , $filter);
      $this->deploymentConfig = $deploymentConfig;
      $this->collectionFactory = $collectionFactory;
      $this->_directoryList = $directory_list;
      $this->objectManager = MagentoFrameworkAppObjectManager::getInstance();

      }
      /**
      * Cancel selected orders
      *
      * @param AbstractCollection $collection
      * @return MagentoBackendModelViewResultRedirect
      */
      protected function massAction(AbstractCollection $collection)
      {

      if (!file_exists($this->_directoryList->getRoot().'/pub/media/OrderExport')) {
      mkdir($this->_directoryList->getRoot().'/pub/media/OrderExport', 0777, true);
      }

      $todayDate = date('Y_m_d_H_i_s', time());
      $fileName = $this->_directoryList->getRoot().'/pub/media/OrderExport/OrderExport'.$todayDate.'.csv';


      $fp = fopen($fileName, 'w');
      $this->writeHeadRow($fp);

      $countOrderExport = 0;
      foreach ($collection->getItems() as $_order) {

      $orderId = $_order->getId();
      if ($orderId) {
      $order = $this->objectManager->create('MagentoSalesModelOrder')->load($_order->getId());
      $this->writeOrder($order, $fp);
      $incId = $order->getIncrementId();
      $countOrderExport++;
      }
      }
      fclose($fp);

      $this->downloadCsv($fileName);
      $this->messageManager->addSuccess(__('We Exported %1 order(s).', $countOrderExport));

      //$resultRedirect = $this->resultRedirectFactory->create();
      //$resultRedirect->setPath('sales/*/');
      //return $resultRedirect;
      }


      public function downloadCsv($file)
      {

      if (file_exists($file)) {
      //set appropriate headers
      header('Content-Description: File Transfer');
      header('Content-Type: application/csv');
      header('Content-Disposition: attachment; filename='.basename($file));
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file));
      ob_clean();flush();
      readfile($file);
      }
      }

      protected function writeHeadRow($fp)
      {
      fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
      }

      protected function getHeadRowValues()
      {
      return array(
      'Order Number',
      'Order Date',
      'Order Status',
      'Order Purchased From',
      'Order Payment Method',
      'Order Shipping Method',
      'po_number',
      'c_market_price',
      'Order Subtotal',
      'Order Tax',
      'Order Shipping',
      'Order Discount',
      'Order Grand Total',
      'Order Paid',
      'Order Refunded',
      'Order Due',
      'Total Qty Items Ordered',
      'Customer Name',
      'Customer Email',
      'Shipping Name',
      'Shipping Company',
      'Shipping Street',
      'Shipping Zip',
      'Shipping City',
      'Shipping State',
      'Shipping State Name',
      'Shipping Country',
      'Shipping Country Name',
      'Shipping Phone Number',
      'Billing Name',
      'Billing Company',
      'Billing Street',
      'Billing Zip',
      'Billing City',
      'Billing State',
      'Billing State Name',
      'Billing Country',
      'Billing Country Name',
      'Billing Phone Number',
      'Order Item Increment',
      'Item Name',
      'Item Status',
      'Item SKU',
      'Item Options',
      'original_price',
      'Item Selling Price',
      'Item Qty Ordered',
      'Item Qty Invoiced',
      'Item Qty Shipped',
      'Item Qty Canceled',
      'Item Qty Refunded',
      'Item Tax',
      'Item Discount',
      'Item Total',
      'price_per_lb',
      'Coupon Code',
      'GST Number',
      'premium_care',

      );
      }

      protected function writeOrder($order, $fp)
      {
      $common = $this->getCommonOrderValues($order);


      $orderItems = $order->getAllVisibleItems();
      $itemInc = 0;
      $item = "";
      foreach ($orderItems as $item)
      {
      // if (!$item->isDummy()) {
      $record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
      fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
      // }
      }

      }

      protected function getCommonOrderValues($order)
      {
      $shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
      $billingAddress = $order->getBillingAddress();

      $payment = $order->getPayment();
      $method = $payment->getMethodInstance();
      $methodTitle = $method->getTitle();

      $total_item_qty = $this->getTotalQtyItemsOrdered($order);

      $priceHelper = $this->objectManager->create('MagentoFrameworkPricingHelperData');
      $objDate = $this->objectManager->create('MagentoFrameworkStdlibDateTimeTimezoneInterface');
      $country_name = $this->objectManager->create('MagentoDirectoryModelCountry');
      //echo $order->getData('price_per_lb'); exit;
      return array(
      $order->getIncrementId(),
      $objDate->date(new DateTime($order->getCreatedAt()))->format('m-d-Y'),
      $order->getStatus(),
      $order->getData('store_name'),
      $methodTitle,
      $order->getData('shipping_method'),
      $order->getData('po_number'),

      $order->getData('c_market_price'),
      number_format($order->getData('subtotal'), 2, '.',''),
      number_format($order->getData('tax_amount'), 2, '.',''),
      number_format($order->getData('shipping_amount'), 2, '.',''),
      number_format($order->getData('discount_amount'), 2, '.',''),
      number_format($order->getData('grand_total'), 2, '.',''),
      number_format($order->getData('total_paid'), 2, '.',''),
      number_format($order->getData('total_refunded'), 2, '.',''),
      number_format($order->getData('total_due'), 2, '.',''),
      $total_item_qty,
      $order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
      $order->getData('customer_email'),
      $shippingAddress ? $shippingAddress->getName() : '',
      $shippingAddress ? $shippingAddress->getData("company") : '',
      $shippingAddress ? $shippingAddress->getData("street") : '',
      $shippingAddress ? $shippingAddress->getData("postcode") : '',
      $shippingAddress ? $shippingAddress->getData("city") : '',
      $shippingAddress ? $shippingAddress->getRegion() : '',
      $shippingAddress ? $shippingAddress->getRegion() : '',
      $shippingAddress ? $shippingAddress->getdata("country_id") : '',
      $shippingAddress ? $shippingAddress->getData("country_id") : '',
      $shippingAddress ? $shippingAddress->getData("telephone")."/".$shippingAddress->getData("fax") : '',
      $order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
      $billingAddress->getData("company"),
      $billingAddress->getData("street"),
      $billingAddress->getData("postcode"),
      $billingAddress->getData("city"),
      $billingAddress->getRegionCode(),
      $billingAddress->getRegion(),
      $billingAddress->getData("country_id"),
      $country_name->load($billingAddress->getData("country_id"))->getName(),
      $billingAddress->getData("telephone")."/".$billingAddress->getData("fax")
      );

      }

      protected function getOrderItemValues($item, $order, $itemInc=1)
      {
      $custom_option = "";
      if($item->hasProductOptions()){
      if (array_key_exists("options",$item->getData('product_options'))){
      $option_coll = $item->getData('product_options')['options'];
      foreach ($option_coll as $cptions) {
      $custom_option .= strip_tags($cptions['label']).";";
      }
      }
      }

      //$priceOrder = $this->getPricePer($item);
      //$product = $this->objectManager->get('MagentoCatalogModelProduct')->load($item->getId());
      //$offerinfo = $product->getResource()->getAttribute("offer")->getFrontend()->getValue($product);
      //unset($product);
      //echo "suman"; die;
      //print_r($item->getPricePerLb()); exit;
      return array(
      $itemInc,
      $item->getName(),
      $item->getStatus(),
      $item->getSku(),
      $custom_option,
      $item->getOriginalPrice(),
      $item->getPrice(),
      (int)$item->getQtyOrdered(),
      (int)$item->getQtyInvoiced(),
      (int)$item->getQtyShipped(),
      (int)$item->getQtyCanceled(),
      (int)$item->getQtyRefunded(),
      $order->getData('tax_amount'),
      abs($item->getData('discount_amount')),
      $item->getData('row_total') - $item->getDiscountAmount(),
      abs($item->getPricePerLb()),

      $order->getCouponCode(),
      $order->getBillingAddress()->getData('vat_id')
      );


      }

      protected function getTotalQtyItemsOrdered($order)
      {

      $qty = 0;

      $orderedItems = $order->getAllVisibleItems();
      foreach ($orderedItems as $qitem)
      {
      //if (!$item->isDummy()) {
      $qty += (int)$qitem->getQtyOrdered();
      //}
      }

      return $qty;

      }


      Code of Sales_order_grid is:



      <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="../../../../Ui/etc/ui_configuration.xsd">
      <listingToolbar name="listing_top">
      <!-- add export mass action -->
      <massaction name="listing_massaction">
      <action name="export">
      <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
      <item name="confirm" xsi:type="array">
      <item name="title" xsi:type="string" translate="true">Export Order</item>
      <item name="message" xsi:type="string" translate="true">Export selected orders?</item>
      </item>
      <item name="type" xsi:type="string">export</item>
      <item name="label" xsi:type="string" translate="true">Export</item>
      <item name="url" xsi:type="url" path="orderexport/order/massExport"/>
      </item>
      </argument>
      </action>
      </massaction>
      </listingToolbar>




      Now i want to create one button in top like same as create new order, and want to give option to export csv as per store view.



      for creating button i add xml code in sales_order_grid.xml



          <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
      <item name="confirm" xsi:type="array">
      <item name="title" xsi:type="string" translate="true">Export Order</item>
      <item name="message" xsi:type="string" translate="true">Export selected orders?</item>
      </item>
      <item name="type" xsi:type="string">export</item>
      <item name="label" xsi:type="string" translate="true">Export</item>
      <item name="url" xsi:type="url" path="orderexport/order/orderExport"/>
      </item>
      </argument>


      Now how can i give the option of all the stores, and how i set the condition to export selected stores csv?









      share














      I am using magento 2.1.5, i have created custom module for order export csv. but i created this export option in mass action.



      enter image description here



      and i did code like this:



       use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
      use MagentoBackendAppActionContext;
      use MagentoSalesModelResourceModelOrderCollectionFactory;
      use MagentoUiComponentMassActionFilter;
      use MagentoFrameworkAppResourceConnection;
      use MagentoFrameworkAppDeploymentConfig;
      use MagentoFrameworkConfigConfigOptionsListConstants;
      use MagentoFrameworkAppFilesystemDirectoryList;
      class MassExport extends
      MagentoSalesControllerAdminhtmlOrderAbstractMassAction
      {
      const ENCLOSURE = '"';
      const DELIMITER = ',';

      protected $_directoryList;
      public $_resource;
      private $deploymentConfig;
      private $objectManager;
      public function __construct(Context $context,
      ResourceConnection $resource,
      Filter $filter, CollectionFactory $collectionFactory,DeploymentConfig
      $deploymentConfig,DirectoryList $directory_list)
      {

      $this->_resource = $resource;
      parent::__construct($context , $filter);
      $this->deploymentConfig = $deploymentConfig;
      $this->collectionFactory = $collectionFactory;
      $this->_directoryList = $directory_list;
      $this->objectManager = MagentoFrameworkAppObjectManager::getInstance();

      }
      /**
      * Cancel selected orders
      *
      * @param AbstractCollection $collection
      * @return MagentoBackendModelViewResultRedirect
      */
      protected function massAction(AbstractCollection $collection)
      {

      if (!file_exists($this->_directoryList->getRoot().'/pub/media/OrderExport')) {
      mkdir($this->_directoryList->getRoot().'/pub/media/OrderExport', 0777, true);
      }

      $todayDate = date('Y_m_d_H_i_s', time());
      $fileName = $this->_directoryList->getRoot().'/pub/media/OrderExport/OrderExport'.$todayDate.'.csv';


      $fp = fopen($fileName, 'w');
      $this->writeHeadRow($fp);

      $countOrderExport = 0;
      foreach ($collection->getItems() as $_order) {

      $orderId = $_order->getId();
      if ($orderId) {
      $order = $this->objectManager->create('MagentoSalesModelOrder')->load($_order->getId());
      $this->writeOrder($order, $fp);
      $incId = $order->getIncrementId();
      $countOrderExport++;
      }
      }
      fclose($fp);

      $this->downloadCsv($fileName);
      $this->messageManager->addSuccess(__('We Exported %1 order(s).', $countOrderExport));

      //$resultRedirect = $this->resultRedirectFactory->create();
      //$resultRedirect->setPath('sales/*/');
      //return $resultRedirect;
      }


      public function downloadCsv($file)
      {

      if (file_exists($file)) {
      //set appropriate headers
      header('Content-Description: File Transfer');
      header('Content-Type: application/csv');
      header('Content-Disposition: attachment; filename='.basename($file));
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file));
      ob_clean();flush();
      readfile($file);
      }
      }

      protected function writeHeadRow($fp)
      {
      fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
      }

      protected function getHeadRowValues()
      {
      return array(
      'Order Number',
      'Order Date',
      'Order Status',
      'Order Purchased From',
      'Order Payment Method',
      'Order Shipping Method',
      'po_number',
      'c_market_price',
      'Order Subtotal',
      'Order Tax',
      'Order Shipping',
      'Order Discount',
      'Order Grand Total',
      'Order Paid',
      'Order Refunded',
      'Order Due',
      'Total Qty Items Ordered',
      'Customer Name',
      'Customer Email',
      'Shipping Name',
      'Shipping Company',
      'Shipping Street',
      'Shipping Zip',
      'Shipping City',
      'Shipping State',
      'Shipping State Name',
      'Shipping Country',
      'Shipping Country Name',
      'Shipping Phone Number',
      'Billing Name',
      'Billing Company',
      'Billing Street',
      'Billing Zip',
      'Billing City',
      'Billing State',
      'Billing State Name',
      'Billing Country',
      'Billing Country Name',
      'Billing Phone Number',
      'Order Item Increment',
      'Item Name',
      'Item Status',
      'Item SKU',
      'Item Options',
      'original_price',
      'Item Selling Price',
      'Item Qty Ordered',
      'Item Qty Invoiced',
      'Item Qty Shipped',
      'Item Qty Canceled',
      'Item Qty Refunded',
      'Item Tax',
      'Item Discount',
      'Item Total',
      'price_per_lb',
      'Coupon Code',
      'GST Number',
      'premium_care',

      );
      }

      protected function writeOrder($order, $fp)
      {
      $common = $this->getCommonOrderValues($order);


      $orderItems = $order->getAllVisibleItems();
      $itemInc = 0;
      $item = "";
      foreach ($orderItems as $item)
      {
      // if (!$item->isDummy()) {
      $record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
      fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
      // }
      }

      }

      protected function getCommonOrderValues($order)
      {
      $shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
      $billingAddress = $order->getBillingAddress();

      $payment = $order->getPayment();
      $method = $payment->getMethodInstance();
      $methodTitle = $method->getTitle();

      $total_item_qty = $this->getTotalQtyItemsOrdered($order);

      $priceHelper = $this->objectManager->create('MagentoFrameworkPricingHelperData');
      $objDate = $this->objectManager->create('MagentoFrameworkStdlibDateTimeTimezoneInterface');
      $country_name = $this->objectManager->create('MagentoDirectoryModelCountry');
      //echo $order->getData('price_per_lb'); exit;
      return array(
      $order->getIncrementId(),
      $objDate->date(new DateTime($order->getCreatedAt()))->format('m-d-Y'),
      $order->getStatus(),
      $order->getData('store_name'),
      $methodTitle,
      $order->getData('shipping_method'),
      $order->getData('po_number'),

      $order->getData('c_market_price'),
      number_format($order->getData('subtotal'), 2, '.',''),
      number_format($order->getData('tax_amount'), 2, '.',''),
      number_format($order->getData('shipping_amount'), 2, '.',''),
      number_format($order->getData('discount_amount'), 2, '.',''),
      number_format($order->getData('grand_total'), 2, '.',''),
      number_format($order->getData('total_paid'), 2, '.',''),
      number_format($order->getData('total_refunded'), 2, '.',''),
      number_format($order->getData('total_due'), 2, '.',''),
      $total_item_qty,
      $order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
      $order->getData('customer_email'),
      $shippingAddress ? $shippingAddress->getName() : '',
      $shippingAddress ? $shippingAddress->getData("company") : '',
      $shippingAddress ? $shippingAddress->getData("street") : '',
      $shippingAddress ? $shippingAddress->getData("postcode") : '',
      $shippingAddress ? $shippingAddress->getData("city") : '',
      $shippingAddress ? $shippingAddress->getRegion() : '',
      $shippingAddress ? $shippingAddress->getRegion() : '',
      $shippingAddress ? $shippingAddress->getdata("country_id") : '',
      $shippingAddress ? $shippingAddress->getData("country_id") : '',
      $shippingAddress ? $shippingAddress->getData("telephone")."/".$shippingAddress->getData("fax") : '',
      $order->getData('customer_firstname')." ".$order->getData('customer_lastname'),
      $billingAddress->getData("company"),
      $billingAddress->getData("street"),
      $billingAddress->getData("postcode"),
      $billingAddress->getData("city"),
      $billingAddress->getRegionCode(),
      $billingAddress->getRegion(),
      $billingAddress->getData("country_id"),
      $country_name->load($billingAddress->getData("country_id"))->getName(),
      $billingAddress->getData("telephone")."/".$billingAddress->getData("fax")
      );

      }

      protected function getOrderItemValues($item, $order, $itemInc=1)
      {
      $custom_option = "";
      if($item->hasProductOptions()){
      if (array_key_exists("options",$item->getData('product_options'))){
      $option_coll = $item->getData('product_options')['options'];
      foreach ($option_coll as $cptions) {
      $custom_option .= strip_tags($cptions['label']).";";
      }
      }
      }

      //$priceOrder = $this->getPricePer($item);
      //$product = $this->objectManager->get('MagentoCatalogModelProduct')->load($item->getId());
      //$offerinfo = $product->getResource()->getAttribute("offer")->getFrontend()->getValue($product);
      //unset($product);
      //echo "suman"; die;
      //print_r($item->getPricePerLb()); exit;
      return array(
      $itemInc,
      $item->getName(),
      $item->getStatus(),
      $item->getSku(),
      $custom_option,
      $item->getOriginalPrice(),
      $item->getPrice(),
      (int)$item->getQtyOrdered(),
      (int)$item->getQtyInvoiced(),
      (int)$item->getQtyShipped(),
      (int)$item->getQtyCanceled(),
      (int)$item->getQtyRefunded(),
      $order->getData('tax_amount'),
      abs($item->getData('discount_amount')),
      $item->getData('row_total') - $item->getDiscountAmount(),
      abs($item->getPricePerLb()),

      $order->getCouponCode(),
      $order->getBillingAddress()->getData('vat_id')
      );


      }

      protected function getTotalQtyItemsOrdered($order)
      {

      $qty = 0;

      $orderedItems = $order->getAllVisibleItems();
      foreach ($orderedItems as $qitem)
      {
      //if (!$item->isDummy()) {
      $qty += (int)$qitem->getQtyOrdered();
      //}
      }

      return $qty;

      }


      Code of Sales_order_grid is:



      <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="../../../../Ui/etc/ui_configuration.xsd">
      <listingToolbar name="listing_top">
      <!-- add export mass action -->
      <massaction name="listing_massaction">
      <action name="export">
      <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
      <item name="confirm" xsi:type="array">
      <item name="title" xsi:type="string" translate="true">Export Order</item>
      <item name="message" xsi:type="string" translate="true">Export selected orders?</item>
      </item>
      <item name="type" xsi:type="string">export</item>
      <item name="label" xsi:type="string" translate="true">Export</item>
      <item name="url" xsi:type="url" path="orderexport/order/massExport"/>
      </item>
      </argument>
      </action>
      </massaction>
      </listingToolbar>




      Now i want to create one button in top like same as create new order, and want to give option to export csv as per store view.



      for creating button i add xml code in sales_order_grid.xml



          <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
      <item name="confirm" xsi:type="array">
      <item name="title" xsi:type="string" translate="true">Export Order</item>
      <item name="message" xsi:type="string" translate="true">Export selected orders?</item>
      </item>
      <item name="type" xsi:type="string">export</item>
      <item name="label" xsi:type="string" translate="true">Export</item>
      <item name="url" xsi:type="url" path="orderexport/order/orderExport"/>
      </item>
      </argument>


      Now how can i give the option of all the stores, and how i set the condition to export selected stores csv?







      magento2 sales-order sales-order-grid





      share












      share










      share



      share










      asked 1 min ago









      samsam

      140215




      140215






















          0






          active

          oldest

          votes











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "479"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f265830%2forder-export-per-store-view-in-magento-2%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f265830%2forder-export-per-store-view-in-magento-2%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          What other Star Trek series did the main TNG cast show up in?

          Berlina muro

          Berlina aerponto