Page 4 - Magento 2 Development
Get URL in the .phtml template files
1. Get URL of the store homepage (http://domain.com/):
<?= $this->getUrl() ?>
2. Get URL of some page, e.g. "Contact Us" (http://domain.com/contacts/):
<?= $this->getUrl('contacts') ?>
3. Get URL of the theme static file, e.g.:
app/design/frontend/ThemeVendor/theme_name/web/css/custom.css
app/design/frontend/ThemeVendor/theme_name/Magefan_Blog/web/js/lazyload.js
app/code/Magefan_Blog/view/frontend/web/js/lazyload.js
vendor/magefan/module-blog/view/frontend/web/js/lazyload.js
use the following code:
<?= $this->getViewFileUrl('css/custom.css') ?>
<?= $this->getViewFileUrl('Magefan_Blog::js/lazyload.js') ?>
Menu Title [identifier]
Dashboard [Magento_Backend::dashboard]
Sales [Magento_Sales::sales] Operations [Magento_Sales::sales_operation] Orders [Magento_Sales::sales_order] Invoices [Magento_Sales::sales_invoice] Shipments [Magento_Sales::sales_shipment] Credit Memos [Magento_Sales::sales_creditmemo] Billing Agreements [Magento_Paypal::paypal_billing_agreement] Transactions [Magento_Sales::sales_transactions]
The etc/adminhtml/menu.xml file is used to control the Magento 2 admin panel menu and add new items to it, in particular.
In the previous article we described how to create your own section on the Magento 2 configuration page (Stores > Configuration).
In order to set the default values for the configuration fields, you need to create the following file in the module folder:
etc/config.xml
and add this code:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<section_id>
<group_id>
<field_id>default_value</field_id>
</group_id>
</section_id>
</default>
</config>
In the previous article we explained how to configure and delimitate access rights for the Magento 2 admin panel users. In this article, you will learn how to create your own access rules (Role Resources).
You need to create ACL file (ACL - Access Control List) in your module folder:
etc/acl.xml
To find the Magento 2 configuration page navigate to Magento 2 Admin Panel > Stores > Configuration.
All tabs and forms on this page are customized using this file
etc/adminhtml/system.xml
To add a new table to the Magento 2 database, you need to create a file in the module folder:
app/code/<VendorName>/<ModuleName>/Setup/InstallSchema.php
add the following code to it:
<?php
namespace VendorName\ModuleName\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;
class InstallSchema implements InstallSchemaInterface
{
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
//new table script will be there
$installer->endSetup();
}
}
Since you already know how to create first controller in Magento 2 and to display the "Hello World" text on your own page, in this article we will show you how to display it in the new block.
1. Add a new PHP class block.
Create this file:
app/code/<VendorName>/<ModuleName>/Block/SomeName.php
and add the following code to it:
<?php
namespace VendorName\ModuleName\Block;
class SomeName extends \Magento\Framework\View\Element\Template
{
public function getWelcomeText()
{
return 'Hello World';
}
}
where,
SomeName is a random name in CamelCase format.
\Magento\Framework\View\Element\Template — a class from which you inherit your own block that interacts with the template.
getWelcomeText — a public method we created to return the text "Hello World". You can create a name for it yourself.
2. Add a template file (template .phtml file)
Create this file:
app/code/<VendorName>/<ModuleName>/view/frontend/templates/some-name.phtml
and add the following
To display "Hello World" on your own page in Magento 2, follow these steps:
1. Register a router for the storefront.
Create this file:
app/code/<VendorName>/<ModuleName>/etc/frontend/routes.xml
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:App/etc/routes.xsd">
<router id="standard">
<route id="VendorName_ModuleName" frontName="path">
<module name="VendorName_ModuleName" />
</route>
</router>
</config>
You can use the developer name (VendorName) associated with the module name (ModuleName) as the router id. The frontName is used in the URL to access your controllers.
Both names have to be unique.
To create basic Magento 2 module you need only 2 files: module.xml and registration.php.
1. Firstly, create the module's folder:
app/code/<VendorName>/<ModuleName>/
and the folder that will contain the module configuration files:
app/code/<VendorName>/<ModuleName>/etc/
If the app/code folder is missing from your Magento 2 installation, please create one.
As you create your eCommerce store, there are multiple stages you go through: starting with development and gradually moving to live. Each stage has corresponding tasks to keep your website running.
Magento 2 handles this through the mode functionality. There are three Magento modes: default, development, and production. Each facilitates different store operations.
However, to use Magento 2 deploy modes effectively, you need to know what each is useful for. This is exactly what you will find out today: what Magento modes are, how they differ and how to switch between them.
What Are Magento 2 Deploy Modes?
Magento 2 deploy modes are modes that create specific operation conditions suitable for different store operation tasks. As we've mentioned, there are 3 core Magento deploy modes that make your experience better. Let's have a closer look at each of them.
1. Default mode
After installation, Magento 2 is in a default mode making it possible to use the platform without applying
If you face an unexpected 301 or 302 redirect in Magento 2 and you don't know why it happens or what code causes it, you can easily find this out by temporarily editing the following files:
/vendor/magento/framework/HTTP/PhpEnvironment/Response.php /vendor/magento/framework/Controller/Result/Redirect.php
Open Response.php and add the following line to the beginning of the setRedirect function:
var_dump($url); \Magento\Framework\Debug::backtrace(false, true, false); exit();
Example:
public function setRedirect($url, $code = 302)
{ var_dump($url); \Magento\Framework\Debug::backtrace(false, true, false); exit();
$this->setHeader('Location', $url, true)
->setHttpResponseCode($code);
return $this;
}
Now open the second Redirect.php file and add this:
var_dump($this->url); \Magento\Framework\Debug::backtrace(false, true, false); exit();
after each line containing:
$this->url =
Example:
public function setRefererUrl()
{
$this->url = $this->redirect->getRefererUrl();
In case you work with a lot of different Magento instances as a temporary project you might want to have a nice method to check debug backtrace of some function execution in Magento 2 quickly without installing or enabling additional software on the server, e.g. Xdebug.
In this case, you can use the native Magento backtrace function from \Magento\Framework\Debug class and call it whenever you need:
\Magento\Framework\Debug::backtrace(false, true, false);
As a result, you will get this nice HTML debug-backtrace:
Modules in the Magento 2 file structure
Module files in Magento 2 are located in 2 directories.
1. app/code/<VendorName>/<ModuleName>/ 2. vendor/<vendor-name>/<module-name>/
Vendor Name — is the name of the company/person that developed the module. In some cases, the name of the vendor may coincide with the name of the customer's company. Therefore, before developing a new module, the name should be agreed upon. In the examples, we use our name — Magefan.
Module files developed on order or modules from other companies installed via FTP are located in the app/code folder.
The vendor folder contains Magento 2 root modules, as well as modules installed using the Web Setup Wizard or Composer. You will find the Magento root modules in the vendor/magento folder.
Interesting to know:
In the Magento 2 repository (dev branch) on GitHub (https://github.com/magento/magento2), all root modules are in the app code/Magento folder. And all PHP libraries are in lib/internal/Magento.
This structure was used during the Magento 2 development, long before the vendor folder existence and official release. For convenience, this structure is still used on GitHub.
When a visitor scrolls the web-page down It is convenient to display a button that will allow easily, by a one-click move customer back to the top of the page.
(button example)
To enable such a button on your website please follow these simple steps:
1. Create default.xml layout file in your theme directory:
/app/design/frontend/ThemeVendor/ThemeName/Magento_Theme/layout/default.xml
The sortOrder property for plugins in Magento 2 determines when to call them (before, after, or around a method), on condition more than one plugin is configured for the same method.
<config> <type name="{ObservedType}"> <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false" /> </type> </config>
Prioritizing rules are as follows:
- Before executing the original method, Magento will run before plugins from the smallest to the biggest value in sortOrder.
- The part of the plugin around code will also be executed from the smallest to the biggest value before calling the original method (callable).
- The after plugin is called from the biggest to the smallest after calling the original method.
If you don't want to reindex Magento 2 from admin panel, the other way is to run reindex via CLI.
To reindex Magento 2 using CLI (Command Line Interface), navigate to your Magento folder in a terminal and use the following command:
php bin/magento indexer:reindex
It will reindex all indexes. Here is an example of the successful reindex execution:
Design Config Grid index has been rebuilt successfully in 00:00:00
Customer Grid index has been rebuilt successfully in 00:00:00
Category Products index has been rebuilt successfully in 00:00:01
Product Categories index has been rebuilt successfully in 00:00:00
Catalog Rule Product index has been rebuilt successfully in 00:00:01
Product EAV index has been rebuilt successfully in 00:00:02
Stock index has been rebuilt successfully in 00:00:00
Product Price index has been rebuilt successfully in 00:00:01
Catalog Product Rule index has been rebuilt successfully in 00:00:00
Catalog Search index has been rebuilt successfully in 00:00:02
In case you
If you have a product attribute and want to assign it to a single attribute set, it's easy to do via Magento 2 Admin Panel > Stores > Attributes > Attribute Set.
But what if you need to assign it to all your attribute sets? What if you have 50+ or ever 100+ attribute sets? It can be time costly.
So what you can do, is to create a simple script that will do all job for you.
1. Create a PHP file "myscript.php" in your Magento 2 root directory.
Have you ever wondered how easy it is to check the quality of your own code, your colleagues' code, or a third-party module you want to use on a Magento project?
The Magento development team has created the Magento Extension Quality Program Coding Standard (Magento EQP), which allows you to check the code compliance with the standard, as well as identify the following shortcomings:
- SQL queries execution in the loop;
- use of dangerous functions;
- use of super-global variables;
- excessive code complexity;
- Unjustified collections loads.
Imagine you are cooking pasta and sit down to play some game. You listen with one ear to see if the "dish" does not boil away. In this case, you are an observer. When the pasta starts to boil away — the event "pasta_began_to_boil_away" is triggered, which causes you (the observer) to rush to the kitchen (perform an action, an algorithm).
In Magento 2, as in real life, there are observers and events that are implemented on the basis of the "Publish-subscribe pattern". We have already described plugins in Magento 2, which allows you to extend and change the functionality of the store. Let's see how you can do this with the help of events and observers in Magento 2.
Events
Events are triggered by Magento 2 modules when an action has occurred or has to occur. Magento has many native events and also allows you to call your own event.
Use the dispatch method of the \Magento\Framework\Event\ Manager class to call an event.
You often need to change the JavaScript code logic located in the .js file. The easiest way is to override the js file is by using a theme. You can learn how to override view files in the article about Overriding Magento 2 Storeftont Files. This is a quick but not an elegant way.
To change one or more js-file methods, use the mixins available in RequireJS.
To extend this file:
app/code/VendorName/ModuleName/view/%area%/web/js/folder1/folder2/somefile.js