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

$this->object_manager->create('Magento\Customer\Model\Customer')->getCollection()
->addAttributeToSelect('code', 'left')
->getData();

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:-

$collection->getSelect()->__toString();

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
$this->object_manager->create('Magento\Customer\Model\Customer')->getCollection();
Get Product Collection
$this->object_manager->create('Magento\Catalog\Model\Product')->getCollection()
Get Order Collection
$this->object_manager->create('Magento\Sales\Model\Order')
->getCollection()
Get Order payment Collection
$this->object_manager->create('Magento\Sales\Model\Order\Payment')
->getCollection()

Leave a Comment.