:::: MENU ::::

Use jquery magento 2

In this tutorial we will discuss Use jquery magento 2 .i.e how to use jquery in magento 2. with following example you can use jQuery in phtml file.And in this tutorial i will try to explain it briefly and also make it convenient.

Suppose you have created a Magento theme where you need to include jQuery.Usually there comes a conflict that with jquery, JavaScript functions does not work properly.In this tutorial we will learn how to use the Magento 2 built in jQuery library on a custom theme.

Since jquery is already added in magento 2.But if u want to use in custom themes, you will have to do it differently.

If you are adding your custom js library other than jQuery then you need to include the js code inside require function like:

require(['jquery', 'jquery/ui'], function($){
     //your js code here  
 });

For example:
Inside the require function, you can directly access jQuery functionality in place by using either jQuery or its short form alias, the dollar $ sign. For example:

require(['jquery', 'jquery/ui'], function($){
  jQuery(document).ready( function() {
    alert("Page loaded.");
  });
});

Have a look at the example with $ alias:

require(['jquery', 'jquery/ui'], function($){
  $(document).ready( function() {
    alert("Page loaded.");
  });
});

Similarly we can use jquery or call widget of magento from js file like:

define([
  'jquery',
  'jquery/ui',
  'mage/<widget.name>' found in /lib/web/mage dir
], function($){

$.widget('<your_namespace>.<your_widget_name>', $.mage.<widget.name>, {  CODE HERE... });

return $.<your_namespace>.<your_widget_name>;
});

Furthermore if you get an error, it’s possible that it’s because of duplication of jquery.So check it and remove jquery source first, if you are getting error in page .xml file in layout folder.


then define your jQuery like:

<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
 define jquery and print message in console
<script type="text/javascript">// < ![CDATA[
        $.noConflict();
        jQuery(document).ready(function(){
       console.log('hello this is dmeo ');

 });// ]]>
</script>

That’s it from this tutorial. I hope it serves the purpose.Furthermore please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: January 1, 2019


Install magento 2 command line interface (CLI)

This tutorial is about Install magento 2 command line interface (cli). Often i have faced little bit of trouble while installing magento or upgrading to a newer version. Also many people complain and ask about to how to install magento via command line.So here, we will discuss particularly about magento 2 version on any system. It is quite a simple process.We will discuss one or two methods here.So moving forward, lets have a look.

So it can be done using a command which is as follows:

php bin/magento setup:install --backend-frontname="admin" --key="admin" --session-save="files"
 --db-host="localhost" --db-name="magento2" --db-user="root" --db-password="root"
--base-url="http://127.0.0.1/magento2/" --base-url-secure="https://127.0.0.1/magento2/"
 --admin-user="admin" --admin-password="admin123" --admin-email="[email protected]"
--admin-firstname="Qaisar" --admin-lastname="Satti" --use-rewrites=1

If you want to add extra setting in installation you can add language currency time zone and etc with adding following parameters.

--language=en_US
--currency=USD --timezone=America/Chicago

That’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave what you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: January 1, 2019


Magento 2 Add Custom field at Product Form

This tutorial is about Magento 2 Add a Custom field at Product Edit Page method.Very often many developers face trouble and ask many questions about how to add a custom field/fieldset at product edit page in the Backend of Magento 2. This is a very important demand when you want to use extra information on your page which Magento 2 doesn’t include by default.Moving forward, this article would be the piece of writing you should definitely read.

I think i should break it in steps because that would be easy to understand.

Lets start with the step 1.

Create file etc\adminhtml\di.xml.This file will declare the module’s UI provider to Magento system.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
        <arguments>
            <argument name="modifiers" xsi:type="array">
                <item name="customTab" xsi:type="array">
                    <item name="class" xsi:type="string">
            QaisarSatti\HelloWorld\Ui\DataProvider\Product\Form\Modifier\ExtraField
            </item>
                    <item name="sortOrder" xsi:type="number">70</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

Step 2: Create

Ui\DataProvider\Product\Form\Modifier\NewField.php

.This class will create field and fieldset for you. Paste the below code in the created file

<?php
namespace QaisarSatti\HelloWorld\Ui\DataProvider\Product\Form\Modifier;
use Magento\Catalog\Model\Locator\LocatorInterface;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Ui\Component\Form\Fieldset;
use Magento\Ui\Component\Form\Field;
use Magento\Ui\Component\Form\Element\Select;
use Magento\Ui\Component\Form\Element\DataType\Text;
class ExtraField extends AbstractModifier
{
    private $locator;
    public function __construct(
        LocatorInterface $locator
    ) {
        $this->locator = $locator;
    }
    public function modifyData(array $data)
    {
        return $data;
    }
    public function modifyMeta(array $meta)
    {
        return $this->meta;
    }
}

Furthermore modifyMeta() – creating field, fieldset.

modifyData() – adding data when product edit page is loaded.

locator – getting product’s information by using $this->locator->getProduct().

For example, we create 1 fieldset and 1 field select yes/no, the content of modifyMeta will be as folllows:

 public function modifyMeta(array $meta)
    {
        $meta = array_replace_recursive(
            $meta,
            [
                'custom_fieldset' => [
                    'arguments' => [
                        'data' => [
                            'config' => [
                                'label' => __(Custom Fieldset'),
                                '
componentType' => Fieldset::NAME,
                                '
dataScope' => 'data.product.custom_fieldset',
                                '
collapsible' => true,
                                '
sortOrder' => 5,
                            ],
                        ],
                    ],
                    '
children' => [
'
custom_field' => $this->getCustomField()
],
                ]
            ]
        );
        return $meta;
    }

Furthermore as we can see, 1 fieldset in product page edit with label “Custom Fieldset”, the fields in this fieldset will be listed in ‘children’ item as an array. We only need to add 1 field with id custom_field through a function getCustomfield().

 public function getCustomField()
    {
        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'label' => __('Custom Field'),
                        'componentType' => Field::NAME,
                        'formElement' => Select::NAME,
                        'dataScope' => 'enabled',
                        'dataType' => Text::NAME,
                        'sortOrder' => 10,
                        'options' => [
                            ['value' => '0', 'label' => __('No')],
                            ['value' => '1', 'label' => __('Yes')]
                        ],
                    ],
                ],
            ],
        ];
    }

Similarly, we can add the other fields such as text, checkbox, file upload, so on.

Furthermore, If you want to create Custom Text Field, please add the following code:

public function getCustomField()

{

     return [

         'arguments' => [

             'data' => [

                 'config' => [

                     'label' => __('Custom Field'),

                     'componentType' => Field::NAME,

                     'formElement' => \Magento\Ui\Component\Form\Element\Input::NAME,

                     'dataScope' => 'enabled',

                     'dataType' => Text::NAME,

                     'sortOrder' => 10,

                 ],

             ],

         ],

     ];

}

Furthermore to assign value to the newly created field, just insert the code as below

public function modifyData(array $data)

{

     $data = array_replace_recursive(

         $data,

         [

             $productId => [

                 'product' => [

                     'enabled' => 'your_value'

                 ]

             ]

         ]

     );

     return $data;
}

In a nutshell, with the Custom field/fieldset you can put extra product’s information as your desire and I hope that this tutorial will help you understand clearly about custom field/fieldset at Product edit page in Backend of Magento 2.

Similarly here i will just give you a glimpse of how to add the custom field inside the advance inventory is to declare Ui Component, I will keep it short to make it fast and easy:

In the\\view\adminhtml\ui_component\product_form.xml please add:

<?xml version="1.0" encoding="UTF-8"?>

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <modal name="advanced_inventory_modal">
        <fieldset name="stock_data">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Stock Configuration</item>
                    <item name="dataScope" xsi:type="string"/>
                    <item name="sortOrder" xsi:type="number">100</item>
                    <item name="collapsible" xsi:type="boolean">false</item>
                </item>
            </argument>
            <field name="custom_toggle">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="sortOrder" xsi:type="number">3000</item>
                        <item name="dataType" xsi:type="string">boolean</item>
                        <item name="formElement" xsi:type="string">checkbox</item>
                        <item name="source" xsi:type="string">category</item>
                        <item name="prefer" xsi:type="string">toggle</item>
                        <item name="label" xsi:type="string" translate="true">Custom Label</item>
                        <item name="notice" xsi:type="string">Custom description.</item>
                        <item name="valueMap" xsi:type="array">
                            <item name="true" xsi:type="string">1</item>
                            <item name="false" xsi:type="string">0</item>
                        </item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">false</item>
                        </item>
                        <item name="default" xsi:type="string">0</item>
                    </item>
                </argument>
            </field>
        </fieldset>
    </modal>
</form>

So, that’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 27, 2018


Magento 2 Color Picker in system configuration

This tutorial is about addingColor Picker in Magento 2 admin configuration. In this article I will show how to add jquery color picker in Magento 2 system configuration. You can use following step to use this jquery color picker on frontend too. Magento 2 have default lib/web/jquery/colorpicker/js/colorpicker library so you don’t have to add any external library for that. Below are the steps of how to do it:

Lets start with the Image to demonstrate you what it looks like:

Magento 2 color picker

Magento 2 color picker

Here my Module Namespace is QaisarSatti.
And my module name is: HelloWorld

Lets have have a look at different steps below:

1. Create system.xml at app/code/QaisarSatti/HelloWorld/etc/adminhtml/system.xml
All admin config options for your module will go in this file. For color picker we will create a text field as below. Just for your information i have not added complete code here for sake of readability.

    <field id="color_background" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
         <label>Background Color</label>
         <frontend_model>QaisarSatti\HelloWorld\Block\ColorPicker</frontend_model> <!-- block for adding color picker on text box -->
     </field>

2. Create the QaisarSatti\HelloWorld\Block\ColorPicker.php
This code will enable color picker options with the text box.

<?php

namespace QaisarSatti\HelloWorld\Block;

class Color extends \Magento\Config\Block\System\Config\Form\Field {

   
    public function __construct(
    \Magento\Backend\Block\Template\Context $context, array $data = []
    ) {
        parent::__construct($context, $data);
    }

    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) {
        $html = $element->getElementHtml();
        $value = $element->getData('value');

        $html .= '<script type="text/javascript">
            require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) {
                $(document).ready(function () {
                    var $currentelement = $("#'
. $element->getHtmlId() . '");
                    $currentelement.css("backgroundColor", "'
. $value .'");  //adding already selected value

                    // Attach the color picker
                    $currentelement.ColorPicker({
                        color: "'
. $value .'",
                        onChange: function (hsb, hex, rgb) {
                            $el.css("backgroundColor", "#" + hex).val("#" + hex);
                        }
                    });
                });
            });
            </script>'
;
        return $html;
    }

}

Now
3. Add the color picker JavaScript library.
Now finally we need to add color picker JavaScript library to admin config pages. Magento 2 by default is shipped with Color picker jQuery plugin. This plugin is present in lib/web/jquery/colorpicker/ folder.
Create the app/code/QaisarSatti/HelloWorld/view/adminhtml/layout/adminhtml_system_config_edit.xml. This layout file will be called on all admin configuration pages. We will add our color picker JavaScript and CSS to this layout.

<!-- File: app/code/QaisarSatti/HelloWorld/view/adminhtml/layout/adminhtml_system_config_edit.xml -->

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="jquery/colorpicker/css/colorpicker.css"/>
    </head>
</page>

Now clear the cache and refresh the page. You will see the color picker enabled in config option.

That’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 27, 2018


Get all module list in Magento 2

This tutorial is about Get all module list in Magento 2 .i.e how to get all module or extension list in magento 2. Also the status, whether it’s enable or disabled. I assume your question is,how to get it? And in this tutorial i will try to explain it briefly and also make it convenient.

There are few ways to achieve it. We will discuss few here.

Lets start with a method, in which we can get the desired result using CLI command.

Using CLI command

There is a CLI command

bin/magento module:status

which returns the list of enabled and disbaled modules. Check the below given path to know how it’s done.

\Magento\Setup\Console\Command\ModuleStatusCommand::execute

Basically

\Magento\Framework\Module\ModuleList::getNames

returns you a list of enabled modules. Similarly

\Magento\Framework\Module\FullModuleList::getNames

returns you a full list of all modules.Furthermore we will have to do an array_diff() to get the disabled modules.

Secondly we can take help from Magento’s core codebase.

Magento Corebase

Since we already discuss the command that lists all modules:

php bin/magento module:status

Let me share with you that magento uses

\Magento\Framework\Module\FullModuleList

class to get the list of enabled and disabled modules.

Based on Magento’s implementation, I have implemented my code in the following way:

<?php
namespace QaisarSatti\HelloWorld\Block;

class Modules extends \Parent\Class
{
    protected $fullModuleList;

    public function __construct(
        \Other\Dependenciy\Classes,
        \Magento\Framework\Module\FullModuleList $fullModuleList
    ) {

        $this->fullModuleList = $fullModuleList;
    }

    public function modulesList()
    {
        ...
        $allModules = $this->fullModuleList->getAll();
        ...
    }
}

I hope it is quite efficient and fulfill its use.

Furthermore there are another two ways to get this done.

Lets have a look at the them respectively.

1.

Following code will give the enabled and disabled modules list. I have commented the code to make it easy to understand what the code is doing.

protected $fullModuleList;
protected $moduleManager;

public function __construct(
    ...................
    \Magento\Framework\Module\FullModuleList $fullModuleList,
    \Magento\Framework\Module\Manager $moduleManager,
    ...................
) {

    $this->fullModuleList = $fullModuleList;
    $this->moduleManager = $moduleManager;
}

public function yourFunction()
{
    ...
    $allModules = $this->fullModuleList->getAll();
    $listOfModules = [];
    foreach ($allModules as $key => $value) {
        $listOfModules[] = $key;
    }
    foreach ($listOfModules as $key => $value) {
        if ($this->moduleManager->isEnabled($value)) {
            echo $value; //Enable Module List
        } else {
            echo $value; //Disable Module List
        }
    }
    ...
}
Similarly the second method is as follows.<strong>
2.</strong>

protected $fullModuleList;
protected $moduleList;

public function __construct(
    ...................
    \Magento\Framework\Module\FullModuleList $fullModuleList,
    \Magento\Framework\Module\ModuleList $moduleList,
    ...................
) {

    $this->fullModuleList = $fullModuleList;
    $this->moduleList = $moduleList;
}

public function yourFunction()
{
    ...
    $allModules = $this->fullModuleList->getNames(); //List of All Module Names
    $enabled_list = $this->moduleList->getNames(); //List of Enabled Module Names
    $disabled_list = array_diff($enabled_list, $allModules); //List of Disabled Module Names

That’s it from this tutorial. I hope it serves the purpose.
Since these are learning tutorials,please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: November 9, 2018


Magento 2 after save and before save method

This tutorial is about Magento 2 after save and before save method .i.e how to use after save and before save methods in magento 2.I assume you want to add after save and before save method of Magento 2 in your model.So, how can we do this?. This tutorial will tell us,how we can do that?

Magento is a flexible platform and it covers almost all the basic and necessary functionalities. Magento has its own _beforeSave and _afterSave functions. You can use them in your ResourceModel using below code.

Before Save

_beforeSave function called when you tried to update or insert data in database table with your model. Then _beforeSave function is called. You can implement you logic like validation, Post data change or any other functionality you want perform.

<?php
    namespace QaisarSatti\HelloWorld\Model\ResourceModel;
    class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb  {

        protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
        {
            // do your logic here

        }

 

    }

After Save

_afterSave function called when After update or insert data in database table with your model. Then _afterSave function is called. You can implement you logic like sending email, Add related data or any other functionality you want perform.

<?php
    namespace QaisarSatti\HelloWorld\Model\ResourceModel;
    class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb  {

       protected function _afterSave(\Magento\Framework\Model\AbstractModel $object)
        {  
          //do your logic here
        }

    }

That’s it from this tutorial. I hope it serves the purpose.
Since these are learning tutorials,please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: November 9, 2018


Magento 2 free payment extensions

This article is about Magento 2 free payment extensions . Many people often look for payment methods of magento and find it difficult to find a suitable method or extension.In this tutorial i will try to list available free magento 2 payment extensions.This tutorial just have information of free extensions that are available on magento marketplace or any other extension provider store.I will try to list few here with brief descriptions as well.

Below are the free magento payment method extensions.

Magento payment extensions

Magento provides its own payment methods.But here we will discuss free magento shipping extensions.Because these are available for free so anyone can use them.First,lets have a look at the default magento payment methods.

Default magento payment methods:

  • Saved CC
  • Check / Money Order
  • Zero Subtotal Checkout
  • Bank Transfer Payment
  • Cash On Delivery Payment
  • Purchase Order
  • Authorize.net Direct Post
  • Authorize.net

Above are the default payment methods provided by magento.You can use them by going to configuration settings and then modifying payment methods.

Now lets have a look at the free available magento 2 payment extensions.

WAVES Crypto Currency Payments

The blockchain is the technology that has been slowly but steadily taking root in multiple spheres of businesses. It triggered the emergence of cryptocurrencies that progressively find the way into eCommerce. WAVES is the decentralized blockchain platform that focuses on custom blockchain tokens operations. It has high usability and can boast of the wallets that are securely protected to ensure that their owners are the only ones to access the crypto payments.

Key features

  • Inexpensiveness
  • Speed
  • Security
  • Transparency
  • Irreversibility

Extension Link

Ingenico ePayments

Ingenico ePayments is the online and mobile commerce division of Ingenico Group. We connect merchants and consumers, enabling businesses everywhere to go further beyond today’s boundaries and creating the future of global commerce.

Key features

  • Origin verification based on the SHA verification
  • 1-step checkout for credit cards
  • PCI compliant template handling
  • Multiple/Partial captures/refunds
  • Accept payments by mail or telephone (MOTO)
  • Send reminder mail with link to payment page
  • Display fraud result in order
  • Improve fraud detection through device fingerprinting
  • Credit/Debit card split
  • Dynamically add payment methods
  • Advanced fraud detection support

Extension Link

Stripe Payments

Stripe is a global technology company that builds economic infrastructure for the internet. Businesses of every size—from startups to public companies—use our software to accept payments and manage their businesses. Millions of companies in 120+ countries use Stripe to start, run, and scale their businesses.

Key features

  • Accept all major debit and credit cards as well as local payment methods
  • Benefit from Stripe Elements, which helps your users input their payment information quickly and correctly at checkout
  • Achieve PCI-DSS compliance with Stripe Elements hosted input fields
  • Optimized for mobile and fast checkout with Apple Pay, Google Pay, and Payment Request API support
  • Better detect and prevent fraud with the help of Stripe Radar and optional 3D Secure
    Easily capture authorizations and process refunds from your Magento Backend

Extension Link

Internal Payment Method

This extension for Magento 2 allows you to have a specific payment method in your store’s backend for capturing offline payments. With this payment method enabled, you are able to create orders in your store’s backend for your customers and they will not be visible on the checkout page.

Key features

  • Only visible at the backend orders page
  • The store admin can use the method in a similar way as other payment methods in the backend
  • Custom payment name
  • The store admin can use the method in a similar way as other payment methods in the backend
  • It’s OpenSource

Extension Link

Mollie

Mollie allows you to accept payments and donations online and expand your customer base internationally with support for all major payment methods through a single integration. No need to spend weeks on paperwork or security compliance procedures.

Key features

  • Online within minutes
  • A single solution
  • Transparent pricing
  • Serious security
  • Streamlined checkout
  • Easy refunds
  • Personal Dashboard

Extension Link

Coin Payments

oinPayments extension integrates your Magento 2 store with CoinPayments – a popular online platform that allows accepting, storing, converting, and withdrawing altcoins. At the moment, it supports 70+ cryptocurrencies and provides a unique $tag for accepting payments.

Key features

  • Magento 2 cryptocurrency trading: accept Bitcoin, Ethereum, and other altcoins as payment for products and services you sell
  • Use Magento 2 cryptocurrency wallets to store the altcoins
  • Magento 2 Ethereum wallet
  • Magento 2 Bitcoin wallet
  • Various Magento 2 altcoin wallets
  • Magento 2 Cryptocurrency PayPal integration: send payments to PayPal without any fees
  • Transparent transaction history: view separate logs for deposits, transfers, withdrawals, and conversions

Extension Link

Similarly there are many other extensions available. I tried to list a few. I hope this tutorial help you in any way.

Please feel free to drop any suggestions or queries in comments section. It will be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: November 9, 2018


Pages:1234567...19