:::: MENU ::::

Magento Tutorial | Magento Blog | Learn Magento 2

Are you a Magento 2 Developer? then you are at right place.

Cookies Consent Popup

In this article, we are going to understand the RequireJS Configuration in Magento 2. Magento 2 used Require JS Configuration properties are the map, paths, shim, mixins, and deps.

In Magento, We have to declare all the Require JS configuration properties inside the requirejs-config.js file. You can declare the requirejs-config.js file at different AREA Scope like frontend or adminhtml.

requirejs-config.js file contains the root config object, under the root config object you have to declare all the configuration properties.

Require js used Asynchronous Module Definition (AMD)  pattern to load the js file in the page.

The Basic Configuration looks like inside the js file as per the given syntax,

var config = {
    map: {
        '*': {
            'Magento_Checkout/template/view/shipping.html' : 'Rajesh_Checkout/template/view/shipping.html',
            'Magento_Checkout/js/view/shipping' : 'Rajesh_Checkout/js/view/shipping'
        }
    },
    paths: {
        "CheckoutPath" : 'Rajesh_Checkout/js/view/',
        "googlePayLibrary": "https://pay.google.com/gp/p/js/pay",
    },
    shim: {
        'Magento_PageBuilder/js/resource/slick/slick': {
            deps: ['jquery']
        }
    },
    config: {
        mixins: {
            'Magento_Theme/js/view/breadcrumbs': {
                'Magento_Theme/js/view/add-home-breadcrumb': true
            }
        }
    },
    deps: [
        'Magento_Theme/js/theme'
    ]
};

Let’s understand these configurations one by one.

  1. map: map is used to provide a prefix to a module with the different Id.
    format of map configuration: 

    map: {
        '<module name>': {
            '<Id>': '<JS file>'
        }
    }

    Here <module name> is an already exist module js file or you can use ‘*’.
    here Id is use to alias JS file.
    it can be defined in two formats:

    • module specific: In this mapping is defined only for particular module.
      example: 

      map: {
      	'module/module1': {
      		'sample': 'sample1.js'
      	},
      	'module/module2': {
      		'sample': 'sample2.js'
      	}
      }

      Here, when module/module1.js requires(‘sample’), then it returns sample1.js, and when module/module2.js requires(‘sample’), then it returns sample2.js.

    • globally: It can be used by any module.
      map: {
      	'*': {
      		'sample': 'sample1.js'
      	},
      	'module/module1': {
      		'sample': 'sample2.js'
      	}
      }

      In this ‘*’ is used for globally, i.e. any module which ask for require(‘sample’), then it returns sample1/js, but when module/module2.js require(‘sample’), then it returns ‘sample2.js’.

map in Magento2: map config used to mapping js file. If you want to declare any new JS file that contains the define() method as well as you can also override core Magento JS or template files.

map: {
    '*': {
        'Magento_Checkout/template/view/shipping.html' : 'Rajesh_Checkout/template/view/shipping.html',
            'Magento_Checkout/js/view/shipping' : 'Rajesh_Checkout/js/view/shipping'
    }
}

We are overriding the shipping template and JS file from the checkout module to our module using map config.

baseUrl: Is used when we want to define the url to load the js files for all the modules used in require js.
baseUrl applied on all the files which defined with name starting with a slash”/”, have any url like “http://” or having .js extension.
example:

 

var config = {
	"baseUrl": "module/test"
};

require( ["sample/sample1", "https://code.jquery.com/jquery-3.1.1.min.js", "sample2.js"],
    function(samplemodule) {
    }
);

Here, samplemodule is reffered to module/test/sample/sample1.js,
“https://code.jquery.com/jquery-3.1.1.min.js” is loaded from the url which is specified
and sample2.js is loaded from the same directory.

paths: Paths is used when you want to relate your base url path the your module path.
Path have the same properties as the baseUrl.
If the path is started from “/” or any url “http://” then it will not relate to the base url.
example:

 

var config = {
	"baseUrl": "module/test",
	"paths": {
        "sample": "web/js"
    },
};

require( ["sample/sample1"],
    function(samplemodule) {
    }
);

Now, samplemodule is reffered to the file at path “module/test/web/js/sample1.js”.

paths in Magento2: paths config is the same as maps but also used to declare paths of the JS file.

You can declare a module JS path in the paths config and use an alias to the template file.
paths config used to declare third party js file also.

  • Paths alias will be used to rename path segment as well as full js module also.
  • Path aliases configuration applies globally.
paths: {
    "checkoutPath" : 'Rajesh_Checkout/js/view/',
    "googlePayLibrary": "https://pay.google.com/gp/p/js/pay",
}

if any files inside the view folder are available, let’s assume, title.js. You can use this paths alias like in template,

 <script type="text/x-magento-init">
    {
        "*": {
            "checkoutPath/title" : {
                "storeId": "<?= $block->getStoreId();?>"
            }
        }
    }
</script>

Here “checkoutPath/title” refers to app/code/Rajesh/Checkout/js/view/title.js

googlePayLibrary alias used to load third-party JS files without .js extension the URL.

shim: It used when there are some scripts, to whome you want to declare globally, and those scripts not using define() to define values, if those scripts already used the define() then it will not work correctly.
examples:

 

var config = {
	"shim": {
		"sample": {
            "deps": ["jquery"],
            "exports": moduleSample
        }
	}
}

Here, jquery(dependencies) should be loaded before the sample.js is loaded, and then you can use moduleSample as a global module.

var config = {
	"shim": {
		"sample": {
            "deps": ["jquery"],
            "exports": moduleSample,
            init: function (jquery) {
            	return this.moduleSample.noConflict;
            }
        }
	}
}

Here, Dependencies are jquery, should be loaded before the sample.js.
Here, we use moduleSample as a global module.
init function is called after the exports, in this we can write the conflicts or clean up codes, in this function all the dependencies taken as arguments, and the return object from this functiona overwrites the string defined in “exports”.

shim in Mgento2: shim config used to declare dependency.

If you want to load a specific file before any other JS file you can declare using shim config.

shim: {
  'Magento_PageBuilder/js/resource/slick/slick': {
      deps: ['jquery']
   }
}

Here jquery file is load first after that slick.js file will be loaded. Shim gives a guarantee to load the dependent files first always.
If the dependent file will be not found, your js file will be not loaded. In the above syntax, if the jquery file is not loaded, the slick.js file will be never called on the page.

mixins: mixins config used to create JS mixins. you can declare JS files or any widget to be used as mixins.

config: {
    mixins: {
        'Magento_Theme/js/view/breadcrumbs': {
            'Magento_Theme/js/view/add-home-breadcrumb': true
        }
    }
}

Here we have to declare true for the mixins to work.

deps: A deps property used to load Javascript files on every page of the site.

When you check the network tabs of any page on the Magento site, you can able to see the theme.js file loaded on each page.

deps: [
    'Magento_Theme/js/theme'
]

You can use different config values as per your requirement in the module.

Magento 2 cost: CE vs. EE

The difference that strikes the eye at once is the price. While Magento 2 CE is free, the EE version is paid and the price depends on your business value.
Magento 1 EE license cost starts at $18.000 per year. Magento 2 EE license cost is based on a revenue model. In other words, the price depends on how much your store revenue is.
Here is the Revenue X License Cost X Percentage for Magento 2 EE table:

Revenue (USD) License price (year) Percentage
0-1 M $22.000 2.2%
1-5 M $32.000 3.2% – 0.64%
5-10 M $49.000 0.98% – 0.49%
10-25 M $75.000 0.75% – 0.3%

 

One of the main CE Magento 2 benefits is that it is free. So, if you don’t own enough investment capacity for a startup project, the CE version is what you need.
You can recompense the missing Magento e-commerce features with the use of 3d-party extensions. As a rule, Magento builders offer CE and EE extension versions where the modules for CE (magento enterprise edition) cost less than for EE.

Magento 2 Community vs. Magento Enterprise Edition Features

The two versions will be compared here by similarities and differences. You can find all the main Magento commerce features. Feel free to skip the common Magento 2 enterprise edition feature list if you are already on the subject. 

Magento 2 features list:

Common features

Extra features

Magento 2 CE/Magento 2 EE

Magento 2 EE

Improved SEO;

Customer Segmentation, Targeted Promotions & Merchandising;

Dynamic Rule Based Product Relations;

Site Management;

Persistent Shopping;

Automated Email Marketing Reminder;

Catalog Management;

Private Sales;

Gift Registry;

Catalog Browsing;

Gifting Options;

Rewards Points;

Product Browsing;

Store Credits;

Multiple Wish Lists;

Checkout, Payment and Shipping;

Add to Cart by SKU;

Return Management Authorization (RMA);

Order Management;

Content Management System;

Scheduled Import/Export Functionality;

Customer Accounts;

Backup and Rollback;

Staging, Merging and Rollback of Content;

Customer Service;

Customer Attribute Management;

Administrator Permission Roles on Website and Store Levels;

International Support;

Price and Promotion Permission

Logging of Administrator Actions;

Analytics and Reporting;

Category View and Purchase Permissions per Customer Group (Limited Catalog Access);

Order Archiving;

Mobile Commerce;

Elastic, Solr Search;

Configurable Order Tracking Widget;

Full Page Caching;

Support for Alternate Media Storage – CDN and Database;

PA-DSS Certification/Payment Bridge.


Native Device Applications;

Strong Data Encryption, Hashing and Key Management.

 

Marketing, Promotions and Conversion Tools;

 

 

Optimized Indexing.

 

 

 

To take a decision you need to compare the Magento CMS features and weight up the pros and cons. CE suits emerging projects with small investment capacity but a tech-savvy team and you can always upgrade Magento Community to Enterprise. EE is not a cheap variant but Magento enterprise features helps to save time on customization and tailoring extra functionality. 
Performance is an x-factor for any merchant. And Magento 2 EE is more profitable in this connection. Enterprise edition offers three key characteristics that influence performance directly. These are database scalability, search and job queue. In Magento 2 Community version, only one master database is used. With Magento 2 EE, you achieve data backup and analysis with the master database left untouched, as well as scalability:

graphql in magento

Magento 2 is a powerful ecommerce platform providing out-of-the-box features. However, there may be times when you need to extend the platform to meet specific business requirements. This is where custom GraphQL comes in!

If you’re unfamiliar with GraphQL, it’s a query language for APIs developed by Facebook (now Meta). It allows developers to get the data they need and only receive it in response to their queries. Magento 2 supports GraphQL to help you streamline your data processes.

In this article, I’ll tell you how to use GraphQL in Magento 2. I’ll start by enabling the GraphQL module in Magento 2 and accessing the GraphQL endpoint, and then make GraphQL queries to fetch data about products, categories, customers, orders, etc.

An Overview of GraphQL in Magento 2

GraphQL is an alternative to REST and SOAP in Magento 2. It allows you to specify and receive the data easily, making API responses more efficient and reducing network overhead. A simple example is Progressive Web App (PWA) with client-side rendering.

In Magento 2, GraphQL is a new feature added in version 2.3.4. The primary focus is to speed up and boost the APIs, their flexibility, and their effectiveness. It allows developers to query and mutate data in Magento’s database using a standardized syntax.

Three main operations of GraphQL are in use:

  1. queries (for reading and receiving information);
  2. mutations (needed for taking actions, creating data, and changing information. For example, a customer’s email);
  3. subscriptions (this operation isn’t available in Magento yet, but it provides the opportunity to get data from the server in real-time automatically after a while, for instance, for notifications).

Improvements of GraphQL in Magento 2.4.6

In Adobe Commerce 2.4.6, purchase orders functionality has also been fully exposed in the GraphQL layer by adding approval rules in the API.

Store owners and merchants will have big performance improvements due to the improved rendering process of the category tree in Magento Open Source 2.4.6.

The loading of category children by refactoring code has been improved by removing unnecessary method calls, improving category tree caching, and recursively loading category data.

Bulk cart operations have also been improved for query response times, specifically in situations where 500 or more products have been added to the shopping cart.

Why Is GraphQL Useful for Developers?

GraphQL is useful for Magento 2 developers for the following reasons.

  • Developers can request only the data they need, which results in smaller and more efficient data transfers. This is especially important for mobile and low-bandwidth devices.
  • It provides a flexible data model, which allows developers to query data more naturally and intuitively. This makes it easier to build complex data-driven applications.
  • It has a simple and intuitive syntax, making it easy for developers to learn and use. This simplicity reduces the learning curve and allows developers to focus on building their applications.
  • Developers can create custom GraphQL queries, mutations, and types, allowing them to extend the platform’s default schema and create custom functionality that meets their specific requirements.
  • It allows for optimized queries, which can significantly improve application performance. This is because it reduces the number of API requests required to fetch data.

Compare GraphQL vs Rest API

With the rise of the PWA, getting smaller amounts of data and making fewer API requests is needed. There comes the advanced technology and need for GraphQL. Magento 2 supports both GraphQL and REST APIs for interacting with the platform.

Here are some of the key differences between REST API and GraphQL.

REST API GraphQL
Querying With REST APIs, you typically make separate requests for each resource or the endpoint you want to access. With GraphQL, you can retrieve all the needed data in a single request and specify which fields and data you want.
Caching REST APIs are often easier to cache than GraphQL because the URLs are used as the cache keys. With GraphQL, caching can be more challenging because each request is unique and may require a different data set.
Learning Curve REST APIs are simpler to understand and use, and a wealth of documentation and tooling is available. GraphQL has a steeper learning curve, and it may take longer to become proficient with the technology.
Performance REST APIs can be faster when only a small amount of data is required. GraphQL can be more efficient than REST APIs for some use cases because it reduces over-fetching and under-fetching of data.

Furthermore, one can notice that GraphQL embroils perform rate-limiting and other service denial safety measures.

Although the choice of GraphQL or REST API in Magento 2 is entirely subjective and based on the website’s needs. But the one key point to note is that when it comes to security – RestAPI gives many innate ways to impose the security of your APIs.

In this example, the mutation creates a new customer account with the specified email, first name, last name, and password. The response includes the new customer’s first name, last name, and email address.

Summary

By using GraphQL in Magento 2, you can create APIs that are more efficient and flexible than traditional REST APIs. This is because GraphQL allows developers to specify exactly what data they need, rather than receiving a fixed set of data that may contain more information than necessary.

In addition to improved performance, custom GraphQL modules can also provide a more streamlined developer experience. It can help easily understand how to query the API and get the data they need. This can reduce the time and effort required to build integrations and applications on top of your Magento store.

Frequently Asked Questions

Q. Why use GraphQL in Magento 2?

A. GraphQL provides a definite and understandable description of the data required in the API. You can create APIs that are more efficient and flexible than traditional REST APIs. GraphQL uses types to ensure channels only ask for what’s possible and provide clear and helpful errors.

Q. How to set up GraphQL in Magento 2?

A.  To setup GraphQL in Magento, you will need the following steps:

You need GraphQL IDE such as GraphiQL or a browser extension to run the code samples and tutorials. If you install a browser extension, make sure it can set request headers. Altair GraphQL Client is one of the extensions on the Chrome Web Store that can do the job, or you can also use Postman.

If you are planning to add Recently Viewed products to your website then always use default magento approach. below approach is deprecated.


Because its not fully compatible with FPC so,now days magento using knockoutJS for Recently Viewed products. If you need to add a 'Recently Viewed' products block specifically via layout xml, use the same class Magento\Catalog\Block\Widget\RecentlyViewed which the 'Recently Viewed' Product widget uses.




This will render a simple grid with the last 4 products view by the user.
You can configure the block further, just as you would the widget instance:



One thing to note is that the argument values for ```show_attributes``` and ```show_buttons``` need to be declared as comma delimited strings (no spaces).
Declaring them as arrays or including spaces next to your comma's won't work due to the way the UI Component parse the content before Knockout renders it.
And since I said Knockout... it should play nicely with FPC, should.
Finally this solution doesn't use the **'action'** instruction which appears to have been deprecated.

That's it. Happy Coding !!!

First, You must have installed the Mailchimp extension in your project.


To Synchronize Mailchimp with Magento facilitate the subscription to the Newsletter for the customer and get the service of Mailchimp that will provide a lot of other additional services to the Magento platform.


How to configure Mailchimp in Magento 2?

1) Mailchimp -> Configuration,





2) From the Mailchimp General Configuration Section,
Choose Yes from the Enabled Field. You can see the above screenshot for reference to the enabled option.


3) Click on the Get API Credentials, and a new popup opens from Mailchimp,

When you click on the Get API Credentials button, a new popup will be displayed for asking the username and password for the MailChimp.
After Login with a Mailchimp account, the Second step you will ask to allow for Authorize Mailchimp for Magento 2, Press Allow button to go to the next step in the Popup.
Once you press Allow button, you will see the API key for Mailchimp that need to be added to the API key field of Magento.


You can see the final step of Popup from the Mailchimp API key as looks like the given screenshot.




4) After inserting the API key to the configuration, you need to click the top right button Save Config to save our changes.

This is the process to connect a Mailchimp account with Magento. you can use the subscription feature of Mailchimp in Magento by following the above steps.






 After upgrading to 2.4.3-p1 this issue occurs

Actually it was a problem with upgrade from 2.3.6 to 2.4.3 - magento added 2FA to login in 2.4 and on my Windows installation, for some reason, instead of showing error informing me that i need to configure 2FA to login, it just reloaded login form without any notice or errors.

Disabling 2FA module will solve the issue.


please run below command in terminal Magento root path :


    bin/magento module:disable Magento_TwoFactorAuth

    bin/magento cache:flush 

basically shim is used to avoid dependency conflict. 

For example if you calling a **custom javascript** then it must be loaded after javascript library isn't it? but magento doesn't know whether the library is loaded or not. So using shim we'll let system know that it is dependent on **library** so it will be instantiated when we map shim.

And

Magento uses requirejs to speed up the stuffs and (asynchronously module dependencies) nature of require js. So we use shim to tell the machine load our defined dependency first i.e., **jquery**

If we don't define then we get **jquery not defined error** while developing custom extensions as well.

The RequireJS shim configuration directive allows you to configure what I’ll call “load order” dependencies. i.e., you can say

when you load the jquery.cookie module? Make sure you’ve completely loaded the jquery module first. 


**Example :**

    var config = {

    paths:{

        "jquery.cookie":"Package_Module/path/to/jquery.cookie.min"

    },

    shim:{

        'jquery.cookie':{

            'deps':['jquery']

        }

    }};


We’ve defined a new top level configuration property named shim. This property is a javascript object of key value pairs. The key should be the name of your module (jquery.cookie above). The value is another javascript object that defines the shim configuration for this specific module.


That error indicates somewhere in your code passing null to the third parameter when calling a PHP function that is deprecated in PHP 8.1.


Assume you have below code:


return sprintf(
    $path,
    str_replace('methods_', '', $method)
);

The type of the third parameter should be changed to string if it is null. So the fixed code looks like the below:


return sprintf(
    $path,
    str_replace('methods_', '', $method ?? '')
);

The solution for your code:


$fromDate = date("Y-m-d",strtotime(str_replace("/", "-", $helper->getNewYearBallFromDate() ?? '')));
$toDate  = date("Y-m-d",strtotime(str_replace("/", "-", $helper->getNewYearBallToDate() ?? '')));

 Abstract Class:

  • An abstract class is a class that contains at least one abstract method. The abstract method is function declaration without anybody and it has the only name of the method and its parameters.
  • There can be any number of methods in the class and we have to declare the class as abstract only when there is an abstract method.

An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

Notes on Abstract class:

  • Objects cannot be created for the abstract classes.
  • If a class has only one method as abstract, then that class must be an abstract class. *The child class which extends an abstract class must define all the methods of the abstract class.
  • If the abstract method is defined as protected in the parent class, the function implementation must be defined as either protected or public, but not private.
  • The signatures of the methods must match, optional parameter given in the child class will not be accepted and error will be shown.

    Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).

interface:

An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class subclassing from it, it is said to implement that interface.

Rules of Interfaces:

  • All methods declared in an interface must be public; this is the nature of an interface.
  • All methods in the interface must be implemented within a class; failure to do so will result in a fatal error.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface
  • Interfaces can be extended like classes using the extends operator.

Note on Interfaces:

  • We cannot create objects to interface, but the class implementing the interface can have objects.
  • We cannot define a variable in an interface.
  • If we extend interface all the methods of the interface must be implemented in the child class.
Abstract classInterface
It can have constants, members, method stubs (methods without a body), methodsIt can only have constants and methods stubs.
Methods and members can have public or protected visibilityMethods of interface should only be public not any other visibility
The concept of multiple inheritances not supportedAn interface can extend or a class can implement multiple other interfaces.
Child class must implement all the abstract method of parent class when extend keyword is used.No need of implementing methods from parent interface when interface is extending another interface

First you need to create your cron file in `Cron` directory as below


app/code/Vendor/Module/Cron/Mycron.php

    <?php

       namespace Vendor\Module\Cron;

       class Mycron

        {

          protected $logger;

          public function __construct(

        \Psr\Log\LoggerInterface $loggerInterface

          ) {

        $this->logger = $loggerInterface;

          }

          public function execute() {

            //Your Logic/Code here

            //$this->logger->debug('Vendor\Module\Cron\Mycron');

          }

        }


then create cron_groups.xml in `app/code/Vendor/Module/etc/cron_groups.xml.

 it's option step.


    <?xml version="1.0"?>

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/cron_groups.xsd">

        <group id="vendor_module_cron_group">

            <schedule_generate_every>1</schedule_generate_every>

            <schedule_ahead_for>4</schedule_ahead_for>

            <schedule_lifetime>2</schedule_lifetime>

            <history_cleanup_every>10</history_cleanup_every>

            <history_success_lifetime>60</history_success_lifetime>

            <history_failure_lifetime>600</history_failure_lifetime>

            <use_separate_process>1</use_separate_process>

        </group>

    </config>


This will add entry in admin 

Now for scheduling cron script create crontab.xml on below path

`app/code/Vendor/Module/etc/crontab.xml`. 

Schedule time according to your need. I configured for every 5 minute.


    <?xml version="1.0"?>

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">

        <group id="vendor_module_cron_group">

            <job name="vendor_module_cronjob_mycron" instance="Vendor\Module\Cron\Mycron" method="execute">

                <schedule>*/5 * * * *</schedule>

            </job>

        </group>

    </config>


This will execute your cron at every 5th min. your magento cron must be configured on your server or you can run manually by running `php bin/magento cron:run` (run twice for schedule and execute)


Note: you can skip cron_groups.xml step and define default group too as below 

<group id="default">


"catalog_product_save_before" This event gets called for every product save action, including new products.

In order to use it you could do the following in your module:

**app\code\Vendor\Module\etc\webapi_rest\events.xml**


    <?xml version="1.0"?>

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

        <event name="catalog_product_save_before">

            <observer name="catalog_product_save_before_check_condition" instance="Vendor\Module\Observer\Productsaveafter" />

        </event>

    </config>


Then in `Productsaveafter.php` you can implement logic to connect to your own software and perform actions like adding or updating the product. 


Example:


**app\code\Vendor\Module\Observer\Productsaveafter.php**


    <?php

      namespace Vendor\Module\Observer;

     class Productsaveafter implements ObserverInterface{    

         public function execute(\Magento\Framework\Event\Observer $observer) {

           $product = $observer->getProduct();

            // Your logic to do stuff with $product       

            }

    }


Happy Coading ... Cheers !!!!!


Magento 2 Database Missing Table Error "inventory_stock_1"

Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'inventory_stock_1' doesn't exist, query was: INSERT INTO `search_tmp_5c4f24124efa61_76233970` SELECT `main_select`.`entity_id`, SUM(score) AS `relevance` FROM (SELECT DISTINCT  `search_index`.`entity_id`, (((0) + (0)) * 1) AS `score` FROM `catalog_product_index_eav` AS `search_index`
 INNER JOIN `catalog_product_entity` AS `product` ON product.entity_id = search_index.entity_id
 INNER JOIN `inventory_stock_1` AS `stock_index` ON stock_index.sku = product.sku
 INNER JOIN `catalog_category_product_index_store1` AS `category_ids_index` ON search_index.entity_id = category_ids_index.product_id AND category_ids_index.store_id = '1' WHERE (search_index.store_id = '1') AND (`search_index`.`attribute_id` = 102 AND `search_index`.`value` in ('2', '4') AND `search_index`.`store_id` = '1') AND (category_ids_index.category_id = 394)) AS `main_select` GROUP BY `entity_id` ORDER BY `relevance` DESC, `entity_id` DESC
 LIMIT 10000
Exception #1 (PDOException): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'inventory_stock_1' doesn't exist

Solution:

Please follow these steps:

1) Open your store database.

2) Remove your current "inventory_stock_1" view and run this one:

CREATE
SQL SECURITY INVOKER
VIEW `inventory_stock_1`
  AS
    SELECT
    DISTINCT    
      legacy_stock_status.product_id,
      legacy_stock_status.website_id,
      legacy_stock_status.stock_id,
      legacy_stock_status.qty quantity,
      legacy_stock_status.stock_status is_salable,
      product.sku
    FROM `cataloginventory_stock_status` `legacy_stock_status`
      INNER JOIN `catalog_product_entity` product
        ON legacy_stock_status.product_id = product.entity_id;

 Reindex your store data then check your store.

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.