It may well be that our online catalogue is not updated yet. We have a vast network of ingredients, our supply chain team will be happy to entertain any ingrendient enquiry.
As a store admin, you probably know how time-consuming it is to with their images to Magento 2 one by one especially if your store operates hundreds of items.
So, perhaps you are looking for easier ways to fulfill this task. Today, we'll cover how to import all products with images in Magento 2 using a local server and an external server.
Import Product Images in Magento from the Local Server
One of the possible ways to import product images in Magento is through the local server. For that:
1. Go to the Magento server and upload your image files to the default folder pub/media/import. You can select any other folder, just make sure to use the correct path while uploading product images to Magento.
2. In the CSV file add the name of each image file by SKU in the appropriate row and in the corresponding column depending on the image type (base_image, thumbnail_image, small_image, additional_image, etc.).
Note: if you want to add multiple images to one and the same SKU, then leave a blank
If you want to tailor your customer's experience to their needs you have to gather as much information about them as possible. Displaying unique pricing details or offering different shipping services based on customer groups required you to get current customer data in Magento.
Besides, customer age, gender and location are valuable marketing insights you can use to tweak your strategy.
Since you already know how to and to customize them, in this guide you'll learn everything about getting logged in customers details.
Get Current Customer in Magento 2
You can get current customer in Magento via \Magento\Customer\Model\Session model using two methods.
Using Construct
<?phpnamespace VendorName\ModuleName\Folder;class Example{ private $customerSession; public function __construct( \Magento\Customer\Model\Session $customerSession ) { $this->customerSession = $customerSession; } public function getCurrentCustomer() { return $this->customerSession->getCustomer(); }}?>
Using Object Manager
Magento allows you to create and configure 6 different in the admin panel. Each product has a unique name, ID, and other details related to it. So, after you learn how to , you have to know how to get current product in Magento 2.
Get Current Product in Magento 2
To get current product details you need to use .
<?phpnamespace VendorName\ModuleName\Folder;class Example{ private $registry; public function __construct( \Magento\Framework\Registry $registry ) { $this->registry = $registry; } public function getCurrentProduct() { return $this->registry->registry('current_product'); }}?>
And now you can use getCurrentProduct() method:
// print current product dataif ($currentProduct = $example->getCurrentProduct()) { echo $currentProduct->getName() . '<br />'; echo $currentProduct->getSku() . '<br />'; echo $currentProduct->getFinalPrice() . '<br />'; echo $currentProduct->getProductUrl() . '<br />';
Once you know how to , you might also need to learn how to get the current category in Magento 2. Regardless if you want to provide discounts based on category or simply retrieve all category information, this guide will come in handy.
Get current category in Magento 2 in PHP class
<?phpnamespace Vendor\Module\Folder;class Example { private $registry; public function __construct(Magento\Framework\Registry $registry) { $this->registry = $registry; } public function getCurrentCategory() { return $this->registry->registry('current_category'); }}
Get current category in Magento 2 via Object Manager
<?php$currentCategory = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Framework\Registry::class) ->registry('current_category');echo $currentCategory->getId();echo $currentCategory->getName();?>
Note: you should avoid direct use of the in your code since it hides real dependencies of the class.
So, as you can see, getting current category in Magento 2 is not that hard.
As a developer, you usually have to do plenty of mundane tasks. They would require a lot of time if you hadn't known any tricks to process big amounts of information faster. One of those tasks is getting product collection by category ID for either related products or price updating, etc.
Whatever the cause, you have to know how to get product collection by category ID in Magento.
To get product collection by category ID:
Get Product Collection by Category ID Using Class Construct
/*** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory*/protected $_productCollectionFactory;public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory) { $this->_productCollectionFactory = $productCollectionFactory; parent::__construct($context);}public function getProductCollectionByCategoryIds($ids){ $collection = $this->_productCollectionFactory->create(); $collection->addAttributeToSelect('*');
Magento Two-factor Authentication is one of many ways to and prevent unauthorized access to your data. Correspondingly all admin users have to complete the authorization process to verify their identity before logging in.
Two-Factor authentication is available in the latest Magento 2.4 version by default and supports multiple authenticators like Google Authenticator, Suo, Authy, and U2F keys. So it is easy for you to configure it and generate access codes for different users to add an additional layer of security.
However, if your website is in the development stage or if you work on the testing environment you might need to disable two factor authentication in Magento.
To disable 2F Authentication in Magento 2 you just need to run the following command:
php bin/magento module:disable Magento_TwoFactorAuth
Note: it is not recommended to disable two-factor authentication unless you have to.
If you want to grant some developers access to your installation so they can debug some issues
With the extensive custom database, you always have to go to extra mile to . Two-factor authentication is one of those tiny security steps you have to take to avoid any security loopholes and data leaks.
Correspondingly it is an additional layer of security beyond credentials and every user attempting to log in goes through.
Though it is not recommended to , there are some exceptions. You can disable it if the store is in the development or testing stage.
Still, you don't have to disable two-factor authentication completely, you can do this for a specific user. And we know how.
To disable Two-factor authentication in Magento for a specific user:
1. Create a etc/di.xml file in your custom module:
<?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\TwoFactorAuth\Model\TfaSession"> <plugin name="Magento_TwoFactorAuthCustom_Plugin_Magento_TwoFactorAuth_Model_TfaSession"
If you need to get current URL in Magento 2 PHTML file the easiest way to do this is to use the following code:
$currentUrl = $block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
This is the best method since you don't even need to use the Object Manager.
The same code works for block PHP classes as well. But you need to replace $block with $this.
Example:
$currentUrl = $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
But...
The Best Way to Get Current URL in Magento 2
The best way is to use UrlInterface.
Example:
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Framework\UrlInterface::class);$currentUrl = $urlInterface->getCurrentUrl();
Using the object manager directly is not recommended, so you need to include UrlInterface dependence in your class constructor to be able to use it.
Example:
private $urlInterface;public function __construct(...\Magento\Framework\UrlInterface $urlInterface...) {$this->urlInterface
Magento 2 Registry is a class that is used to share the data between objects in Magento.
e.g. save the object to the Registry in the controller class and get in the block class.
Starting from Magento 2.3 the Registry class was declared as deprecated but a lot of developers, extension vendors, and even Magento core code still use it.
How does it work?
To get a Registry object in your class you need to define it in the constructor, for example:
/*** @var \Magento\Framework\Registry*/private $registry;/*** ...* @param \Magento\Framework\Registry $registry,*/public function __construct(...,\Magento\Framework\Registry $registry,...) {$this->registry = $registry;...}
or you can easily get it via the for the testing purpose:
$registry = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Framework\Registry::class);
How to SET a new value into the Registry?
To set a new value into the register please use the public function register($key, $value, $graceful = false) method.
Imagine if you have to update currency rates or catalog price rules and generate website sitemaps manually. Seems like an impossible scenario, right? All because all these and many other tasks in your store are already handled for you by the Magento 2 cron jobs.
They schedule different activities and perform them automatically without you even noticing. However, if you want to learn more about your store performance you need to learn more about the cron tasks.
So in this comprehensive guide, we'll cover everything you need to know about Magento cron jobs. You'll discover how they work and how you can directly from the admin panel.
What is a Magento Cron Job?
Magento cron job is one of many tools Magento uses to schedule and run repetitive tasks (such as updating inventory, sending product alerts, or generating sitemaps) instead of triggering them manually.
Cron jobs rely on the crontab (configuration file) to execute the commands and scripts to perform certain operations within
There are a lot of processes in Magento 2 admin that require automation and scheduling. Updating currency rates, sending newsletters and product alerts are all handled by a handy default feature — .
Besides, plenty of Magento 2 extensions also come with custom cron jobs to execute different tasks within the module. So, if you're wondering how you can create one for your extension too, you've landed in the right place.
Today you'll learn how to create a cron job in Magento 2 step by step.
Note: before creating your custom cron job, make sure you have the crons by opening the crontab as the Magento file system owner. Run the following command:
crontab -l
The result should be as follows:
#~ MAGENTO START c5f9e5ed71cceaabc4d4fd9b3e827a2b
* * * * * /usr/bin/php /var/www/html/magento2/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/html/magento2/var/log/magento.cron.log
#~ MAGENTO END c5f9e5ed71cceaabc4d4fd9b3e827a2b
1. Create a Simple Module
The first step
Invoice is an element of the that is as important as the order itself. An invoice is a document that signifies the "agreement" between a store and a person and contains all of the order details.
Usually, order invoices in Magento 2 are created automatically, once the payment was authorized or captured by the store. However, there are cases when you need to create an invoice programmatically in Magento 2.
This is just the case. We will show you how to do this is in just 1 step.
To create an invoice programmatically in Magento 2 create a new model in your module, e.g: app/code/Vendor/Module/Model/CreateInvoice.php with code:
<?php
namespace [Vendor]\[Module]\Model;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Service\InvoiceService;
use Magento\Framework\DB\Transaction;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
class CreateInvoice
{
protected $orderRepository;
protected $invoiceService;
protected $transaction;
protected $invoiceSender;
public
Magento 2 Preferences is used by the to extend the default implementation. You can use preferences in Magento 2 to implement some interfaces or to rewrite/override the existing PHP classes and their methods.
In this article, you'll learn how to do it and discover useful examples that will help you along the way.
Overriding classes in Magento 2
If you want to rewrite existing class methods with Magento preference follow the steps below:
1. Create the etc/di.xml file in your extension folder:
app/code/MyCompany/ModuleName/etc/di.xml
2. Add this code to it:
<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\Checkout\Block\Onepage\Success" type="MyCompany\ModuleName\Block\Onepage\Success" /></config>
Use attribute "for" in the "preference" tag to define the PHP class that you want to override. Use attribute "type" to define the PHP class that will
When you configure Github webhooks, you open a lot of opportunities and make the development process easier. They are used to update backup mirror or external issue tracker, trigger CL builds and deploy changes to the production server.
Once you install the webhook, it will be triggered by a specific event like pull request or code push. Generally, webhooks allow you to automate a lot of processes, so you don't have to manually apply changes to the live.
So, in this article, you will learn how to add webhook in Github.
Let's start.
To add webhook in Github:
1. Navigate to your Github account.
2. Choose the repository which you want to configure the webhooks for and go to the Settings.
3. Go to the Webhooks tab and press the Add webhook button.
4. Set the Payload URL, Content type and Secret to set up webhook in Github.
Payload URL — server URL where the webhook requests will be sent.
Content type — the type of delivering webhook requests to the payload URL
Secret — "password" used to
Webhooks simplify a lot of processes on your application. They automate the pull requests, merging, pushing and others. You can create an event that would trigger the webhook request which will do the work for you.
In this article, you're going to learn about Gitlab.
Take the following steps to add webhooks in Gitlab:
1. Go to your GitLab account.
2. Navigate to a repository you want to add webhooks for and find the Settings section.
3. Click on the Webhooks tab.
4. Enter the URL you want POST requests to be sent to.
5. Set the Secret Token, so the URL you send the requests to can verify they are from GitLab.
6. Select the Trigger Events under which the webhooks should be sent.
Note: if you choose Push events you also have to specify the branch or wildcard pattern to trigger on. If you want all pushes to trigger the URL, just leave this field blank.
Once you select all events you want to trigger the webhooks in GitLab, press the Add webhook button.
That's it. It is really
Magento 2 Object Manager is a PHP class responsible for creating and retrieving objects in Magento 2. It also manages to create factories and proxies.
How does it work?
To get the object manager instance (e.g. get magento 2 object manager in phtml) use the code:
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
To add object Manager to constructor:
/
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/
* @param \Magento\Framework\ObjectManagerInterface $objectmanager
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectmanager
) {
$this->objectManager = $objectmanager;
}
Using the ObjectManager you can get a singleton object (method "get") of PHP class or create a new one (method "create").
Example:
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); /* Create a new product object */ $product = $objectManager->create(\Magento\Catalog\Model\Product::class); /* Get a request object
Creating configurable products you just` create simple products with some configurable options for customers to choose from. So, to create a configurable product programmatically you should start by creating a simple product and then assigning some features to it.
Follow these steps to create a configurable product in Magento 2 programmatically:
1. Create a simple product.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$product = $objectManager->create('Magento\Catalog\Model\Product');$sku = 'sku';$product->setSku($sku);$product->setName('Simple Product'); $product->setAttributeSetId(4); $product->setStatus(1); $product->setWeight(1);$product->setVisibility(4); $product->setWebsiteIds(array(1)); $product->setTaxClassId(0); $product->setTypeId('simple'); $product->setPrice(100);$product->setStockData(array('use_config_manage_stock' => 0, 'manage_stock' => 1, 'min_sale_qty' => 1, 'max_sale_qty' => 2, 'is_in_stock' => 1,'qty' => 1000));$product->save();$categoryIds
Magento 2 being a multifunctional e-commerce platform allows you to create products from the admin panel. There are plenty of options to fill out to , which obviously takes some time.
And what if you have to create a huge amount of products, especially during the development or testing?
The easiest, in this case, would be to create products programmatically. And that is exactly what you're going to learn in this article.
Use the following method to create a simple product in Magento 2 programmatically:
getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product = $objectManager->create('Magento\Catalog\Model\Product');
try {
$product->setName('Test Product');
$product->setTypeId('simple');
$product->setAttributeSetId(4);
$product->setSku('test-SKU');
$product->setWebsiteIds(array(1));
$product->setVisibility(4);
$product->setPrice(array(1));
$product->setImage('/testimg/test.jpg');
Sometimes you need to run Magento 2 code externally, in the following cases:
Magento 2 integration with other frameworks or platforms that are installed on the same web server,
quick test execution of some method, for example, cron job.
For example, create a test.php file in the Magento 2 root directory and add the following code to it:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get(Magento\Framework\App\State::class);$state->setAreaCode('adminhtml');
$object = $obj->create(\VendorName\ModuleName\Folder\Class::class);$object->someMethod();
VendorName\ModuleName\Folder\Class - the name of the class, you want to execute;someMethod - the name of the method you want to execute;Attention! Make sure the __DIR__. '/app/bootstrap.php is the correct path to the Magento 2 app/bootstrap.php file.
In Magento 2 you can create plugins (interceptors) that allow you to extend functionality and execute your own code before, after, or around any PHP class public method.
For example there is a PHP class with public functions "setName", "getName", "save":
<?phpnamespace VendorName\ModuleName\Folder;class SomeModel{ private $name; public function setName($name, $storeId = 0) { $this->name[0] = $name; } public function getName($storeId = 0) { return $this->name[$storeId]; } public function save($fields, $customData) { /* some save logic here */ }}
How to create plugin in Magento 2?
1. Create the etc/di.xml file in folder and add the following code there:
<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="VendorName\ModuleName\Folder\SomeModel"> <plugin name="mycompany_mymodule_plugin_modulename_Folder_somemodel" type="MyCompany\MyModule\Plugin\ModuleName\Folder\SomeModelPlugin"
In the you learned how to create new tables in Magento 2 database. In this one, you will learn more about the models used to work with the Magento 2 database which allows you to read, edit and delete the data.
Magento 2 and Magento 1 uses the Model/ResourceModel/Collection ORM (Object-relational mapping) for these purposes. To implement this concept you need to create 3 files (model, resource model, collection).
1. Create the Model file:
app/code/VendorName/ModuleName/Model/Somemodel.php
add the following code to it:
<?php
namespace VendorName\ModuleName\Model;
class Somemodel extends \Magento\Framework\Model\AbstractModel{ protected function _construct() { $this->_init('VendorName\ModuleName\Model\ResourceModel\Somemodel'); }}
The _construct initializes the resource model. Pass the name of the resource model class (create it in the next step) to the _init method.
Model is what you will most often work with. This class must be inherited from