问题描述
我是magento2的新手。我已经从表中检索记录并显示在网格中,但是现在我正尝试从表单中向自定义表中插入/数据,但没有得到任何帮助。您能否指导我如何使用块类和资源模型等在自定义表中插入数据。我的意思是插入数据的标准方法。
这是方块类
class Insert extends Template
{
private $collectionFactory;
public $successMessage=null;
protected $data;
public function __construct(
Template\Context $context,CollectionFactory $collectionFactory,array $data = []
) {
$this->collectionFactory = $collectionFactory;
parent::__construct($context,$data);
}
public function execute()
{
$name = $this->getRequest()->getParam('bookName');
$author = $this->getRequest()->getParam('bookAuthor');
$description = $this->getRequest()->getParam('bookDescription');
$model = $this->collectionFactory->create();
$model->load($name);
$model->load($author);
$model->load($description);*/
$input = $this->getRequest()->getPostValue();
$model->setData($input);
$model->save();
$successMessage="Saved Successfully!";
}
}
-----------这些是模型类---------------
class Book extends AbstractModel
{
protected function _construct()
{
$this->_init(\vendor\BooksModule\Model\ResourceModel\Book::class);
}
}
class Book extends AbstractDb
{
protected function _construct()
{
$this->_init('vendor_BooksModule_Book','id');
}
}
----------------这是资源模型-----------------
class Collection extends AbstractCollection
{
protected $_idFieldName = 'id';
protected function _construct()
{
$this->_init("vendor\BooksModule\Model\Book","vendor\BooksModule\Model\ResourceModel\Book");
}
}
谢谢
解决方法
首先,需要创建一个客户模块。 https://www.mageplaza.com/magento-2-module-development/how-create-hello-world-module-magento-2.html
此处的一些说明创建定制模块后,您需要创建定制表。和使用该链接的资源模型。 https://www.mageplaza.com/magento-2-module-development/how-to-create-crud-model-magento-2.html
创建表和模型后,您可以将数据保存在块内。内部块可以使用getParam进行数据处理。但是想要那样改变。
public function execute()
{
$name = $this->getRequest()->getParam('bookName');
$author = $this->getRequest()->getParam('bookAuthor');
$description = $this->getRequest()->getParam('bookDescription');
$model = $this->collectionFactory->create();
$model = $model->getCollection()->addFieldToFilter('bookName',$name)->addFieldToFilter('bookAuthor',$author)->addFieldToFilter('bookDescription',$description);
$input = $this->getRequest()->getPostValue();
$model->setData($input);
$model->save();
$successMessage="Saved Successfully!";
}
我们只能收集具有ID的负载。你做错了。使用setData时,您还想添加属性名称。检查并更改。