Magento 2 some quick tips and code

Get value of any custom Attribute from customer or product

Sometime we face issue in fetching the custom attribute data from entities, thus to get that we have to join them as shown in below example:-
I want to fetch ‘code’ attribute data, which is a customer attribute. Then I have added a join to collection and specify the type of join we will be using

->addAttributeToSelect('code', 'left')

Print the collection query

Most of the time we need to print collection query so that we can review what exactly is going on behind the scene, thus we will be using below code to do that:-


Load a model using a different attribute such as sku

It is the most useful code, there are scenarios when we want to load module by using attribute other than id then we can simply use following code:-

$model->load(‘MAT-01’, ‘sku’);
// 1st parameter is the value and 2nd is the attribute code

Logging in magento2

Add a dependency injection of Logger Interface (\Psr\Log\LoggerInterface $logger) and then use below code:-

$this->_logger->emergency('some text or variable'); // when System is unusable
$this->_logger->alert('some text or variable'); // when Action must be taken immediately 
$this->_logger->critical('some text or variable'); // Critical conditions
$this->_logger->error('some text or variable'); //Runtime errors that do not require immediate action but should typically be logged and monitored.
$this->_logger->warning('some text or variable'); // Exceptional occurrences that are not errors
$this->_logger->notice('some text or variable'); // Normal but significant events
$this->_logger->info('some text or variable'); // Interesting events
$this->_logger->debug('some text or variable'); // Detailed debug information

Get collection of various entities

Get Customer Collection
Get Product Collection
Get Order Collection
Get Order payment Collection

Leave a Comment.