:::: MENU ::::
Posts tagged with: module

Magento 2 get product collection

Today we talk about Magento 2 get product collection. First we need to familiar with model collection structure of magento 2. Magento 2 use the collection class for get all record from database table. SO let start with coding. We are using the Factory method here.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      return   $this->_productCollectionFactory->create()->addAttributeToSelect('*');
     
     }

To Fetch Data in phtml file

$productCollection = $block->getProductCollection();

foreach ($productCollection as $product) {

   
        echo $product->getName().'<br />';

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


Magento 2 custom image resize

Today we talk about how to resize image in custom module. So let start talk about it with some background classes that are use to resize the image. In framework we use classes of Filesystem and Image\AdapterFactory. So here we go First we create the method resize in your block or you can create method in helper. In my example i am creating in my block.

   protected $_filesystem ;
   protected $_imageFactory;
   public function __construct(            
        \Magento\Framework\Filesystem $filesystem,        
        \Magento\Framework\Image\AdapterFactory $imageFactory        
        ) {        
        $this->_filesystem = $filesystem;              
        $this->_imageFactory = $imageFactory;        
        }

    // pass image Name, width and height
    public function resize($image, $width = null, $height = null)
    {
        $absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('helloworld/images/').$image; //complete path of image

        $imageResized = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$image;        
        //create image factory...
        $imageResize = $this->_imageFactory->create();        
        $imageResize->open($absolutePath);
        $imageResize->constrainOnly(TRUE);        
        $imageResize->keepTransparency(TRUE);        
        $imageResize->keepFrame(FALSE);        
        $imageResize->keepAspectRatio(TRUE);        
        $imageResize->resize($width,$height);  
        //destination folder                
        $destination = $imageResized ;    
        //save image      
        $imageResize->save($destination);        

        $resizedURL = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;
        return $resizedURL;
     }

Now we call our block method in our phtml.

$block->resize('test.jpg',500,400);
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 call static block

Today we learn about how to call static block from phtm fiile,cms page and layout (xml) file. First you have to create a static block from admin panel, go to menu Content , choose Blocks and Click Add New Block button from top right. Every static block have identifier that are unique. You can call static block by identifier. For example our identifier is QaisarSattiTest.Now we use this identifier in phtml file, layout file and cam page.

Phtml:

echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId(QaisarSattiTest)->toHtml();

Layout (xml):

<block class="Magento\Cms\Block\Block" name="footersocial" before="-">                     
      <arguments>
            <argument name="block_id" xsi:type="string">QaisarSattiTest</arguments>
      </arguments>
 </block>

CMS Page:

{{block  id="QaisarSattiTest"}}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


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 overriding rewriting model

Today we talk about Magento 2 overriding rewriting model. 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 Magento 2 overriding rewriting model. In start we are overriding core Product model. We are jut checking our rewriting model is working or not. You can modify the model 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 Model

Magento 2 Models play an even bigger role, as they typically contain the “Business Logic” that’s often relegated to the Controller or Helper methods in other PHP MVC frameworks. Now we start to overriding or rewriting core Product model. The model we are overriding is Product Model.
Step 1.

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

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

Step 2
The step2 to overriding or rewriting Magento2 model is to create a Product.php helper file in the following directory QaisarSatti/HelloWorld/Model/Rewrite/Catalog

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

namespace QaisarSatti\HelloWorld\Model\Rewrite\Catalog;
class Product extends \Magento\Catalog\Model\Product
{
public function __construct()
{
echo "Overrding/ Rewrite Working"; die();
}
}

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

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


Magento 2 get latest order collection

Today we will talk about Magento 2 get latest order collection. We will learn how to get latest order collection. You can simply add the setOrder entity_id to DESC or use created_at to DESC to your order collection. If you want to add limit simply add setpagesize

setPageSize(yournumberhere);

protected $_orderFactory;
public function __construct(

\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory,

)
{

$this->_orderFactory = $orderFactory;

}
public function getLatestOrders() {
$orderCollection =$this->_orderFactory->create()->addFieldToSelect(array('*')); $orderCollection->setOrder('entity_id','DESC');
return $orderCollection;
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Pages:1234