Categories
Magento

How to Validate Input Field Value via Regex in Magento2

In this tutorial, We’ll learn how to validate input field value via regex in magento2. This validation is done on the server side via PHP and very effective. You can use this via ajax also.

Create a file anywhere from where you want to call this function and use below code:

<?php

namespace Vendor_Name\Module_Name\File_Path;

use InvalidArgumentException;

class InputValidator
{
    public function __construct(
        \Magento\Framework\Validator\RegexFactory $regexValidatorFactory
    ) {
        $this->regexValidatorFactory = $regexValidatorFactory;
    }

    public function checkInput(string $content)
    {
        if ($content) {
            $inputValidator = $this->regexValidatorFactory->create(
                [
                    'pattern' => '/^[A-Za-z0-9_.]+$/'
                ]
            );

            if (!$inputValidator->isValid($content)) {
                throw new InvalidArgumentException(
                    'Attribute name "%1" is invalid. Content should contain only characters, digits and dots', $content
                );
            }
        }
    }
}

Magento provides also inline pattern validation so you can use this also. Hope this server side code would be helpful. If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

Magento2 Cron and Create Cron Job in Custom Module

In this tutorial, We’ll learn how to create cron in our module but before that we should know what is cron.
If you do not want to handle a task manually, then cron is a good option. The Cron Job enables for precise time and date-based automatic running. The Cron Jobs are the ideal option for recurring projects every day or every week because of their automation.

Cron Jobs are used by Magento to do scheduled operations like reindexing and creating emails, newsletters, sitemaps, among other things. Crons can be readily set up in Magento 2 and listed in the database table to complete our duties at the appointed time.

When the cron job is run, a record with the cron job’s name, custom cron, is added to the cron schedule table. Now before start we assume the following:
(i) The Commerce application is installed in /var/www/html/magento_folder
(ii) Your Commerce database username and password are both is set
(iii) You perform all actions as the file system owner

Step 1: Create a sample module
You may utilise a custom module that you already have. Verify that the test module is registered and turned on.
Before you continue, verify that the sample module is registered and enabled.
Run the following command:

bin/magento module:status Vendor_Module

Step 2: Create a class to run cron
Create a class in following path: Vendor_Name/Module_name/Cron/Test.php and paste below code.

<?php
namespace Vendor_Name\Module_name\Cron;

use Psr\Log\LoggerInterface;

class Test {
    protected $logger;

    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }

   /**
    * Write to system.log
    *
    * @return void
    */
    public function execute() {
        $this->logger->info('Hello!! Magento Cron Works');
    }
}

Step 3: Create crontab.xml
Create crontab.xml as follows in the Vendor_Name/Module_name/etc directory:

<?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="default">
        <job name="custom_cronjob" instance="Vendor_Name/Module_name\Cron\Test" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

The Vendor_Name/Module_name/Cron/Test.php class is called by the previous crontab.xml once every minute, adding a row to the cron schedule database.

Step 4: Verify the cron job

  1. Compile the code with this command:
bin/magento setup:di:compile

2. And clean the cache with this command:

bin/magento cache:clean

3. Run Commerce cron jobs:

bin/magento cron:run

I hope this blog is resolve your issue easily.
If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

How to Hide Ui Component Form Custom Tab in Admin in Magento2

In this article, we will learn how to add/remove tab according to condition in magento2. As per previous blog we create custom tab and load ui grid on it. Now to hide that tab we’ll follow some steps:

Create customer_form.xml file at app/code/Vendor_Name/Module_Name/view/adminhtml/layout/customer_index_edit.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="demo-amit-tab" class="Vendor_Name\Module_Name\Ui\Component\Form\Product\Action">
        <settings>
            <collapsible>false</collapsible>
            <label translate="true">Demo Tab</label>
            <componentType>fieldset</componentType>
            <additionalClasses>
                <class name="customer-warranty-form">true</class>
            </additionalClasses>
        </settings>

        <insertListing name="product_listing">
            <settings>
                <dataLinks>
                    <exports>false</exports>
                    <imports>true</imports>
                </dataLinks>
                <externalProvider>product_listing.product_listing_data_source</externalProvider>
                <selectionsProvider>product_listing.product_listing.product_columns.ids</selectionsProvider>
                <autoRender>true</autoRender>
                <dataScope>product_listing</dataScope>
                <ns>product_listing</ns>
                <exports>
                    <link name="parent_id">${ $.externalProvider }:params.parent_id</link>
                </exports>
                <imports>
                    <link name="parent_id">${ $.provider }:data.customer.entity_id</link>
                    <link name="onAction">ns = ${ $.ns }, index = actions:action</link>
                    <link name="onMassAction">ns = ${ $.ns }, index = listing_massaction:massaction</link>
                </imports>
            </settings>
        </insertListing>
    </fieldset>
</form>

Create Action.php file at Vendor_Name\Module_Name\Ui\Component\Form\Product\Action.php

<?php
use Magento\Ui\Component\Listing\Columns\Column;
class Action extends Column
{
    public function prepare()
    {
        if ($condition) { // Your condition goes here
            $status = true;
        }
        $this->_data['config']['componentDisabled'] = $status; // for removing the tab
        parent::prepare();
    }
}

I hope this blog is resolve your issue easily.
If you still have any issue feel free to ask and let us know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

How to Load Ui Component in Custom Tab inside Admin in Magento2

In the previous blog, we learned how to create custom tab in customer form and now we will learn how to load grid inside admin in customer form in magento 2.

You will remember that we made two files: customer_index_edit.xml and customer_form.xml. So now we have to edit customer_form.xml and paste below code:

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="demo-amit-tab">
        <settings>
            <collapsible>false</collapsible>
            <label translate="true">Demo Tab</label>
            <componentType>fieldset</componentType>
            <additionalClasses>
                <class name="customer-warranty-form">true</class>
            </additionalClasses>
        </settings>

        <insertListing name="product_listing">
            <settings>
                <dataLinks>
                    <exports>false</exports>
                    <imports>true</imports>
                </dataLinks>
                <externalProvider>product_listing.product_listing_data_source</externalProvider>
                <selectionsProvider>product_listing.product_listing.product_columns.ids</selectionsProvider>
                <autoRender>true</autoRender>
                <dataScope>product_listing</dataScope>
                <ns>product_listing</ns>
                <exports>
                    <link name="parent_id">${ $.externalProvider }:params.parent_id</link>
                </exports>
                <imports>
                    <link name="parent_id">${ $.provider }:data.customer.entity_id</link>
                    <link name="onAction">ns = ${ $.ns }, index = actions:action</link>
                    <link name="onMassAction">ns = ${ $.ns }, index = listing_massaction:massaction</link>
                </imports>
            </settings>
        </insertListing>
    </fieldset>
</form>

Here we load product grid. We hope this article on load ui grid in custom tab to the Magento 2 customer form inside admin is simple to grasp.

If you still have any issue feel free to ask and let us know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

How to Add Custom Tab in Customer Form in Magento 2

In this editorial, we will learn how to add custom tab in admin customer form in magento 2.

The customer form mainly contains “Customer View”, “Account Information”, “Whishlist” and “Orders” sections. To add a custom tab to the customer form in Magento 2, follow the below steps:

Create customer_index_edit.xml file at app/code/Vendor_Name/Module_Name/view/adminhtml/layout/customer_index_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <uiComponent name="customer_form"/>
        </referenceContainer>
    </body>
</page>

Create customer_form.xml file at app/code/Vendor_Name/Module_Name/view/adminhtml/ui_component/customer_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="amit-demo-tab">
        <settings>
            <collapsible>false</collapsible>
            <label translate="true">Demo Tab</label>
            <componentType>fieldset</componentType>
            <additionalClasses>
                <class name="customer-demo-form">true</class>
            </additionalClasses>
        </settings>
    </fieldset>
</form>

I hope this article on adding a custom tab to
the Magento 2 customer form in admin is simple to grasp.

If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

How to Add Custom Tab in Product Detail page Magento2

In this instructional exercise, I will clarify to how to include custom
tab in product detail page in Magento 2. By default, there are 3 tabs
show in product detail page. Details, More Information & Review Tab. You
must then customise the page if you wish to add extra tabs.
you would like to create new file
app/code/Vendor_Name/Module_Name/view/frontend/layout/catalog_product_view.xml
and paste the underneath code :

<referenceBlock name="product.info.details">
     <block class="Magento\Catalog\Block\Product\View"
         name="custom.tab"
         as="customtab"
         template="Vendor_Module::product/view/custom.phtml"
         group="detailed_info">
         <arguments>
             <argument translate="true" name="title"
 xsi:type="string">Demo Tab</argument>
             <argument name="sort_order" xsi:type="string">10</argument>
         </arguments>
     </block>
</referenceBlock>

After that, ought to make file
app/code/Vendor_Name/Module_Name/view/frontend/templates/product/view/custom.phtml and now add content that custom tab with the content you want to display. Additionally, you can provide the sort order of a custom tab, which will cause it to display in the proper order according to the sort order value you choose.

<span>This is Demo tab</span>


I hope this article on adding a custom tab to
the Magento 2 product detail page is simple to grasp.

If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

How to Solve the Admin Login Issue After Upgrading to Magento 2.4.4 to 2.4.5

Admin access is disabled when the maximum session size is set to zero. The error occurs substantially because the maximum session size has been reset to ‘ 0 ’ after the Magento upgrade. This terminates the admin session as soon as it’s initiated and therefore redirects the admin to the same login page.

Coming to the result of the Admin login not working after upgrading to Magento2.4.4 to 2.4.5, you need to increase the maximum session size in Magento 2. This can be done by running a simple command in the command line interface. You can run the following command to do that:

bin/magento config:set system/security/max_session_size_admin 2560000

This will change the maximum session size for the admin to 2560000, allowing the admin to log in and access the Magento admin panel.

If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Categories
Magento

Price Adjustment in Product and Category pages in Magento2

One can adjust the price of saleable entity at product and category page.

For adjustments, create file etc/di.xml in your module:

<type name="Magento\Framework\Pricing\Adjustment\Collection">
  <arguments>
    <argument name="adjustments" xsi:type="array">
      <item name="price_adjustment" xsi:type="const">VENDOR\MODULE\Pricing\Adjustment::ADJUSTMENT_CODE</item>
    </argument>
  </arguments>
</type>
<type name="Magento\Framework\Pricing\Adjustment\Pool">
  <arguments>
     <argument name="adjustments" xsi:type="array">
        <item name="price_adjustment" xsi:type="array">
           <item name="className" xsi:type="string">VENDOR\MODULE\Pricing\Adjustment</item>
           <item name="sortOrder" xsi:type="string">10</item>
        </item>
     </argument>
  </arguments>
</type>

Now create the Adjustment.php file : VENDOR\MODULE\Pricing\Adjustment.php

namespace VENDOR\MODULE\Pricing;
use Magento\Framework\Pricing\Adjustment\AdjustmentInterface;
use Magento\Framework\Pricing\SaleableInterface;
class Adjustment implements AdjustmentInterface
{
    const ADJUSTMENT_CODE = 'price_adjustment';
    const ADJUSTMENT_PRICE = 1.79;
    /**
     * Get adjustment code
     *
     * @return string
     */
    public function getAdjustmentCode()
    {
        return self::ADJUSTMENT_CODE;
    }
    /**
     * Define if adjustment is included in base price
     *
     * @return bool
     */
    public function isIncludedInBasePrice()
    {
        return true;
    }
    /**
     * Define if adjustment is included in display price
     *
     * @return bool
     */
    public function isIncludedInDisplayPrice()
    {
        return true;
    }
    /**
     * Extract adjustment amount from the given amount value
     *
     * @param float $amount
     * @param SaleableInterface $saleableItem
     * @param null|array $context
     * @return float
     */
    public function extractAdjustment($amount, SaleableInterface $saleableItem, $context = [])
    {
        return $amount - self::ADJUSTMENT_PRICE;
    }
    /**
     * Apply adjustment amount and return result value
     *
     * @param float $amount
     * @param SaleableInterface $saleableItem
     * @param null|array $context
     * @return float
     */
    public function applyAdjustment($amount, SaleableInterface $saleableItem, $context = [])
    {
        return $amount + self::ADJUSTMENT_PRICE;
    }
    /**
     * Check if adjustment should be excluded from calculations along with the given adjustment
     *
     * @param string $adjustmentCode
     * @return bool
     */
    public function isExcludedWith($adjustmentCode)
    {
        return $this->getAdjustmentCode() === $adjustmentCode;
    }
    /**
     * Return sort order position
     *
     * @return int
     */
    public function getSortOrder()
    {
        return 21;
    }
}

From the above code one can adjust the price for all the saleable item in the inventory.

ADJUSTMENT_CODE is unique for the adjustment Collection class.

Collection Class : Magento\Framework\Pricing\Adjustment\Collection collection.

The price of the saleable items in the inventory increase to amount ADJUSTMENT_PRICE defined as constant in Adjustment.php.

Functions extractAdjustment and applyAdjustment in Adjustment.php contains the adjustment logic.

Price adjustments affect only the price of the saleable items in product and category pages.

For adjusting the price of specific ID or specific type, one can get the info of saleable item from SaleableInterface $saleableItem. Price adjustments will not affect price of the items in the cart. Resource

Price Adjustment in Product and Category pages in Magento2

If you still have any issue feel free to ask and let us know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.