Magento 2: how to get Model in Block

The question:

I want to use an instance of a Model into a Block.

in Magento 1 they uses:

$exple = Mage::getModel('exple/standard');

How can I do this with Magento 2?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can use below code to call the model from anywhere

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$model = $objectManager->create('NamespaceModulenameModelModelname');

Method 2

Override constructor in your block class and add your class factory as dependency.

public function __construct(
    MagentoBackendBlockTemplateContext $context,
    VendorExpleModelStandardFactory $modelFactory,
    array $data = []
) {
      $this->modelFactory = $modelFactory;
      parent::__construct($context, $data);
}

function someMetod() {
    $model =  $this->modelFactory->create();
}

Method 3

You can instantiate your model by using constructor. You can call it by ObjectManager directly but passing by constructor is the best approach.

Example by using constructor

protected $customer;

/**
 * @param MagentoFrameworkAppActionContext $context
 * @param DemoHelloWorldModelCustomer $customer
 */
public function __construct(
    MagentoFrameworkAppActionContext $context,
    DemoHelloWorldModelCustomer $customer
) {
    $this->customer = $customer;

    parent::__construct($context);
}

$this->customer is your model instances.

Hope this helps.

Method 4

Get the instance of a factory for your model using dependency injection.
You don’t need to define the factory explicitly, because factories are an automatically generated class type. When you reference a factory in a class constructor, Magento’s object manager generates the factory class if it does not exist. https://devdocs.magento.com/guides/v2.3/extension-dev-guide/code-generation.html

public function __construct(
    MagentoBackendBlockTemplateContext $context,
    HelloworldNewsModelNewsFactory $newsFactory,
    array $data = []
) {
    $this->newsFactory = $newsFactory;
    parent::__construct($context, $data);
}

Calling the create() method on a factory gives you an instance of its specific class.

$model = $this->newsFactory->create();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment