Category Archives: Magento2 Faq

Magento 2 Core read write Query


Magento 2 Core read write Query– We sometimes need to run core queries in Magento 2 to perform some specific task. To run custom query we can use object manager or dependency injection. Here in this tutorial, we are going to cover the both method to run the raw query.


Magento 2 Core read write Query | Run Direct SQL Example

Magento 2 allows us to run the core query which can be used to read or write data. –

Magento 2 Core read write Query

Method 1

Import resource(\Magento\Framework\App\ResourceConnection) in class simply as below –

protected  _resource;
public function __construct(Context $context,
\Magento\Framework\App\ResourceConnection $resource)
  {
    $this->_resource = $resource;
    parent::__construct($context);

  }

Get resource connection-

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

Now run your custom query-

Read Query

Fetch All Result

You can select all data from table using custom query simply as below-

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION)
$orderTable = $connection->getTableName('sales_order');
$result1 = $connection->fetchAll('SELECT * FROM '.$orderTable.' WHERE entity_id='.$orderId);

Run raw Query– If you want to run the raw query you can run it simply as below-

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION)
$result1 = $connection->query('SELECT * from users where user_id = 100');

Write Query

You can insert/update/delete the data using core query simply as below-

Insert

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION)
 $connection->query('INSERT into users(1, 'test user', 'test@yopmail.com')');

Update

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION)
 $connection->query(' UPDATE users set name="Jhon" where id="10"');

Delete

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION)
 $connection->query(' DELETE from users where id="10"');

Method 2- Using Object Manager

Using Object Manager You can run custom query simply as below-

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$table = $resource->getTableName('users');
 
//Select Query Example
$result = $connection->fetchAll("Select * FROM " . $table); // returns array.
//Insert Query
$connection->query("Insert Into " . $table . " (name, email, phone) values ('Jhon','jhon@example.com','123123123')");
//Update Query
$sql = "Update " . $table . "Set email = 'abc@example.com' where id = 19";
$connection->query($sql);
//Delete Query Example
$connection->query("Delete FROM " . $table." Where id = 99");

On the same way you can perform read/write ie you can run direct sql query using any one method in Magento 2.

Magento 2 Join 3 Tables


Magento 2 Join 3 Tables collection –We can join more than two table collections in Magento 2 which will return data collectively from three tables using join. You can also add conditions to the collection as per your need. Here in this tutorial, we are going to explain how to join 3 tables in Magento 2.


Magento 2 Join 3 Tables Colleaction Example

Here is an example of 3 table joins-

Example:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$collection = $objectManager->get('Magento\Sales\Model\Order')->getCollection();
$collection->getSelect()
->join( array('order_item'=> 'sales_order_item'),
'order_item.order_id = main_table.entity_id', array('order_item.sku'))
->join( array('quote'=> 'quote'),
'quote.quote_id = main_table.quote_id', array('quote.grand_total')); 

Magento 2 Change Theme Settings


Magento 2 Change Theme Settings– In Magento2 theme related settings has been moved to Content-> Design -> Configuration -> Edit so you need to go to this path to change the theme.


Magento 2 Change Theme Settings Example

To change the theme in magento2 go to below settings and change the theme related options-

Magento 2 Change Theme Settings Example:

Content-> Design -> Configuration -> Edit

Magento 2 Display Category Products on Home Page


Magento 2 Display Category Products on Home Page It is very simple to display the Category products on home page in magento 2. You can display the products of any category on home page using category id.


Magento 2 Display Category Products on Home Page Example

Add the following code to your home page CMS to display the selected category products on home page.

Magento 2 Display Category Products on Home Page Example:

{{widget type="Magento\CatalogWidget\Block\Product\ProductsList"
         products_count="4" 
        template="product/widget/content/grid.phtml"
        conditions_encoded="a:2:[i:1;a:4:[s:4:`type`;    s:50:`Magento|CatalogWidget|Model|Rule|Condition|Combine`;s:10:`aggregator`;s:3:`all`;s:5:`value`;s:1:`1`;s:9:`new_child`;s:0:``;]s:4:`1--1`;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Product`;s:9:`attribute`;s:12:`category_ids`;s:8:`operator`;s:2:`==`;s:5:`
            value`;s:1:`your_category_id`;]]"}}

Where your_category_id is category id. In the above example pass the category id which you want to display on the home page.

Magento 2 Collection get First Item


Magento 2 Collection get First Item(Single row)– It is very simple to get the first item in Magento 2. Here in this tutorial we are going to explain how you can get the single(first item) from the collection .


Magento 2 Collection get First Item | Element | Limit 1 | Single Row Example

You can get the first item simply using the ->getFirstItem() on your collection-

Magento 2 Collection get First Item | Result | Example:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();   
$firstItem = $objectManager->create('Mypackage\MyModule\Model\MyData')
                    ->getCollection()
                    ->getFirstItem();

The above example will give you the first item from the collection. You can sort the collection to get the last item.

Magento 2 get product image


Magento 2 get product image url We often need to get the product images while working with the products. We can get the image, thumbnail and small image from the product object simply. Here in this tutorial we are going to explain how you can get the product images from product object in Magento 2.


Magento 2 get product image Small | Thumbnail Image | Url Example |

You can get the product images such as image, thumbnail, small_image simply as below-

Magento 2 get product image url Example:

$productId = 100;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId);
$image = $product->getData('image');
$thumbnail = $product->getData('thumbnail');
$smallImage = $product->getData('small_image');

Thus using the aobve method you can get the images selected for product.

Magento 2 Display Category Products on Home Page


Magento 2 Display Category Products on Home Page– Sometimes we need to display some specific category products on homepage. It is a little bit tricky to display the category products on Home Page. Here in this tutorial, we are going to explain how you can display the products from selected category on home page.


Magento 2 Display Category Products on Home Page Example

You can display the catgory products on Home page by using the following code-

Magento 2 Display Category Products on Home Page Example:

{{widget type="Magento\CatalogWidget\Block\Product\ProductsList"
        products_count="10" 
        template="product/widget/content/grid.phtml"
        conditions_encoded="a:2:[i:1;a:4:[s:4:`type`;    s:50:`Magento|CatalogWidget|Model|Rule|Condition|Combine`;s:10:`aggregator`;s:3:`all`;s:5:`value`;s:1:`1`;s:9:`new_child`;s:0:``;]s:4:`1--1`;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Product`;s:9:`attribute`;s:12:`category_ids`;s:8:`operator`;s:2:`==`;s:5:`
            value`;s:1:`14`;]]"}}

In the above example 14 is the category id for which we need to get the list of products.

So replace 14 by your category id while using the above code. We hope the above example will help you and save your time.

Turn On Error Messages In Magento 2


How to turn on Error Messages In Magento 2 – Error Reporting is very importtant for any framework, it helps us to track the errors during development. Here in this article we are going to explain how you can enable error messages in Magento 2.


Turn On Error Messages In Magento 2 | Enable Error Reporting

It is a little bit different to enable error reporting in magento.
.There are following methods to enables errors.

Method 1 : Set Developer Mode

To enable the error messages to show on frontend, backend you need to set the Developer Mode. Here is the following command to set the developer mode –

Magento 2 Enable Error Reporting | Set Developer Mode Example:

php bin/magento deploy:mode:set developer

Now you will be able to see the errors occurred.

Method 2: Using Traditional Method

Alternatively you can add the following lines of code to the index.php to enable the erros & warnings.

Enable Erros & Warning Using Index.php Example:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Magento 2 Modes

Primarily Magento 2 provides the following modes which can be used easily for various stages of a project. Let us look at the modes available-

  • Default Mode– When you install fresh magento 2 it sets the default mode it means error will not be displayed on front end but errors can be seen in Magento error log.
  • Developer Mode– If you enable the develpoer mode frontend errors will also be displayed.
  • Production Mode– If you set the production mode then the errors and warnings will not be generated.

Show Current Mode

If you want to see the current mode run the following command-

Magento 2 Show Current Mode CLI Example:

bin/magento deploy:mode:show

The above command shows the current mode instance.

Magento 2 Create Event Observer


Magento 2 Create Event Observer– Observers are great ways to extend the default functionality in Magento. Using Observers we can easily implement the custom changes required related to different-different functionalities. Here in this tutorial we are going to explain how you can create Event Observers in Magento 2.


Magento 2 Create Event Observer Example

Creating observer event in Magento 2 is totally different than the Magento 1. We need to create events.xml configuration file to create events-

Step 1 – Create events.xml

Go to etc folder and create events.xml and define the event obsever simply as below-

Magento 2 Create Event Observer Example:



	
		
	

Step 2 – Create Obsever

Now go to Observer folder and create folder named as Sales. Inside this sales folder create OrderPlaceAfter.php and add the code as below-

Magento 2 sales order place after Event Example:


Thus you can create any observer event in magento 2.

Download Sample Code

If you want to download the sample code you can download it from here - Magento 2 Observer Example Sample