9

I have created a new table using custom module and stored value to this table, now, i need to get table data in block php file from database in magento 2, How to achieve this?

TableName="email_format" columns="customerid" and "format" now, i need to retrieve customer id and format value from table.

Thanks,

Nits
2,5341 gold badge11 silver badges21 bronze badges
asked Apr 23, 2016 at 10:39

2 Answers 2

17

1) I Assume you have created Model and Collection file associated with that tables.

2) In a Block PHP file constructor add one argument (Dependency Injection) like below and store it in a class member variable.

 public function __construct(
 Context $context,
 \Namespace\Modulename\Model\ModelNameFactory $modelNameFactory,
 array $data = array()
) {
 $this->_modelFactory = $modelFactory;
 parent::__construct($context, $data);
}

3) Prepare a public method in your block to access collection like below.

public function getCollection(){
 return $this->_modelFactory->create()->getCollection();
}

4) Loop through each of the collection result.

Hope, this will help you.

answered Apr 23, 2016 at 10:58
1
  • Can we inject \Namespace\Modulename\Model\ResourceModel\ModelName\Collection directly in to constructor? Commented Jul 24, 2017 at 20:22
12

You can directly get custom table using objectmanager concept,

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
 $result1 = $connection->fetchAll("SELECT * FROM email_format");
echo "<pre>";print_r($result1);

Or

This is proper way using block:

public function __construct(
 Context $context,
 \Namespace\Module\Model\ModuleFactory $modelFactory,
 array $data = array()
) {
 $this->_modelFactory = $modelFactory;
 parent::__construct($context, $data);
}

You can get collection by factory methods:

public function getCollection(){
 return $this->_modelFactory->create()->getCollection();
}
answered Apr 23, 2016 at 10:43
2
  • 6
    This is not correct way Commented Apr 23, 2016 at 10:52
  • 12
    Using the object manager directly is definitely not the most elegant way of doing it. Try to stick to dependency injection Commented Apr 23, 2016 at 10:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.