Page 3 - Magento 2 Development
Once you know how to get URLs in Magento 2, 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
<?php
namespace 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 ObjectManager in your code since it hides real dependencies of the class.
So, as you can see, getting current
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 improve Magento admin security 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
With the extensive custom database, you always have to go to extra mile to improve Magento admin security. 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 reCAPTCHA every user attempting to log in goes through.
Though it is not recommended to disable 2FA in Magento, 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
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 Object Manager 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,
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 run cron jobs manually 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
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 — Magento cron jobs.
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
Invoice is an element of the Magento order processing 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.
Magento 2 Preferences is used by the Magento 2 object manager 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
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.
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.
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:
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 create a simple product in Magento 2, 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));
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.
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":
<?php
namespace 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 your module 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" sortOrder="10" />
</type>
</config>
In the previous article 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).
When developing an online store based on Magento 2, you might face the problem of extending the standard Magento 2 or Magento extensions functionality.
Editing Magento core files or modules is not allowed because these changes will be overwritten during the upgrade.
So, how to make changes to the storefront (frontend) template file, css, js?
WARNING! The following instructions cannot be used to override the layout files.
Override module view-files in the app/code folder.
Let's say you need to change this file:
app/code/Magefan/Blog/view/frontend/templates/post/view.phtml
Make its copy in the theme folder with the following path:
app/design/frontend/ThemeVendor/themename/Magefan_Blog/templates/post/view.phtml
Make the necessary changes to the newly created theme file.
If your own theme is missing from your Magento installation, create new theme.
If you want to change product attribute type from dropdown to text in Magento 2, all you need to do is to run the following SQL queries (please make a Database backup before execution):
1. This query will change the attribute settings and convert it to a text attribute.
UPDATE eav_attribute SET
backend_type = "varchar",
frontend_input = "text",
source_model = ""
WHERE attribute_code = "MY_ATTRIBUTE_CODE";
2. This query will copy dropdown attribute data to the text attribute value table and replace the option IDs with their actual labels (text).
INSERT INTO catalog_product_entity_varchar
SELECT null as value_id, pei.attribute_id, pei.store_id, pei.entity_id, aov.value as value
FROM catalog_product_entity_int pei
LEFT JOIN eav_attribute_option ao ON pei.attribute_id = ao.attribute_id
LEFT JOIN eav_attribute_option_value aov ON ao.option_id = aov.option_id
WHERE
pei.value IS NOT NULL
AND pei.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = "MY_ATTRIBUTE_CODE
Sometimes, during Magento 2 customization you need to get the store Information programmatically. You may need to get a current Store ID, Store Code, Name, Website ID, or current URL.
To retrieve this data use the singleton instance of the following class:
\Magento\Store\Model\StoreManagerInterface
For example, you can include it in your class constructor and then call:
<?php
namespace \MyCompany\ExampleModule\Model;
class Example
{
private $storeManager;
public function __construct( ... \Magento\Store\Model\StoreManagerInterface $storeManager, ... ) {
... $this->storeManager = $storeManager; ... } /**
* Examples
*/
public function execute()
{
/* Get Current Store ID */
$storeId = $this->storeManager->getStore()->getId();
/* Get Current Store Code */
$storeCode = $this->storeManager->getStore()->getCode();
/* Get Current Store Name */
$storeName = $this->storeManager->getStore()->getName();