6

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?

5

You can use below code to call the model from anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('\Namespace\Modulename\Model\Modelname');
| improve this answer | |
10

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();
}
| improve this answer | |
  • If I need to use my class factory in many methods of my block, have I to call create() factory method in everywhere? Or should I call I only one time? And in this case, where? – WaPoNe Jan 13 '17 at 9:23
  • How to use it for eav/entity_attribute ? – jafar pinjar Aug 4 '18 at 10:56
7

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.

| improve this answer | |
  • Is it a correct way (best practice) in Magento 2 or it should be better to use class factory as dependency as suggested by @KAndy? – WaPoNe Jan 13 '17 at 8:42
0

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();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.