I created a custom form in admin using block(without UI component). So i want to get all columns of my custom table in form block file. Please suggest me.
Magento 2 Database – Get All Column Names of Table
blocksdatabasemagento2
Related Solutions
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.
Create a controller in your Vendor/Modlue/Controller/Index
<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Context;
use Vendor\Module\Model\YourModel;
class Blog extends \Magento\Framework\App\Action\Action
{
protected $model;
protected $date;
protected $customermodel;
public function __construct(
Context $context,
YourModel $model,
\Magento\Framework\Stdlib\DateTime\DateTime $date
)
{
$this->model = $model;
$this->date = $date;
parent::__construct($context);
}
public function execute()
{
$query['question'] = $this->getRequest()->getPostValue("question");
$query['email'] = $this->getRequest()->getPostValue("email");
$query['product_name']=$this->getRequest()->getPostValue("product_name");
$query['cutomer_name']=$this->getRequest()->getPostValue("customer_name");
if ($query){
$this->model->setData($query);
$this->model->Save();
$redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$redirect->setUrl($this->_redirect->getRefererUrl());
$this->messageManager->addSuccess(__('You submitted your Question successfully.'));
return $redirect;
}
else{
$redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$redirect->setUrl($this->_redirect->getRefererUrl());
$this->messageManager->addError (__('Failed To Submit Please Provide Valid Data.'));
return $redirect;
}
}
}
Best Answer
Try this add New function in your custom resource model and call that function where you want to display.
public function getFields() { $fields = $this->getConnection()->describeTable($this->getMainTable()); return $fields; }