Order Export Per store View in magento 2How can i rewrite TierPrice Block in Magento2main.CRITICAL: Plugin class doesn't existMagento2 price per store viewMagento 2: How to override newsletter Subscriber modelMagento2 - Impossible to get widget configurationMagento 2 Add new field to Magento_User admin formOverriding Invoice / Interceptor, modifying the PDF generation for an Invoice orderMagento 2 sales order grid custom column export csv issueMagento offline custom Payment method with drop down listHow to solve Front controller reached 100 router match iterations in magento2

Potentiometer like component

Welcoming 2019 Pi day: How to draw the letter π?

Unreachable code, but reachable with exception

Force user to remove USB token

Should we release the security issues we found in our product as CVE or we can just update those on weekly release notes?

Do I need to leave some extra space available on the disk which my database log files reside, for log backup operations to successfully occur?

How does Dispel Magic work against Stoneskin?

Need some help with my first LaTeX drawing…

How can I discourage/prevent PCs from using door choke-points?

Running a subshell from the middle of the current command

If the Captain's screens are out, does he switch seats with the co-pilot?

Decoding assembly instructions in a Game Boy disassembler

Time dilation for a moving electronic clock

Co-worker team leader wants to inject the crap software product of his friends into our development. What should I say to our common boss?

Draw arrow on sides of triangle

What is the likely impact on flights of grounding an entire aircraft series?

Confusion with the nameplate of an induction motor

What is the difference between "shut" and "close"?

How to deal with a cynical class?

Making a sword in the stone, in a medieval world without magic

What is the definition of "Natural Selection"?

My adviser wants to be the first author

Is a lawful good "antagonist" effective?

Is all copper pipe pretty much the same?



Order Export Per store View in magento 2


How can i rewrite TierPrice Block in Magento2main.CRITICAL: Plugin class doesn't existMagento2 price per store viewMagento 2: How to override newsletter Subscriber modelMagento2 - Impossible to get widget configurationMagento 2 Add new field to Magento_User admin formOverriding Invoice / Interceptor, modifying the PDF generation for an Invoice orderMagento 2 sales order grid custom column export csv issueMagento offline custom Payment method with drop down listHow to solve Front controller reached 100 router match iterations in magento2













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.



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',
'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',
'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');
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'),
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);
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(),
$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.



How can i achieve this?










share|improve this question




























    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.



    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',
    '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',
    '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');
    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'),
    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);
    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(),
    $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.



    How can i achieve this?










    share|improve this question


























      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.



      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',
      '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',
      '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');
      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'),
      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);
      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(),
      $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.



      How can i achieve this?










      share|improve this question
















      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.



      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',
      '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',
      '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');
      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'),
      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);
      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(),
      $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.



      How can i achieve this?







      magento2 sales-order sales-order-grid






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 5 mins ago







      sam

















      asked 16 mins 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

          Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

          Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

          How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2