:::: MENU ::::
Posts tagged with: phtml

Magento 2 override phtml file in custom module

Today we talk about how to override the magento 2 phtml file in custom module. First thing is simple just create xml file default.xml in your module layout folder. Then call the referenceBlock name you want to override in your module. There are two possible way to do that.

First:

Using the layout file to override the phtml file. You must be aware of block name of phtml file. Now use below simple code to override.

<referenceBlock name="block-name">
    <action method="setTemplate">
        <argument name="template" xsi:type="string">'QaisarSatti_HelloWorld::path/to/my/file.phtml </argument>
    </action>
</referenceBlock>

Note
This solution requires finding all instances where the block is used and create as many xml files as handles in which it is used.

Second:

The block is used very often or you want to make sure each new usage will not require adding this kind of configuration you can do it using plugin.

Declare your plugin either in etc/di.xml or etc/frontend/di.xml

<type name="Other\Module\Block">
    <plugin name="very-unique-name" type="QaisarSatti\HelloWorld\Plugin\Block" />
</type>

And then create a class QaisarSatti\HelloWorld\Plugin\Block with content like

<?php
namespace QaisarSatti\HelloWorld\Plugin;

class Block
{
    public function beforeToHtml(\Other\Module\Block $block)
    {
        $block->setTemplate('QaisarSatti_HelloWorld::path/to/my/file.phtml');
    }
}

Note:
This way you enforce use of this template in each instance so you will be no longer available to set it different just for 1 usage in layout xml file (unless you will add some flag to the block and a logic to check it in the plugin).

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 overriding Rewriting block

Today we talk about Magento 2 overriding Rewriting block. In our daily coding routine we need to customization with core files. For that we need to overriding or rewrite the core classes because modify the core classes is not good practice. If you modify the code classes when you update the new version your code will be loss. So today we learn how to override core blocks. In start we are overriding core Product blocks. We are just checking our rewrite is working or not. You can modify the blocks as you want by following this tutorial. But first you need to know How to create module in Magneto 2.For any suggestions & question, please feel free to drop a comment.

Overriding or Rewrite Magento 2 Block

A Block is one of the first class elements in the structure of Magento layouts. Every page in Magento is decorated by the Layouts file and the content is filled up by the Blocks of the different modules.Now we start to overriding or rewriting core Product block. The model we are overriding is Product Listing block. Magento 2 use block for category product listing.

Step 1.

Create a di.xml file in a following directory QaisarSatti/HelloWorld/etc/

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Product\ListProduct" type="QaisarSatti\HelloWorld\Block\Rewrite\Product\ListProduct" />
</config>

Step 2
The step2 to overriding or rewriting Magento 2 block is to create a ListProduct.php block file in the following directory QaisarSatti/HelloWorld/Block/Rewrite/Product

<?php
/**
* Catalog Product Rewrite Block
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Block\Rewrite\Product;
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
{
public function __construct() {


echo "Block Rewrite Working"; die();
}
}

As following this code you can rewrite or override any Magento 2 block using the same method.

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 add pagination custom collection

Today we talk about Magento 2 add pagination custom collection. we’ll talk about how to get custom collection with magento 2 default pagination or use pager with custom collection.For any suggestions & question, please feel free to drop a comment.

First Step:

Get collection for pagination.

public function getNews() {
 //get values of current page
$page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
 //get values of current limit
$pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;
$newsCollection = $this->newscollectionFactory->create(); $newsCollection->addFieldToFilter('is_active',1); $newsCollection->setOrder('title','ASC'); $newsCollection->setPageSize($pageSize); $newsCollection->setCurPage($page);
return $newsCollection;
}

Second Step:
Now simply add the pagination to you collection

protected function _prepareLayout() {
parent::_prepareLayout();
$this->pageConfig->getTitle()->set(__('News'));
 if ($this->getNews()) {
$pager = $this->getLayout()->createBlock( 'Magento\Theme\Block\Html\Pager', 'qaisarsatti.news' )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection( $this->getNews() );
$this->setChild('pager', $pager);
$this->getNews()->load();
}
return $this;
}

Third Step:
Now create a function to get the child block of pager.

public function getPagerHtml() {
return $this->getChildHtml('pager');
 }

Fourth Step:
in your phtml file add this code then pagination will be showing with limits.

<?php if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>
<?php endif ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get controller module action and router

Today we talk about Magento 2 get controller module action and router.We’ll talk about how to get controller name, module name, action name and router name programmatically in Magento 2.For any suggestions & question, please feel free to drop a comment.

Controller name:
Controller is a class located in module Controller folder. Here is Controller file of module.

$this->getRequest()->getControllerName();

Module name:

$this->getRequest()->getModuleName();

Action name:
Action name is located in module Controller file. Here is Action Method controller.

$this->getRequest()->getActionName();

Router name:
Router are defined in module router.xml file. Here is Action Method controller.

$this->getRequest()->getRouteName();

Example:

If you test this code for home page it will give you following output.

Controller:index
Action:index
Route:cms
module:cms

You can use this code in both phtml and controller file.

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 create simple theme

Today we discuss how in Magento 2 create simple theme? Creating a simple theme or custom theme is consisting on four easy step in magento2. First you have to create your SpaceName in my case it is QaisarSatti. Create folder in app/design/frontend/QaisarSatti. Now add the theme name after app/design/frontend/QaisarSatti/theme.

First Step:

Create the composer.json file for theme.

app/design/frontend/QaisarSatti/theme/composer.json

{
"name": "magento/theme-frontend-blank",
"description": "My First Theme",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0",
"magento/theme-frontend-blank": "100.0.*",
"magento/framework": "100.0.*"
},
"type": "magento2-theme",
"version": "100.0.1",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"autoload": {
"files": [
"registration.php"
]
}
}

Second Step:

In this step we will register our theme.

app/design/frontend/QaisarSatti/theme/registration.php

<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/QaisarSatti/theme',
    __DIR__
);

Third Step:
Create the theme.xml file. Here you will define the parent theme for your theme so in my case the magento blank theme.

app/design/frontend/QaisarSatti/theme/theme.xml

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
     <title>My First Theme</title> <!-- your theme's name -->
     <parent>Magento/blank</parent> <!-- the parent theme, in case your theme inherits from an existing theme -->
     <media>
         <preview_image>media/preview.jpg</preview_image> <!-- the path to your theme's preview image -->
     </media>
 </theme>

Fourth Step:

Now add you theme preview image in media folder. This will be show in admin panel where theme are listed.

app/design/frontend/QaisarSatti/theme/media/preview.jpg

Here we create the new theme in magento 2. Now just simply run these command you register you theme in magento.

php bin/magento setup:upgrade

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 load product by id

Today we talk about how in Magento 2 load product by id. There are three way to get product load in magento 2. First Object Manager second factory Method and third one is Api Repository.

Factory Method:

Best practice method always use this method.

namespace QaisarSatti\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function getLoadProduct()
    {
        $product_id=7;
        return $this->_productloader->create()->load($product_id);
    }

}

Api Repository:

This was introduce in Magento 2.1 by magento.

    namespace QaisarSatti\Module\Block;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    class Product extends \Magento\Framework\View\Element\Template
     {
          protected $_productRepository;
       

          public function __construct(
         
            ProductRepositoryInterface $productRepository
          ) {
         

              $this->_productRepository = $productRepository;
          }
          public function getProduct()
          {
              $productId=7;
              return $product = $this->productRepository->getById($productId);
          }
      }

Object Manager:

No recommended method to use in magento2 but so magento use it so here it is just for knowledge.

$product_id=7;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
Author: Qaisar Satti
Category: Magento 2
Last Modified: September 5, 2018


Set meta tag Magento 2

This tutotrial is about how to set Meta tag in magento 2. Magento is a very useful ecommerce platform.Since every Magento project requires a certain level of modification. This may involve changing an existing functionality or adding a new one. In this tutorial we will learn about how to set Meta tag in magento 2.This includes Meta title,Meta Keyword and Meta description. And in this tutorial we will learn how to do it programmatically in Magento 2.

Lets come to our topic and see an example and code.Below are the two methods. Making changes in the block and controller will help to getthe desired results.
 

Block


$this->pageConfig->getTitle()->set(__('First Hello World Module'));
//setting the page title
$this->pageConfig->setDescription('test description'); // set meta description
$this->pageConfig->setKeywords('test keywords'); // set meta keyword

 

Controller

 

namespace QaisarSatti\HelloWorld\Controller\Index;

use Magento\Framework\View\Result\PageFactory;

class Index extends Action {

protected $_resultPage;

public function __construct(
PageFactory $resultPage) {
$this->_resultPage = $resultPage;
}
public function execute() {
$result= $this->_resultPage->create();
$result->getConfig()->getTitle()->set("Meta Title"); //setting the page
$result->getConfig()->setDescription("Description"); // set meta description
$result->getConfig()->setKeywords("Key Words"); // set meta keyword

return $result;
}

I hope this tutorial is easy to understand and serve its purpose.
For any suggestions & question, please feel free to drop a comment.

Author: Qaisar Satti
Category: Magento 2
Last Modified: September 30, 2018


Pages:1234