Skip to content

Instantly share code, notes, and snippets.

@molotovbliss
Last active July 1, 2021 16:59
Show Gist options
  • Save molotovbliss/a989f7894dd72b0ddc5b2332f915407d to your computer and use it in GitHub Desktop.
Save molotovbliss/a989f7894dd72b0ddc5b2332f915407d to your computer and use it in GitHub Desktop.
Frontend Magento2.x useful code snippets

Store Manager


Get Current store Id

\Magento\Store\Model\StoreManagerInterface $storeManage

$this->storeManager = $storeManager;

Store Id

$id = $this->storeManager->getStore()->getId();

Base URL

$baseUrl = $this->storeManager->getStore()->getBaseUrl();

NOTE: Use the constants in \Magento\Framework\UrlInterface, as parameters (UrlInterface::URL_TYPE_LINK) instead of 'link' strings.

Constance in Magento\Framework\UrlInterface

const URL_TYPE_LINK = 'link';
const URL_TYPE_DIRECT_LINK = 'direct_link';
const URL_TYPE_WEB = 'web';
const URL_TYPE_MEDIA = 'media';
const URL_TYPE_STATIC = 'static';
const URL_TYPE_JS = 'js';

More details:

NOTE: To Inject the UrlInterface within a _controller- that is extending: Magento\Framework\App\Action\Action using the dependency injection

/**
 * Inject via DI
 *
 * @param Context $context
 * @param UrlInterface $urlBuilder
 */
public function __construct(
    Context $context,
    UrlInterface $urlBuilder
) {
    parent::__construct($context);
    $this->urlBuilder = $urlBuilder;
}

Base currency code

$baseCurrency = $this->storeManager->getStore()->getBaseCurrencyCode();

Current currency code

$currentCurrency = $this->storeManager->getStore()->getCurrentCurrencyCode();

Base media directory path

$baseMediaDir = $this->storeManager->getStore()->getBaseMediaDir();

Base static directory path

$baseStaticDir = $this->storeManager->getStore()->getBaseStaticDir();

Cart


Magento\Checkout\Model\Cart $cart

$this->cart = $cart;

Total items in cart

$cartCount = $this->cart->getItemsCount();

Quote data

$cartQuote= $this->cart->getQuote()->getData();
\Zend_Debug::dump($cartCount);

Additional Quote data

echo $cartQuote['base_grand_total'];

Items in cart via session

Magento\Checkout\Model\Session $session

ex:

$this->session  =  $session; 
foreach ($this->session->getQuote()->getAllItems() as $item) {
    echo $item->getName();
}

Clear quote

$this->session ->clearQuote();

Catalog


\Magento\Framework\Registry $registry

$this->registry = $registry;

Current category

$category = $this->registry->registry('current_category');

Current Category Id

$cid = $this->registry->registry('current_category')->getId();

Current Category level

$level = $this->registry->registry('current_category')->getLevel();

Current product

$pid = $this->registry->registry('current_product');

Related products for PDP

Crosssell

$products = [];
foreach ($this->registry->registry('current_product')->getCrossSellProducts() as $product) {
    $products[$product->getId()] = ['position' => $product->getPosition()];
}
\Zend_debug::dump($products);

Related

$products = [];
foreach ($this->registry->registry('current_product')->getRelatedProducts() as $product) {
    $products[$product->getId()] = ['position' => $product->getPosition()];
}
\Zend_debug::dump($products);

Upsell

$products = [];
foreach ($this->registry->registry('current_product')->getUpSellProducts() as $product) {
    $products[$product->getId()] = ['position' => $product->getPosition()];
}
\Zend_debug::dump($products);

Current product from registry

if ($this->registry->registry('current_product')) {
    $product = $this->registry->registry('current_product');
} else {
    throw new \LogicException('Product is not defined');
}

CMS


\Magento\Framework\Registry $registry

$this->registry = $registry;

Current CMS page

$page = $this->registry->registry('cms_page');

Current CMS page Id:

$cmsId = $this->registry->registry('cms_page')->getId();

CMS page exist check

if ($this->registry->registry('cms_page')->getId()) {
    return $this->registry>registry('cms_page')->getTitle();
} else {
    return __('New Page');
}

View


Within any Block that extends \Magento\Framework\View\Element\Template,

Get assets elements URL from extensions in current current theme

$loader = $this->getViewFileUrl("ibnab_lazy::images/logo.svg");

Get from assets of current theme

$js = $this->getViewFileUrl("js/yetanotherdamnJSlib.js");

Layout & Blocks


Add a block dynamically

\Magento\Framework\View\LayoutFactory $layoutFactory
$this->_layoutFactory->createBlock('\Vendor\Module\Block\Foo', 'custom.block.foo.bar', ['data' => ['title' => "Bar"]]);`

Output of above block creation

<block class="Vendor\Module\Block\Foo" name="custom.block.foo.bar">
    <arguments>
        <argument translate="true" name="title" xsi:type="string">Bar</argument>
    </arguments>
</block>

Data structure injection

Magento\Framework\View\Layout\Data\Structure

Using the Layout\Factory from the dynamic block creation, use the method

setChild($parentName, $elementName, $alias) ex: $this->structure->setAsChild('custom.block', 'product.info.details') ;

Which will allow for calling of a child of the parent inside of a .phtml file, foo.phtml for example.

Other methods to call from Layout\Factory

  • \Zend_Debug::dump(getBlock($name));
  • \Zend_Debug::dump(getXml());
  • addContainer($name, $label, array $options = [], $parent = '', $alias = '');

Layout Data Structure registers ALL mappings of child elements of parent

Including the type of element, block, or container, and class layout.

For example to determine IF an element is a container or block:

Type of element

\Zend_Debug::dump($this->structure->isContainer($name));

Is a Block

\Zend_Debug::dump($this->structure->isBlock($name))";


Frontend Magento2.x useful code snippets:

Credit

Original sauce, Ibnab

With minor changes & additions of my own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment