Magento 2: how to get Model in Block
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');