我有一个自定义表格,我也为它编写了一个自定义模型,但我无法理解如何执行Mage::getModel('')->setData()
之类的操作。我已经遵循了所需的结构,创建了Model类并指定了资源模型并定义了集合类,我可以在admin网格中检索数据。但是,我仍然无法理解如何将我的模型用于setData()
和getData()
。这是我的控制器,我正在进行AJAX调用,我想将数据保存到自定义表中。
Rent.php
<?php
namespace Mofosys\Fastcure\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Vendor\Module\Model\ModuleFactory;
class Rent extends Action {
protected $request;
protected $_moduleFactory;
public function __construct(Context $context, moduleFactory $moduleFactory) {
$this->_moduleFactory = $moduleFactory;
parent::__construct($context);
}
public function execute() {
$model = $this->_moduleFactory->create();
$data = $this->getRequest()->getPost();
$model->setName($data['name']);
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($data['name']);
return $resultJson;
}
}
我的模型具有以下结构:
|-Model
|-ResourceModel
| |-Module
| | |-Collection.php
| |-Module.php
|-Module.php
现在,我无法理解如何使用自定义模型从控制器中将此数据插入到表中。
Module/Model/Module.php
<?php
namespace Vendor\Module\Model;
use Magento\Framework\Exception\LocalizedException as CoreException;
class Fastcure extends \Magento\Framework\Model\AbstractModel {
public function _construct() {
$this->_init('Vendor\Module\Model\ResourceModel\Module');
}
public function getName() {
return $this->getData(self::name);
}
public function setName($name) {
return $this->setData(self::name, $name);
}
}
所有这一切似乎都不起作用,请帮助我们。
答案 0 :(得分:2)
|-Controller
|-Index
|-Rent.php
|-Model
|-ResourceModel
| |-Module
| | |-Collection.php
| |-Module.php
|-Module.php
--------控制器代码Rent.php -----------------------
<?php
namespace Mofosys\Fastcure\Controller\Index;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
class Rent extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$data = $this->getRequest()->getPost();
$model->setName($data['name']);
$model = $objectManager->create('Mofosys\Fastcure\Model\Module');
$model->setData('itemname', $data['name']);
$msg ="";
if($data != ''){
$model->save();
$msg = 'saved successfully';
}else{
$msg = 'not saved';
}
echo $msg;
}
}
--------------------模型代码Module.php ---------------------- -----
<?php
namespace Mofosys\Fastcure\Model;
use Magento\Framework\Phrase;
class Module extends \Magento\Framework\Model\AbstractModel
{
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
)
{
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
protected function _construct()
{
$this->_init('Mofosys\Fastcure\Model\ResourceModel\Module');
}
}