How to create new command in magento2

Step1:- Declare module in etc/module.xml


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Ecommoco_Command" setup_version="1.0.0" />
</config>

Step2: Register module in registration.php


<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Ecommoco_Command',
__DIR__
);

Step3: Declare command in etc/di.xml


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandList">
<arguments>
<argument name="commands" xsi:type="array">
<item name="firstcommand" xsi:type="object">Ecommoco\Command\Console\Firstcommand</item>
</argument>
</arguments>
</type>
</config>

Step4: Create the class for execution


<?php
namespace Ecommoco\Command\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Firstcommand extends Command
{
protected function configure()
{
$this->setName('ecommoco:first');
$this->setDescription('First Command');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("First command");
}
}

Activate the module

Advertisements

Export products to csv by script

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$collection = Mage::getModel(‘catalog/product’)
->getCollection()
->addAttributeToSelect(‘*’)
->addUrlRewrite();

// create a file pointer connected to the output stream
header(‘Content-Type: text/csv; charset=utf-8’);
header(‘Content-Disposition: attachment; filename=all_products.csv’);
$output = fopen(‘php://output’, ‘w’);

// output the column headings
fputcsv($output, array(‘id’, ‘sku’, ‘title’, ‘url’, ‘image0′,’image1′,’image2′,’image3′,’status’,’price’,’special_price’,’special_from_date’,’special_to_date’,’qty’,’is_in_stock’,’type’));
foreach($collection as $product) {
//Load the product categories
$categories = $product->getCategoryIds();
//Select the last category in the list
$categoryId = end($categories);
//Load that category
$category = Mage::getModel(‘catalog/category’)->load($categoryId);
// Collect details in variables
$title=$product->getName();
$sku=$product->getSku();
$id=$product->getId();

$url=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).$product->getUrlPath();
//$image=str_replace(‘export.php/’,”,Mage::getBaseUrl()).$product->getUrlPath($category);
$image=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . ‘catalog/product’ . $product->getImage();

//Gallary
//$_product = $product->load($product->getId());
$gallary = [”,”,”,”];
$mediaApi = Mage::getModel(‘catalog/product_attribute_media_api’);
$mediaItems = $mediaApi->items($product->getId());
foreach ($mediaItems as $key=> $images) {
$gallary[$key]=$images[‘url’];
}

$price=$product->getPrice();
$status = ‘Disabled’;
if(‘1’ == $product->getStatus()){
$status = ‘Enabled’;
}
$type=$product->getTypeId();
$sp=$product->getFinalPrice();
$from=$product->getSpecialFromDate();
$to = $product->getSpecialToDate();

$stock_item = Mage::getModel(‘cataloginventory/stock_item’)->loadByProduct($id);
$qty = $stock_item->getQty();
$stock =$stock_item->getIsInStock();
fputcsv($output, array( $id, $sku, $title, $url,$gallary[0],$gallary[1],$gallary[2],$gallary[3], $status,$price,$sp,$from,$to,$qty,$stock, $type));
}

Magento get image gallery

$gallery = [];

$product = Mage::getModel(‘catalog/product’)->load(1);
$mediaApi = Mage::getModel(‘catalog/product_attribute_media_api’);
$mediaItems = $mediaApi->items($product->getId());
foreach ($mediaItems as $key=> $images) {
$gallery[]=$images[‘url’];
}

var_dump($gallery);

Module redirect to admin store in multi store.

Open config.xml of your module

<admin>

    <routers>
        <{vendor}>
            <use>admin</use>
            <args>
                <module>{Vendorname}_{Modulename}l</module>
                <frontName>{urlcode}</frontName>
            </args>
        </{vendor}>
    </routers>
</admin>
Replace above  code with below
<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <{Vendorname}_{Modulename}_Adminhtml before="Mage_Adminhtml">{VendorName}_{Modulename}_Adminhtml</{Vendorname}_{Modulename}_Adminhtml>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

Add Discount Coupon in Magento One Page Checkout at review step

Step 1: Add following method on checkout controller
app/code/core/Mage/Checkout/controllers/OnepageController.php

function couponAction() {

$this->loadLayout('checkout_onepage_review');
	
	$this->couponCode = (string) $this->getRequest()->getParam('coupon_code');
	$codeLength = strlen($this->couponCode );

	Mage::getSingleton('checkout/cart')->getQuote()->getShippingAddress()->setCollectShippingRates(true);
	
	Mage::getSingleton('checkout/cart')->getQuote()->setCouponCode(strlen($this->couponCode) ?
	
	$this->couponCode : ' ')->collectTotals()->save();
	
	if ($codeLength) {
        if ( $this->couponCode == Mage::getSingleton('checkout/cart')->getQuote()->getCouponCode()) {
	        $result['success']='true';
                $result['error'] = false;
	        $result['message']=$this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($this->couponCode));
	        } else {
	        $result['success']='false';
	       // $result['error']=true;
	        $result['error_message']=$this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($this->couponCode));
	
	        }
	    } else {
	
	    $result['success']='true';
	    $result['error']=false;
	    $result['message']=$this->__('Coupon code was canceled.');
	
	    }
	
	$result['goto_section'] = 'review';
	
	$result['update_section'] = array( 'name' => 'review', 'html' => $this->_getReviewHtml() );
	
	$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

}

Step 2: Add Js script to phtml file
Open file: app/design/frontend/base/default/template/checkout/onepage.phtml
//<![CDATA[

function updateCoupon(reqid) {

var reqid;

if(reqid == 2) { $(‘coupon_code’).setValue(”); }

$(‘discount-coupon-form’).request({

method: ‘post’,

onComplete: payment.onComplete,

onSuccess: payment.onSave,

onFailure: checkout.ajaxFailure.bind(checkout),

})

}

//]]>

Step 3: Adding form to phtml file

app/design/frontend/base/default/template/checkout/onepage/agreements.phtml

<?php

$CouponCode = Mage::getSingleton(‘checkout/cart’)->getQuote()->getCouponCode(); ?>
<form id=”discount-coupon-form” action=”<?php echo Mage::getBaseUrl()?>/checkout/onepage/coupon/” method=”post”>
<label for=”coupon_code”> <?php echo $this->__(‘Enter your coupon code if you have one.’) ?></label><br />

<input id=”coupon_code” name=”coupon_code” value=”<?php echo $CouponCode; ?>”/>

<?php if(strlen($CouponCode)) { ?>

<button type=”button” onclick=”updateCoupon(2);” value=”<?php echo $this->__(‘Remove Coupon’)?>”><span><?php echo $this->__(‘Remove Coupon’) ?></span></button>

<?php } ?>

<button type=”button” onclick=”updateCoupon(1);” value=”<?php echo $this->__(‘Apply Coupon’)?>”><span><?php echo $this->__(‘Apply Coupon’) ?></span></button>

</form>