Magento 2 : Url rewrite issue

Regenerating Magento 2 Proudct url

If there is an issue in product url of a specific product, remove those products url in backend.

Maketing -> Url Rewrite (SEO section)

Then open the product in backend and save the product with selected websites and categories of the specific store view

If it is not resolved the issue, Open the product in backend and remove the one of the category assigned to the product and save the product and again add that category and save the product.

if you have issue in many products, do the following in...

magento 2: Docker compose file

Docker compose file for magento 2.4

version: '3.3'

networks:
  pwa_net:
    ipam:
      driver: default
      config:
      - subnet: 40.0.0.0/24
        gateway: 40.0.0.1
        
services:
  web-cont:
    image: registry.vasan.com/magento24_fpm74:1.0
    container_name: magentoent242-web-cont
    volumes:
      - /home/suresh/works/projects/magentoEnt242:/var/www/html   
   
    environment:
      SERVER_NAME: magentoent242.dev.local    
      USER_ID: 1000
   
    networks:
      pwa_net:
        ipv4_address: 40.0.0.10  
     ...

Magento 2 : Data cleaning and import

Following example shows how to clean customer and order records and import customer data from another database

## Following query to identify the name of the attribute and attribute id
select * from  live.eav_attribute where entity_type_id = 1 order by attribute_id;

## Following query to fetch the mobile number 


select * from  live.customer_entity_varchar where attribute_id = 543;

## Following query to create temp table with mobile number

CREATE TABLE  live.temp_customer_entity
select ce.*, cev.value as mobile_number from  live...

Magento 2: Custom Log

In magento 2, custom log file is important to verify the log for specific critical function implementation and debug the issues in the server level

Custom log file can be created by simply creating two virtual classes.

Virtual class definition in di.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * di
 *
 * @copyright Copyright © 2021 Vasan. All rights reserved.
 * @author    survasp@gmail.com
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Obje...

Magento 2 : Address additional attributes

In this example, you can learn how to add additional attributes for customer address

Steps

  1. Add additional attributes to EAV table
  2. Create extension attributes to link with models to save additional attributes values in databases
  3. Create fieldset.xml file to copy the additional attributes value to order table
  4. Ui component customization to show the data in admin

Add additional attributes to EAV table

In this example, district and sub_district attributes will be added in the EAV t...

Magento 2 : How to write a controller to download a file

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\App\Action\Action;
use Magento\Customer\Model\Session;


class DownloadPrescription extends Action
{
    /**
     * @var FileFactory 
     */
    protected $fileFactory;
    
    /**
     * @var DirectoryList 
     */
    protected $directory;

    /**
     * @var Session 
     */
    protected $session;

    

    /**
     * DownloadPrescription constructor.
     * @param...

Magento 2 : How to hide a image path in a page

Following example explains how to add encoded url for image

1) Create a function to get the path in block class

public function getEncodedPath()
    {
        $ext = pathinfo($this->getPath(), PATHINFO_EXTENSION);
        if ($ext) {
            $ext = strtolower($ext);
        }

        $imageUrl = $this->getBaseUrl() . $this->getPath();
        $imageData = base64_encode(file_get_contents($imageUrl));

        switch ($ext) {
            case "jpeg":
                return 'data: image/jpeg;base64,'.$imageData;
            cas...

How to add a column in magento grid joining other table example shipment grid

Following steps explain how to add additional column in shipment grid by joining tables

1) Add a plugin

<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <plugin name="antyra_extended_shipping_grid"
                type="Vasan\Shipping\Model\Plugin\AddDataToShipmentGrid"
                sortOrder="10"
                disabled="false"/>
    </type>

/**
     * @param \Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject
     * @param OrderGridCol...

Magento 2 : Admin Module Part 2

5.Create Model and Resource model

Address model class extends the AddressInterface and it contains the data object getters setter methods.

<?php
/**
 * Address
 *
 * @copyright Copyright © 2021 Vasan. All rights reserved.
 * @author    survasp@gmail.com
 */

namespace Vasan\KpsAddress\Model;


use Vasan\KpsAddress\Api\Data\AddressInterface;
use Magento\Framework\Model\AbstractModel;
use Vasan\KpsAddress\Model\ResourceModel\Address as ResourceModel;

class Address extends AbstractModel implem...

Magento 2 : Admin Module Part 1

1. Create required folders and files for a module

Vasan
--KpsAddress
  --Api
    --Data
      --AddressInterface.php
      --AddressSearchResultsInterface.php
    --AddressRepositoryInterface.php
  --Block
    --Adminhtml
      --Edit
        --DeleteButton.php
        --GenericButton.php
        --ResetButton.php
        --SaveAndContinueButton.php
        --SaveButton.php
  --Console
    --InstallAddress.php
  --Controller
    --Adminhtml
      --Index
        --Delete.php
    ...

Magento 2 : How to add a column in Order Grid and Order

Following steps explain how to add new column in order and grid tables

1) Add the columns in order, quote and grid tables using declarative schema

2) Add arguments to Magento\Sales\Model\ResourceModel\Order\Grid virtual class that already defined in Magento_Sales di.xml

<virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="channel" xsi:type="string">sales_order.channel</item>
            </argument>
        </a...

Magento 2 : Multi Store configuration

Sometime , we need to create multisite application using magento 2 framework.
Following example shows the nginix confgiration of multisite application with magento website or store

In this example contains three sites and each has different domain

upstream fastcgi_backend {
    server   unix:/run/php/php7.4-fpm.sock;
}

map $http_host $MAGE_RUN_CODE {
    default '';
    magento2lst.dev.bn.com ban;
    magento2lst.dev.jk.com jak;
    
}
server {
    listen 80;
    server_name magento2lst.dev.com  magento2lst.dev.bn.com magento2ls...

Magento 2 : City Auto complete

Edit the address edit.phtml to do the changes

<div class="field city required">
            <label class="label" for="city"><span><?= /* @noEscape */ $block->getAttributeData()->getFrontendLabel('city') ?></span></label>
            <div class="control">
                <input type="text"
                       name="city"
                       value="<?= $block->escapeHtmlAttr($block->getAddress()->getCity()) ?>"
                       title="<?= $block->escapeHtmlAttr(__('City')) ?>"
                       placeholder="<?= $block...

Magento 2 : Custom Email Sending

Email can be sent in magento customization with following implementation

First, The email template should be created in view section and registered in etc using email_template.xml

email_template.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
    
    <template id="vender_email_paymentlinkemail" label="Payment Link Email" file="paymentlinkemail.html" type="html" module="Vender_Prescription" area="frontend...

Mysql

Mysql Secure Installation in ubuntu 18.04

sudo apt install mysql-server

enter Y to install
2.

sudo mysql_secure_installation

to run automated securing script
3. Press N for VALIDATE PASSWORD plugin
4. Set root password
5. Remove anonymous users? Y
6. Disallow root login remotely? N
7. Remove test database and access to it? Y
8. Reload privilege tables now? Y
9.

sudo mysql

to enter MySQL CLI
10.

SELECT user,authentication_string,plugin,host FROM mysql.user;

to verify root user's auth method
11....

Magento 2 : Popup

Simple popup can be generated with magento 2 popup model

First, create a phtml to load the popup message and it should be added in footer section to load in every page

If you define the phtml in default.xml file then, simply you can call it as child component

<div class="note">
    <div class="popup-open" ></div>
</div>
<div id="popup" style="display: none;">
    <?php echo $this->getChildHtml('popup-content') ?>
</div>
<script type="text/x-magento-init">
{
   ".popup-open": {
       "Vender_Module/js/popup": {}
   }
}
</script>

...

Magento 2 Notes

1) Non Auto Increment Primary key

The $_isPkAutoIncrement should be assigned as false in resource model, when a primary key of a table is used as non auto increment.

protected $_isPkAutoIncrement = false;

2) Custom Cron Job

Following two files are mandatory to execute a process using cron

A class file and a crontab.xml file

class Notifier
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function execute()
    {
        $this-...

How to use Mailhog in magento 2 development with docker

Mailhog is a tool to test the you application mail outgoing.

Steps to use with docker

First, install mailhog sendmail tool in your php docker container

wget https://github.com/mailhog/mhsendmail/releases/download/v0.2.0/mhsendmail_linux_amd64
sudo chmod +x mhsendmail_linux_amd64
sudo mv mhsendmail_linux_amd64 /usr/local/bin/mhsendmail

Second, change your php.ini sendmail_path value as follows

sendmail_path = '/usr/local/bin/mhsendmail --smtp-addr="mailhog-cont:1025"'

Third, add mailhog in your docker compose f...

Magento 2 : Customer attribute creation

CustomerSetupFactory and Attribute SetFactory classes should be used to create the customer attribute using setup script

<?php


namespace ExamNotes\Chapter10\Setup;

use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\ResourceModel\Attribute;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

cla...

How to write a post-receive script for bit bucket

The post script is useful when execute or trigger any action after pushing the code in repository

Following example shows how to push the code to s3 bucket after pushing the code.

#!/bin/bash
set -x #echo on

tag_push_trigger()
{    
    masterTag=$(git for-each-ref | grep $newrev | grep refs/heads/master )
    
    if [[ -z "$masterTag" ]]; then
      echo " Tag is not created for master branch "       
    else
      tag_create_zipfile  
    fi
}


tag_create_zipfile()
{
    export AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxxxx
    export...

Magento 2 : How to use Javascript in Magento

Javascript in Magento 2

Magento 2 uses Require JS lib and Knockout JS lib to solve the page speed and manage the JS dependency.

As JS are loaded asynchronously in backend, it helps to increase the page speed.

The JS files can be found in following locations :

lib/web
view/area/web
theme/module/web
theme/web

Magento 2 uses requirejs-config.js in module view/area/ folder to map the JS file with alias.

Magento 2 declares JS using following ways :

data-mage-init
<script type="text/x-magento-init"> ...........

Magento 2 Tips : How to get client ip

The client ip can be retrieved using

getClientIp()

method in

Magento\Framework\HTTP\PhpEnvironment\Request

class. This is very useful , when do the ip restriction in maintenance page development.

Docker Tips

Here you can learn about the docker basic and its commands

  1. How to execute the docker run command

The docker run command is used to get the specific docker image from registry and start and run the container of the image.
For this example, the alpine docker image is used as it is more light weight linux image.

docker run alpine:3.4 uptime

Here the apline is a public image and it will be pulled from registry and created the container and started the container and ran the 'uptime' and exit....