Magento 2 : Debug cli commands

How to debug cli command in magento 2

Steps:

1) Export the key (if you are using docker, do it in container)

export XDEBUG_CONFIG='PHPSTORM'

2) Start the phpstorm Bug Debug

3) Execute the cli command

Docker Compose : Add New Container in existing docker compose

How to add a new container in a existing docker-compose file.

Steps:
The existing docker-compose file

version: '3.3'

networks:
  pwa_net:
    ipam:
      driver: default
      config:
      - subnet: 60.0.0.0/24
        gateway: 60.0.0.1
        
services:
        
  mysql-cont:
    image: mysql:8.0      
    container_name: springboot-mysql-cont
   
    networks:
      pwa_net:
        ipv4_address: 60.0.0.11
       
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: bookstore
      MYSQL_USER: bookstore
      MYS...

Magento 2 Tips: main.WARNING: Session size of 257209 exceeded allowed session max size of 256000.

This can be fixed by excuting folloing configuration.

./bin/magento config:set system/security/max_session_size_admin 512000
./bin/magento config:set system/security/max_session_size_storefront 512000

Magento 2 : Admin Grid

How to add di.xml configuration for simplet grid.

<!-- City listing definitions -->

    <virtualType name="Kemana\Directory\Model\ResourceModel\City\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
        <arguments>
            <argument name="mainTable" xsi:type="string">kemana_directory_city</argument>
            <argument name="resourceModel" xsi:type="string">Kemana\Directory\Model\ResourceModel\City</argument>
        </arguments>
    </virtualType>

    <type name="Magento\Framewor...

Magento 2: Virtual Class

Virtual Classes

The Virtual classes are not created physically with all features but it will be created by dependency injection file in magento 2.

Developers define these classes in di.xml when they want to use the existing classes with argument replacement to create additonal functionality without chaning the original class.

<virtualType name="MilestoneRepositoryExtended" type="Vasan\Training\Model\MilestoneRepository">
        <arguments>
            <argument name="milestoneManagement" xsi:type="object">Vasan\Training\Model\M...

Magento 2 : Create cron with config schedule

Step 1:

Create system.xml file with configuration field.

<group id="cron" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1"
                   showInStore="1">
                <label>MSD Cron</label>
                <field id="schedule" translate="Schedule" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Schedule</label>
                </field>
            </group>

Step 2 :

Create crontab.xml content

<group id="...

Magento 2 Tips : Date Format

use Magento\Framework\Intl\DateTimeFactory;
=====================================
$endDate = $this->dateTimeFactory
            ->create($milestone->getData('end_date'), new \DateTimeZone('UTC'))->format('d/m/Y');
  ========================================          
            
 $collection = $this->collectionFactory->create();
        $gracePeriod = (int)$this->scopeConfig
            ->getValue(self::XML_PATH_GRACE_PERIOD, ScopeInterface::SCOPE_STORE, null);
        $interval = 'P' . $gracePeriod . 'D';
        $date = $this->dateTim...

Magento 2: API Functional Testing

The API funcational testing can be implemented using following steps

First Step : Develop your API

Second Step : Write the API Test class

Eg:

<?php
/**
 * OrganisationRepositoryTest
 *
 * @copyright Copyright © 2023 Vasan. All rights reserved.
 * @author    psureshvasan@yahoo.com
 */

namespace Vasan\Organisation\Test\Api;


use Magento\TestFramework\TestCase\WebapiAbstract;
use Vasan\Organisation\Model\ResourceModel\OrganisationRepository;
use Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\TestFramework\Helper\...

Magento 2 Oreder Creation other than the base currency

How to create order programmatically other than the basic currency?

Step 1) After create your Quote object set the currency code that you want in the order

$quote = $this->quoteFactory->create();
$store = $order->getStore();
$store->setCurrentCurrencyCode($order->getOrderCurrencyCode()); // Eg: AUD|GRB
$quote->setStore($store);

Step 2) Set again before add the product to Quote

$store-...

How to fix composer server sertificate issue

If you get following issue in composer package installation
"server certificate verification failed. CAfile: none CRLfile: none"
Then update certificate using follwing commands

sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates -y 
sudo update-ca-certificates

Magento 2 : Custom Sql

Custom Sqls

To insert records to tracking table, fetch the data from custom table as array

$tableName = $this->connection->getTableName(self::SHIPMENT_TABLE);
        $jointTableName = $this->connection->getTableName(self::TABLE);

        $sql = $this->connection->select()->from(
                ['ss' => $tableName],
                [
                    'parent_id' => 'ss.entity_id',
                    'order_id' => 'ss.order_id'
                ]
            )->joinLeft(
                ['kst' => $jointTableName],
            '...

Mysql : Tips

Fix for logging issue

ERROR 1419 (HY000) at line 410: You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)

login into the mysql container

docker exec -it wow-mysql-cont /bin/bash

cd /etc/mysql/

cp my.cnf mycnfbk

After the backup of my.cnf and execute following commant to add it in the end of the file

echo 'log_bin_trust_function_creators = 1' >> my.cnf

cleaning dump database

sed -i 's/DEFINER=[^*]*\*/\*/g'

Magento 2 Tips : System Configuration field dependent on multiple values

How to show a field dependent on another field multiple values

<depends>
                        <field id="vasan/general/enable">1</field>
                        <field id="vasan/email_dispatch/receiver" separator=",">2,3</field>
                    </depends>

Magento 2 Tips : Install external lib

How to install a excel lib to generate formatted excel file

Step 1) Go to the magento 2 root folder then execute following command

sudo -uwww-data composer require phpoffice/phpspreadsheet

Magento 2: GraphQl

How to create a Mutation with single input and output

The class file

class CreateSplitOrders implements ResolverInterface {


    /**
     * @param Field $field
     * @param $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|null $args
     * @return \Magento\Framework\GraphQl\Query\Resolver\Value|mixed
     * @throws GraphQlAuthorizationException
     * @throws GraphQlInputException
     */
    public function resolve (Field $field, $context, ResolveInfo $info, array $value = null, ar...

Magento 2: GraphQl

How to create a query with single input and output

Following graphql is defined schema.graphqls with Integer input and String output

type Query {
      testing(id: Int!): String @resolver(class: "Vasan\\TesterGraphQl\\Model\\Resolver\\Testing")
}

The Testing Resolver Class

class Testing implements ResolverInterface {


    /**
     * @param Field $field
     * @param \Magento\Framework\GraphQl\Query\Resolver\ContextInterface $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|nul...

Magento 2 : Form component

How to set a custom value to the field and make it disable

This requirement can be achieved using DataProvider class of the UI form component

/**
     * @inheritdoc
     */
    public function getMeta()
    {
        $meta = parent::getMeta();
        $meta['general']['children']['version']['arguments']['data']['config']['disabled'] = true;

        /** @var \Vasan\Bidding\Model\ResourceModel\Term\Collection $termCollection */
        $termCollection = $this->collectionFactory->create();
        $termCollection->addOrder('id', 'DE...

Magento 2 : Form component

Adding searchable drop-down

Simply following steps to add searchable drop-down ui component in a form

1. Add element in form xml

<field name="rateselection" component="Vasan_Bidding/js/form/components/rate-select" formElement="select">
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="filterOptions" xsi:type="boolean">true</item>
                            <item name="multiple" xsi:type="boolean">false</item>
 ...

Magento 2: Searchable drop-down

Searchable drop-down component with Jquery Plugin

Following example shows the steps to use Select2 Jquery Plugin in Magento 2 admin form.

Stesps :

1. Download the required files from Repository

https://github.com/select2/select2/tree/4.1.0-rc.0

2. Add the required files in magento 2 module

In view/adminhtml/web/js folder

Add the downloaded select2.js in above folder

In view/adminhtml/web/css folder

Add the select2.css file under above folder

In required-config.js

var config = {
    ...

Magento 2 : Form component

Custom time component

Magento2 time component does not pass the selected time when post the form to controller.
Following custom time component is used to capture the time.

In form xml

<field name="start_time" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">milestone</item>
                </item>
            </argument>
            <settings>
                <elementTmpl>Vasan_Bidding/form/el...

Magento 2 : Listing component

Date columns with date formatting

Following example shows how to use date component in listing

In xml

<column name="due_date" class="Magento\Ui\Component\Listing\Columns\Date">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Due Date</item>
                    <item name="timezone" xsi:type="string">false</item>
                    <item name="dataType" xsi:type="string">date</item>
                 ...

Magento 2 : Form component

Text box component with suffix

Magento use ui component with suffix in product form for weight.
Following example shows how to use the suffix for a text ui component.

In xml

<field name="duration" formElement="input" component="Vasan_Bidding/js/form/components/duration">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">milestone</item>
                </item>
            </argument>
            <settings>
           ...

Magento 2 : Form component

Text box component with currency symbol as prefix

In Product Form, Magento uses the text ui component with currency symbol as a prefix for price.
Following example shows how to get the prefix in text component

In form xml

<field name="final_total_text" formElement="input" sortOrder="120" component="Vasan_Bidding/js/form/components/price">
            <settings>
                <elementTmpl>Vasan_Bidding/form/element/currency_text</elementTmpl>
                <label translate="true">Total</label>
                <dataScope>amoun...

Magento 2 : Listing component Dataprovider

Adding dataprovider for listing component with filtering and sorting

Listing component default data provider get all the data from collection.
Sometime we need to do filer and sorting.
Following example shows how to do the filer and sorting of a listing component



class DataProvider extends \Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
{

    /**
     * @inheritdoc
     */
    public function getData()
    {
        $this->addFilter(
            $this->filterBuilder->setField('proposal_id')->setValue($thi...