Skip to content

Instantly share code, notes, and snippets.

@gelanivishal
Last active June 24, 2016 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gelanivishal/4a2dc32171aa81c18fb765eec8d0b93a to your computer and use it in GitHub Desktop.
Save gelanivishal/4a2dc32171aa81c18fb765eec8d0b93a to your computer and use it in GitHub Desktop.

Magento 2 Tips, Tricks and Snippets

Infos About Store##

inject \Magento\Store\Model\StoreManagerInterface $storeManage
$this->storeManager = $storeManager;

Get Store id
$id = $this->storeManager->getStore()->getId();
Get Base Url
$baseUrl = $this->storeManager->getStore()->getBaseUrl();
Currency
$baseCurrency = $this->storeManager->getStore()->getBaseCurrencyCode(); //get base currency code
$baseCurrency = $this->storeManager->getStore()->getBaseCurrency();
$baseCurrency = $this->storeManager->getStore()->getDefaultCurrencyCode();
$baseCurrency = $this->storeManager->getStore()->getDefaultCurrency();

$currentCurrency = $this->storeManager->getStore()->getCurrentCurrencyCode(); //get current currency code 
$currentCurrency = $this->storeManager->getStore()->getCurrentCurrency(); 
$currentCurrency = $this->storeManager->getStore()->getAvailableCurrencyCodes();
$currentCurrency = $this->storeManager->getStore()->getAllowedCurrencies(); 
// To convert currency 
print_r($this->currency->getCurrencyRates($this->currency->getConfigBaseCurrencies(), $this->currency->getConfigAllowCurrencies()));
Retrieve base media directory path
$baseMediaDir  = $this->storeManager->getStore()->getBaseMediaDir();
Retrieve base static directory path
$baseStaticDir  = $this->storeManager->getStore()->getBaseStaticDir();

Cart Data

inject Magento\Checkout\Model\Cart $cart
$this->cart = $cart;

Get total number items
$cartCount = $this->cart->getItemsCount();
##### Get quote data ##### 
$cartQuote= $this->cart->getQuote()->getData();

##### clear quote ##### 
```php  
iterate items of cart from session :
inject Magento\Checkout\Model\Session $session
$this->session  =  $session;
 
foreach ($this->session->getQuote()->getAllItems() as $item) {
    echo $item->getName();
}

$this->session ->clearQuote();

Catalog

inject \Magento\Framework\Registry $registry
$this->registry = $registry;

Get current category
$category = $this->registry->registry('current_category');
Get curent category id
$cid = $this->registry->registry('current_category')->getId();
Get current category level
$level = $this->registry->registry('current_category')->getLevel();
Get current product
$pid  =$this->registry->registry('current_product');
Retrieve crosssell products from current product
$products = [];
foreach ($this->registry->registry('current_product')->getCrossSellProducts() as $product) {
	$products[$product->getId()] = ['position' => $product->getPosition()];
}
print_r($products);
Retrieve related products from current product:#####
$products = [];
foreach ($this->registry->registry('current_product')->getRelatedProducts() as $product) {
	$products[$product->getId()] = ['position' => $product->getPosition()];
}
print_r($products);
Retrieve upsell products from current product#####
$products = [];
foreach ($this->registry->registry('current_product')->getUpSellProducts() as $product) {
	$products[$product->getId()] = ['position' => $product->getPosition()];
}
print_r($products);
Test if current product is registered:#####
if ($this->registry->registry('current_product')) {
	$product = $this->registry->registry('current_product');
} else {
	throw new \LogicException('Product is not defined');
}

CMS

inject \Magento\Framework\Registry $registry $this->registry = $registry;

Get current cms page
$page = $this->registry->registry('cms_page');
Get id of current cms page#####
$cmsId = $this->registry->registry('cms_page')->getId();
Test if cms page exist in table
if ($this->registry->registry('cms_page')->getId()) {
	return $this->registry>registry('cms_page')->getTitle();
} else {
	return __('New Page');
}

View

inside any block that extend \Magento\Framework\View\Element\Template you can use :

//getting assets elements url from your extension in current theme
$loader = $this->getViewFileUrl("ibnab_lazy::images/loader.svg");
//or getting from assets of current theme :
$js = $this->getViewFileUrl("js/my.js");

Extra

Change number into currency format

Convert number into currency format using the following code snippet:

$this->helper('Magento\Framework\Pricing\Helper\Data')-  >currency(number_format(50,2),true,false);
Restore the order object on order confirmation page

Retrieve order object on success .phtml page using the following code snippet:

/**
* Checkout session
*
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
 
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Sales\Model\Order $salesOrderFactory
* @param \Magento\Checkout\Model\Session $checkoutSession
*/
public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Model\Order $salesOrderFactory,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    ) {
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
    }
 
/**
* Retrieve current order
*
* @return \Magento\Sales\Model\Order
*/
public function getOrder()
{
   $orderId = $this->_checkoutSession->getLastOrderId();
   return $this->_salesFactory->load($orderId);
}
Or you can do by other code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderId = $objectManager->create('\Magento\Checkout\Model\Session')
                           ->getLastOrderId();      
$order = $objectManager->create('\Magento\Sales\Model\Order')
                           ->load($orderId); 
Retrieve product object
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('\Magento\Catalog\Model\Product')
                           ->load(291)
Retrieve request object
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('\Magento\Framework\App\Request\Http')
                            ->getParam('product', 0);
URL Redirections and URL Builder
namespace Excellence\Hello\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
class Actionname name extends \Magento\Framework\App\Action\Action
{
      public function execute()
      {
           $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
           $resultRedirect->setUrl($this->_redirect->getRefererUrl()); // Previous URL
		   $resultRedirect->setPath('excellence/index/add'); // URL path
           return $resultRedirect;
      }
}

return $this->resultRedirectFactory->create()->setPath('excellence/index/add/', ['_current' => true]); 

If we use [‘_current’ => true]  then the objects being passed via query string will remain in the redirected URL but if we don’t use [‘_current’ => true] or use [‘_current’ => false], then objects will not be passed in the redirected URL.

// URL Builder:
$this->_urlBuilder->getUrl("excellence/index/add/")
Request Response JSON
// To read data passed via get Method we simply use following two methods:
$this->getRequest()->getParams()
// this will read all the get data but to read any specific data we use
$this->getRequest()->getParam('data');
// To read data passed via POST method, we use following method:
$this->request->getPost()
this will read all the the data being passed via post. But if we want to read specific data then we will use
// $this->getRequest()->getPost('data');
$post = $this->getRequest()->getPostValue();

// The above methods will work if you are trying this from a controller that extends Magento\Framework\App\Action\Action you can get the request. In other cases you need to inject request in the constructor as:

class ClassName
{
     protected $request;
     public function __construct(
     \Magento\Framework\App\Request\Http $request,
     ....//rest of parameters here
     ) {
          $this->request = $request;
          ...//rest of constructor here
     }
     public function getPost()
     {
          return $this->request->getPost();
     }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment