Magento 2 Snippets

In it’s complexity I find one can lose a lot of time in just looking for the right mark-up for the right situation. That’s why I decided to make this little ‘scrap-book’ of snippets.

Overwriting files

Overwriting files in Magento 2 isn’t as straightforward as was with Magento 1. There you just had to have the same path and you’re done. In Magento 2, this is a bit different.
Take a look at these examples and try to see the pattern:

Source
/vendor/magento/module-theme/view/frontend/templates/html/header.phtml
Goal
/app/design/frontend/${VENDORNAME}/${THEMENAME}/Magento_Theme/templates/html/header.phtml

Source
vendor/magento/module-theme/view/frontend/templates/html/topmenu.phtml
Goal
app/design/frontend/${VENDORNAME}/${THEMENAME}/Magento_Theme/templates/html/topmenu.phtml

Source
/vendor/magento/module-catalog/view/frontend/templates/category/image.phtml
Goal
app/design/frontend/${VENDORNAME}/${THEMENAME}/Magento_Catalog/templates/html/topmenu.phtml

Get URLs

Get current URL

<?php echo $block->getUrl();?>
<?php $this->_storeManager->getStore()->getBaseUrl(); ?>
<?php $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); ?>

Get media URL

<?php 
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of\Magento\Framework\App\ObjectManager
$storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); 	
?>

Get checkout URL

<?php $this->getUrl('checkout', ['_secure' => true]); ?>

Get static URL

<?php $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC); ?>

Get JS URL

<?php $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_JS); ?>

SSH

Set base url via CLI
php bin/magento setup:store-config:set --base-url="http://your.baseurl.com/shop/"
php bin/magento setup:store-config:set --base-url-secure="https://your.baseurl.com/shop/"