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?
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?
Override constructor in your block class and add your class factory as dependency.
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Vendor\Exple\Model\StandardFactory $modelFactory,
array $data = []
) {
$this->modelFactory = $modelFactory;
parent::__construct($context, $data);
}
function someMetod() {
$model = $this->modelFactory->create();
}
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 \Magento\Framework\App\Action\Context $context
* @param \Demo\HelloWorld\Model\Customer $customer
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Demo\HelloWorld\Model\Customer $customer
) {
$this->customer = $customer;
parent::__construct($context);
}
$this->customer is your model instances.
Hope this helps.
You can use below code to call the model from anywhere
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('\Namespace\Modulename\Model\Modelname');
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(
\Magento\Backend\Block\Template\Context $context,
\Helloworld\News\Model\NewsFactory $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();