magento-2
Magento, Magento 2 Tutorials

What is PageFactory in Magento 2?

Page Factory is a design pattern used in Magento 2 that provides an easy way to manage web elements on a page. It acts as a model for creating pages, allowing developers to define elements and define methods for interacting with these elements.

Example:

Let’s say you want to interact with a “Sign In” button on the login page of your Magento 2 store. You can create a class with Page Factory to define the element and interact with it. Here’s how you might define the class in PHP:

<?php
namespace YourNameSpace\Page;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\AbstractBlock;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

class LoginPage extends AbstractBlock implements ButtonProviderInterface
{
    /**
     * @var \Magento\Framework\View\Element\UiComponent\Control\ButtonFactory
     */
    protected $buttonFactory;

    /**
     * Constructor
     *
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\View\Element\UiComponent\Control\ButtonFactory $buttonFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\View\Element\UiComponent\Control\ButtonFactory $buttonFactory,
        array $data = []
    ) {
        $this->buttonFactory = $buttonFactory;
        parent::__construct($context, $data);
    }

    /**
     * Define the element with Page Factory
     *
     * @return \Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface[]
     */
    public function getButtonData()
    {
        return [
            'label' => __('Sign In'),
            'class' => 'signin',
            'id' => 'signin-button',
            'on_click' => sprintf("location.href = '%s';", $this->getSignInUrl()),
            'sort_order' => 10
        ];
    }

    /**
     * Get sign in URL
     *
     * @return string
     */
    public function getSignInUrl()
    {
        return $this->getUrl('customer/account/login');
    }
}

With Page Factory, you can now interact with the “Sign In” button by calling the getButtonData() method in your code. This makes it easier to manage elements on your page and reduces the risk of errors.

Posted by
Editorial Staff

Editorial Staff at WebShouters is a team of experts.

Leave a Reply

Your email address will not be published. Required fields are marked *