Magento 2 : Listing component amount formatting
Formatting amount column with currency symbol
The prices column can be be formatted to two decimal and currency symbol
Following example shows how to add formatting for a amount column.
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$currencyCode = null;
if (!$currencyCode...
Magento 2 : Listing component
Adding Button in listing component as a column
Magento2 provides action columns as selection but sometime we need a button to execute action as per design.
Following example shows how to trigger the existing button event in column button.
/**
* @param array $dataSource
*
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$name = $this->getData('name')...
Magento2 : Admin Module Part 3
This section contains the edit UI components and layout xml files
Stesps :
- Form ui components
create a file kpsaddress_index_lising.xml for grid under ui_component
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">kpsaddressindex_lis...
Magento 2: Create new customer attribute
How to create a new custom attribute to Customer
This article explain the custom customer attribute creation and showing that in account creation and account edit
Magento Customer module is developed with EAV attributes
if a attribute is created by admin in back-end, the it is a system attribute but if it is created with script then it is custom attribute.
Following example shows that creating new dropdown attribute for customer.
Steps:
- Create a DataPatch class
<?php
/**
* CreateAgeGroupAttribute
*
* @copyright C...
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 : API with GET and POST
Magento 2 API are used to fetch the data and create or update data in magento.
Following is the example of creating custom api for GET and POST
In Magento 2, a module is developed with service contract design pattern, the RepositoryInterface is used for
API GET and POST to get the records and save the record respectively.
Refer the webapi.xml in the etc folder of CMS module
However, the custom API can be implemented by customizing the RepositoryInterface or creating new Interface
The new interface should be created with '@api' anotat...
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
- Add additional attributes to EAV table
- Create extension attributes to link with models to save additional attributes values in databases
- Create fieldset.xml file to copy the additional attributes value to order table
- 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...