Thursday, January 7, 2016

Snippets for Magento 2 Developers

1 - Get ObjectManager Instance
$objectManager      = \Magento\Framework\App\ObjectManager::getInstance();
$customerCollection = $objectManager->create('Magento\Customer\Model\CollectionFactory')->getCollection();

2 - Get BaseUrl
//inject \Magento\Store\Model\StoreManagerInterface $storeManager in constructor
$this->_storeManager = $storeManager;

$url = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); //url in media directory

3 - Get Session Customer
//inject \Magento\Customer\Model\Session $customerSession in constructor
$this->_session = $customerSession;


4 - Get Featured Products Collection
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //dirty way
$productCollection = $objectManager->create('Magento\Catalog\Model\ProductFactory')->getCollection();
//filters
$featuredProducts = $productCollection
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('price')
                ->addAttributeToFilter('is_featured', 1)
                ->addAttributeToFilter('status', 1)
                ->setPageSize($productCollection->getSize())
                ->setCurPage(1)
                ->load();


5 - Insert Image in Static block or cms page
{{view url="images/image-1.jpg"}} //Url: app/design/VendorName/ThemeName/web/images/image-1.jpg

6 - Call Block in template
$block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('block_id')->toHtml();

7 - Call Block in CMS Page
{{block class="Magento\Cms\Block\Block" block_id="block_id"}}

8 - View media
{{view url=Magento_Catalog::images/logo.png}} //in this case, path: pub/static/frontend/Magento/blank/en_US/Magento_Catalog/images/logo.png 

{{media url=test/logo.svg}}" // path: pub/media/test/logo.svg

{{store url="translation/ajax/index"}} // this tag similar like in Magento1x. Url from your current store

9 - Get Media URL
$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')->getDirectoryRead(DirectoryList::MEDIA);  
$fileAbsolutePath = $this->filesystem->getDirectoryRead(DirectoryList::ROOT)->getAbsolutePath($filePath);

10 - Get/Set Config Value from system
$val = $this->scopeConfig->getValue('rss/config/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)
$val = Magento\Framework\App\Config\MutableScopeConfigInterface->setValue($path,$value,$scopeType = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT,$scopeCode = null);


Updated in January 23
To be continue.....

No comments:

Post a Comment