Category Archives: Magento 2.0 Tutorial

Magento 2 Override Controller


Magento 2 Override Controller
It is very simple to override controller in Magento 2. Here in this article we are going to explain how you can override
Magento\Catalog\Controller\Product\View controller.

First of all you need to create di.xml inside module etc folder and you need to add the preferences & type inside this.


Magento 2 Override Controller Example

Let us understand this with real time example-

1. Create di.xml

Create di.xml and add the following code-

Example:



    

Create Controller

Now create View controller in your local module ie. View.php in Tutorialsplane\Helloworld\Controller\Rewrite\Product\ folder.

Example:


All set, you are done. Now core controller \Magento\Catalog\Controller\Product\View is overriden by local module
controller Tutorialsplane\Helloworld\Controller\Rewrite\Product.

Magneto 2 Add product to cart programmatically


Magneto 2 Add product to cart programmatically- We sometimes need to add products to shopping cart using custom code. Here in this article, we are going to explain how you can add products in cart using Magento\Checkout\Model\Cart class.


Magneto 2 Add product to cart programmatically Example

You can add product to cart using factory method & cart session object.

Magneto 2 Add product to cart programmatically

Factory Method

Using factory method you can add product to cart using product id simply as below-

Magneto 2 Add product to cart programmatically:


protected $formKey;   
protected $cart;
protected $product;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
array $data = []) {
    $this->formKey = $formKey;    
    $this->product = $product; 
    $this->cart = $cart;     
    parent::__construct($context);
}

public function execute()
 { 
  $productId =189;
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId,
                'qty'   =>1 //quantity to add             
            );              
    //Load the product based on productID   
    $product = $this->product->load($productId);       
    $this->cart->addProduct($product, $params);
    $this->cart->save();
 }


Magento 2 get product collection filter by Attribute


Magento 2 get product collection filter by Attribute– We often need to load product collection filter by custom attribute. It is very simple to add attribute filter in product collection. Here in this article, we are going to explain how you can add attribute filter to product collection.


Magento 2 get product collection filter by Attribute Example

You can add attribute filter to collection simply as below-

Magento 2 get product collection filter by Attribute

Example:

$productcollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
        ->addAttributeToSelect('*')
        ->addAttributeToFilter(
            array(
                array('attribute'=>'color','eq'=>'red')
            )
        );

The above example will give you output with filter attribute color. On the same way you can add other attributes filter.

Magento 2 get store id by store code


Magento 2 get store id by store code– We can use class \Magento\Store\Model\StoreManagerInterface to get the store id by store code. Here in this article we are going to explain how you can get store id by store code using object manager.


Magento 2 get store id by store code Example

You can use \Magento\Store\Model\StoreManagerInterface to get the store id from store code simply as below-

Example:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();    
$storeManager = $objectManager->create("\Magento\Store\Model\StoreManagerInterface");
$storecode = 'my_store_1';
    $allStores = $storeManager->getStores(true, false);
    foreach($allStores as $store){
    if($store->getCode() === $storecode){
        $storeId = $store->getId();
    }
   }
echo $storeId;

$storeManager->getStores return all stores so you have to match your store code and get store id. On the same way you can get other details about the store.

Magento 2 get product collection by category id


Magento 2 get product collection by category id We can get category products by category id using \Magento\Catalog\Model\CategoryFactory object. Here in this article, we are going to explain how you can get product collection of any category using object manager.


Magento 2 get product collection by category id Example

You can get category product collection simply as below-

Example:

$categoryId = 999;
$objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
$catProductCollection = $objectManager->create('\Magento\Catalog\Model\CategoryFactory')->load($categoryId)->getProductCollection()->addAttributeToSelect('*');

foreach($catProductCollection as $product){
  echo $product->getName();
  echo "
"; echo $product->getSku(); }

Magento 2 Get Post Data in Observer


Magento 2 Get Post Data in Observer– We can get the form post/get value in observer using request interface in constructor. Here in this tutorial, we are going to explain how you can get the form post data in observer in Magento 2.


Magento 2 Get Post Data in Observer Example

First of all you need to inject \Magento\Framework\App\RequestInterface $request in class constructor then you can get the form post value in observer simply as below-

Example:

_request = $request;
}
 public function execute(\Magento\Framework\Event\Observer $observer)

 {
  $postData = $this->_request->getPost();
  print_r($postData);
  }

}

On the same way you can use request/post or get method to get the form post data.

Magento 2 get payment method from order


Magento 2 get payment method from order- We can get payment method code from order object in Mageto 2. We can use dependency injection or object manager to get the order object. Here in this article, we are going to explain how you can get the payment details such as – payment method title, method code and cc_type etc.


Magento 2 get payment method from order Example

First of all load order object by order id then get payment object, Using payment object you can get the payment details simply as below-

Magento 2 get payment method from order

Example:

$orderId = 9999;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('\Magento\Sales\Model\Order')                           ->load($orderId);
$payment = $order->getPayment();
$method = $payment->getMethodInstance();

$paymentMethod = $method->getTitle();

$ccType = $method->getCcType();

On the same way you can get other details about payment method.

Magento 2 Update Product Price Programmatically


Magento 2 Update Product Price Programmatically– We can update product price using product object in Magento 2. Sometimes we need to update product price on run time, we can update price on website and store level using product object. Here in this tutorial, we are going to explain the one of the simplest way to update product price in Magento 2.


Magento 2 Update Product Price Programmatically Example

Let us understand how to update product price in Magento 2. Here is an example-

Magento 2 Update Product Price Programmatically

Example:

$storeId = '2'; //SET Store ID
$productId = 190;
$price = 50.20;
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create()->setStoreId($storeId)->load($productId);
$product->setPrice($price);
$product->save();

In the above example we have loaded product by id(190), Using object manager we have loaded product for store( store id = 2). Then we have updated price for product simply as in above example.

Magento 2 change order status programmatically


Magento 2 change order status programmatically- We sometimes need to update order status programmatically in Magento 2, we can use object manager to update the order status. Here in this tutorial, we are going to explain how you can change order status programmatically in magento 2.


Magento 2 change order status programmatically Example

You can change order status in Magento 2 simply as below-

magento 2 change order status programmatically

Example:

$orderId = 100;
$objManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objManager->create('\Magento\Sales\Model\Order') ->load($orderId);
$newState = Order::STATE_PROCESSING;
$order->setState($newState)->setStatus(Order::STATE_PROCESSING);
$order->save();

On the same way you can update order status for particular order.