:::: MENU ::::
Posts tagged with: M2

Magento 2 Update product attribute value

This article is about Magento 2 – Update product attribute value . Updating product attribute value can be tricky sometimes. In this tutorial i will try to explain it swiftly and in a simple way. There can be various conditions in this matter. Like if someone wants to update the attribute values one by one or as a whole. Here, we are looking t update only one attribute value.

We can set all the values into one object (also we can use set for each attribute) & using set method we can save the product attribute with the help of productRepository or product model.

Furthermore When we use this method, there is a chance to get delays while updating the values like it may take 40 to 50 sec approx for one product . In our case we want to update only one attribute value. To render entire collection & updating the value might will take some ms delay.
So to update only one attribute value, we can do so by using the following code.

Consider the example here.

$item->setWidth(10);

$item->save();

We can use “updateAttributes” method to update Specific Attribute for product instead of updating all the update.

Here we have to pass 3 parameters.

Ex: $productIds , $attrData, $storeId
$objectManager->get(‘Magento\Catalog\Model\Product\Action’)

->updateAttributes( [$item],[‘width’ => 10],  $YourStoreID );

Similarly

$this->action->updateAttributes([$productObj->getId()], [‘Yourattribute_code’ => ‘Yourvalue’], $StoreId);

I am also providing the path for reference, it may vary depending upon your settings.

Magento\Catalog\Model\Product\Action

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: January 11, 2019


Use js mixins magento 2

In this tutorial we will discuss Use js mixins magento 2 .i.e how to use js mixins in magento 2.And in this tutorial i will try to explain it briefly and also make it convenient.

Suppose your code does some task before any js script’s function run or you want to extend a function or to modify some data without overwriting js. And you want to know how to do it.Then this tutorial will help you learn and overcome all these problems easily.

First of all you will need to create requirejs-config.js under app/code/QaisarSatti/HelloWorld/view/frontend, like below:

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/action/set-shipping-information': {
                'QaisarSatti_HelloWorld/js/action/set-shipping-information-mixin': true
            }
        } // this is how js mixin is defined
    }
};
// Here i am extending "Magento_Checkout/js/action/set-shipping-information" this js with our custom js "QaisarSatti_HelloWorld/js/action/set-shipping-information-mixin".

Furthermore create set-shipping-information-mixin.js file under app/code/QaisarSatti/HelloWorld/view/frontend/web/js/action to extend original function. So here i am just using dummy data to shipping address only , Below is the code:

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
], function ($, wrapper, quote) {
    'use strict';
 
    return function (setShippingInformationAction) {
 
        return wrapper.wrap(setShippingInformationAction, function (originalAction) {
            var shippingAddress = quote.shippingAddress();
 
            if (shippingAddress['extension_attributes'] === undefined) {
                shippingAddress['extension_attributes'] = {'customvar':"value1"};
            }
            // you can write here your code according to your requirement
            return originalAction(); // it is returning the flow to original action
        });
    };
});

Now console thequote.shippingAddress() in js to you should see the result:

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 11, 2019


Magento 2 multi-select in system configuration

This article is about Magento 2 multi-select in system configuration . Getting all available categories and display them in a system config multi-select field list can be tricky sometimes. In this tutorial i will try to explain it swiftly and in a simple way that how can you do it in magento 2. There can be various ways of doing it.We will discuss one or two efficient ways of doing so here.

Let’s start our tutorial, here we will discuss different ways of doing it. I hope you are familiar with magento 2 and if yes, you will be able to move along nicely.

First of all modify

QaisarSatti/HelloWorld/etc/adminhtml/system.xml

and paste the following code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="module_section" translate="label" type="text"
                 sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Module</label>
            <tab>tab_name</tab>
            <resource>QaisarSatti_HelloWorld::config</resource>
            <group id="module_section_page" translate="label" type="text"
                   sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Module page settings</label>
                <field id="latest_category" translate="label" type="multiselect" sortOrder="12" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>New Product Category</label>
                    <source_model>QaisarSatti\HelloWorld\Model\Config\Source\Categorylist</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

Now

QaisarSatti/HelloWorld/etc/acl.xml

add Acl

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Magento_Backend::stores">
                    <resource id="Magento_Backend::stores_settings">
                        <resource id="Magento_Config::config">
                            <resource id="QaisarSatti_HelloWorld::config" title="Module Section" />
                        </resource>
                    </resource>
                </resource>
            </resource>
        </resources>
    </acl>
</config>

Now add

QaisarSatti/HelloWorld/Model/Config/Source/Categorylist.php

<?php

namespace QaisarSatti\HelloWorld\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Categorylist implements ArrayInterface
{
    protected $_categoryFactory;
    protected $_categoryCollectionFactory;

    public function __construct(
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    )
    {
        $this->_categoryFactory = $categoryFactory;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
    }

    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        return $collection;
    }

    public function toOptionArray()
    {
        $arr = $this->_toArray();
        $ret = [];

        foreach ($arr as $key => $value)
        {
            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }

        return $ret;
    }

    private function _toArray()
    {
        $categories = $this->getCategoryCollection(true, false, false, false);

        $catagoryList = array();
        foreach ($categories as $category)
        {
            $catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
        }

        return $catagoryList;
    }

    private function _getParentName($path = '')
    {
        $parentName = '';
        $rootCats = array(1,2);

        $catTree = explode("/", $path);
        // Deleting category itself
        array_pop($catTree);

        if($catTree && (count($catTree) > count($rootCats)))
        {
            foreach ($catTree as $catId)
            {
                if(!in_array($catId, $rootCats))
                {
                    $category = $this->_categoryFactory->create()->load($catId);
                    $categoryName = $category->getName();
                    $parentName .= $categoryName . ' -> ';
                }
            }
        }

        return $parentName;
    }
}

Furthermore, let’s discuss another way of doing so. Here In system.xml file field for multi select of category is like:

<group id="helloworld_setting" translate="label" type="text" delault="1" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Setting</label>
    <field id="cateogry" translate="label" type="multiselect" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
        <label>Select Category</label>
        <source_model>QaisarSatti\HelloWorld\Model\Config\Source\Categorylist</source_model>
    </field>
</group>

Now create a file Categorylist.php in QaisarSatti\HelloWorld\Model\Config\Source

namespace QaisarSatti\HelloWorld\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Categorylist implements ArrayInterface
{
    protected $_categoryHelper;

    public function __construct(\Magento\Catalog\Helper\Category $catalogCategory)
    {
        $this->_categoryHelper = $catalogCategory;
    }

    /*
     * Return categories helper
     */


    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }

    /*  
     * Option getter
     * @return array
     */

    public function toOptionArray()
    {


        $arr = $this->toArray();
        $ret = [];

        foreach ($arr as $key => $value)
        {

            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }

        return $ret;
    }

    /*
     * Get options in "key-value" format
     * @return array
     */

    public function toArray()
    {

        $categories = $this->getStoreCategories(true,false,true);

        $catagoryList = array();
        foreach ($categories as $category){

            $catagoryList[$category->getEntityId()] = '__'.($category->getName());
        }

        return $catagoryList;
    }

}

But in this case you’ll get first level only and categories included in menu.

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: January 1, 2019


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


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