3

I am learning how to develop a CRUD module in magento 2. I have develop a module in which database is created through my setup file. But I am not able to use model in Block.

For this I have created my model file:

namespace CompanyName\Hello\Model;

class Test extends \Magento\Framework\Model\AbstractModel implements TestInterface, \Magento\Framework\DataObject\IdentityInterface
{
    const CACHE_TAG = 'hello_test';

    protected function _construct()
    {
        $this->_init('CompanyName\Hello\Model\ResourceModel\Test');
    }

    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    public function loadByTitle($title){
        if(!$title){
            $title = $this->getTitle();
        }
        $id = $this->getResource()->loadByTitle($title);
        return $this->load($id);
    }
}

And I have create my Block file:

<?php

namespace CompanyName\Hello\Block;

class Hello extends \Magento\Framework\View\Element\Template
{
    protected $_testFactory;
    protected $logger;
    public function __construct( \Magento\Framework\View\Element\Template\Context $context,
            \CompanyName\Hello\Model\TestFactory $testFactory, \Psr\Log\LoggerInterface $logger
    )
    {
        $this->logger = $logger;
        $this->_testFactory = $testFactory;
        parent::__construct($context);
    }

    protected function _prepareLayout()
    {
        $test = $this->_testFactory->create();
        $this->logger->info('after create');
        $test->setTitle('magento');
        $test->save();
        $this->setTestModel($test);
    }
}

But I am getting a blank page without any error. Currently I am working in Developer Mode. If I remove this code then my page is visible correctly.

Need an Urgent help. Thanks.

2
  • Please check on log & report folder
    – Jackson
    Commented Nov 29, 2016 at 7:34
  • I have checked it, but not getting any error. Commented Nov 29, 2016 at 8:09

1 Answer 1

0

I think you missed the Interface. You mention in you model implements TestInterface

<?php
namespace CompanyName\Hello\Model;
interface TestInterface 
{

}

delete var/generation after that

2
  • I don't know anything about interface. Can you tell me wky we need to declare Interface? Commented Nov 29, 2016 at 8:09
  • @GauravAgrawal because you are using it implements TestInterface in you code check the magento module structure then you understand it Commented Nov 29, 2016 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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