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

Magento 2 available install schema columns type

Today we talk about Magento 2 available install schema columns type That we can use in install schema that is already mention in my post Magento 2 Create a install Schema. There are different type available in magneto 2. Type of column that you can is listed below with example.

Type boolean

TYPE_BOOLEAN = ‘boolean’;
Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
Example

addColumn(
            'post_id',
            Table::TYPE_BOOLEAN,
            null,
            [ 'identity' => false, 'nullable' => false, 'primary' => true ],
            'Post ID'
        )

Type smallint

TYPE_SMALLINT = ‘smallint’;
Example

addColumn(
            'post_id',
            Table::TYPE_SMALLINT,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type integer

TYPE_INTEGER = ‘integer’;
Example

addColumn(
            'post_id',
            Table::TYPE_INTEGER,
            null,
            ['nullable' => false],
            'Post ID'
        )

Type bigint

TYPE_BIGINT = ‘bigint’;
Example

addColumn(
            'post_id',
            Table::TYPE_BIGINT,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type float

TYPE_FLOAT = ‘float’;
Example

addColumn(
            'post_id',
            Table::TYPE_FLOAT,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type numeric

TYPE_NUMERIC = ‘numeric’;
Example

addColumn(
            'post_id',
            Table::TYPE_NUMERIC,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type decimal

TYPE_DECIMAL = ‘decimal’;
Example

addColumn(
            'post_id',
            Table::TYPE_DECIMAL,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type date

TYPE_DATE = ‘date’;
Example

addColumn(
            'data',
            Table::TYPE_DATE,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type timestamp

TYPE_TIMESTAMP = ‘timestamp’;
Example

->addColumn(
            'creation_time',
            Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
            'Creation Time'
        )

Type datetime

Capable to support date-time from 1970 + auto-triggers in some RDBMS
TYPE_DATETIME = ‘datetime’;
Example

addColumn(
            'data',
            Table::TYPE_DATETIME,
            null,
            [ 'nullable' => false ],
            'Post ID'
        )

Type text

Capable to support long date-time before 1970
TYPE_TEXT = ‘text’;
Example

addColumn(
            'data',
            Table::TYPE_TEXT,
            255,
            [ 'nullable' => false],
            'Post ID'
        )

Type blob

TYPE_BLOB = ‘blob’;
Example

addColumn(
            'data',
            Table::TYPE_BLOB ,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type varbinary

Used for back compatibility, when query param can’t use statement options
TYPE_VARBINARY = ‘varbinary’;
Example

addColumn(
            'data',
            Table::TYPE_VARBINARY,
            null,
            [ 'nullable' => false],
            'Post ID'
        )
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get single column values from collection

Today we learn about how to get single column values from collection. For this example we use the product collection to get names of product. You can get product collection by following the Magento 2 get product collection.

protected $_productCollectionFactory;

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

Note: You can use same method with any collection.

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


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


Pages:1234