Magento 2 – Fixing Error: Factory Class Does Not Exist

custommagento2PHP

This is my block class for form

Smartshore/Subscription/Block/SubscriptionForm

namespace Smartshore\Subscription\Block;

class SubscriptionForm extends \Magento\Framework\View\Element\Template
{

  protected $_subscriptionLoader;  

  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\SubscriptionFactory $_subscriptionLoader

    ) {
        $this->_subscriptionLoader = $_subscriptionLoader;
        parent::__construct($context);
    }

    public function getSubscriptionBy($id)
    {
        return $this->_subscriptionLoader->create()->load($id);
    }

}

Smartshore/Subscription/view/frontend/layout/subscription_index_add.xml

This is my xml file

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>New Subscription</title>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Smartshore\Subscription\Block\SubscriptionForm" name="subscriptionform.add" template="Smartshore_Subscription::form.phtml"/>
        </referenceContainer>
    </body>
</page>

In my template(Smartshore/Subscription/view/frontend/templates/form.phtml) I'm using $this->getSubscriptionBy($id);

But I'm getting two errors:

Invalid block type: Smartshore\Subscription\Block\SubscriptionForm
Class Magento\Catalog\Model\SubscriptionFactory does not exist

What is causing the errors here?

Best Answer

Error comes from the __construct method in your block (di):

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\SubscriptionFactory $_subscriptionLoader

) {
// ....

There is no class \Magento\Catalog\Model\SubscriptionFactory in the Magento. You should check what model you are trying to use in your block. Possible, it should be your own model (the corresponding model of your module)?