119 votes
Accepted

How to implement service contract for a custom module in Magento 2?

I would like to give a bit more detail in addition to the excellent answer of @ryanF. I would like to sum up the reasons to add a repository for custom entities, give examples how to do so, and also ...
Vinai's user avatar
  • 14k
43 votes

How to implement service contract for a custom module in Magento 2?

@Raphael at Digital Pianism: Please refer to the following sample module structure: app/ ├ code/ | ├ Namespace/ | | ├ Custom/ | | | ├ Api/ | | | | ├ ...
ryanF's user avatar
  • 2,279
24 votes
Accepted

Best way to update product's attribute value

I have used method updateAttributes of class \Magento\Catalog\Model\ResourceModel\Product\Action. Method can update multiple products and attribute values, but if you want to update just one product ...
Bartosz Kubicki's user avatar
24 votes
Accepted

Truncate table using resource model in Magento 2

You can truncate table using DB Adapter and table name. /** @var \Magento\Framework\DB\Adapter\AdapterInterface $connection */ $connection = $model->getResource()->getConnection(); $tableName = ...
Max's user avatar
  • 4,054
22 votes
Accepted

What are the differences between a Model and a Resource model?

Models : Models are where your main business logic should be handled and is a single instance of an object. The model will use the resource model to talk to the database and get/set data for it on ...
Suresh Chikani's user avatar
8 votes
Accepted

Magento 2: What is a Resource Model and how can I use it?

You can get product,category and order collection by Proper way, public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\...
Rakesh Jesadiya's user avatar
7 votes

How to implement service contract for a custom module in Magento 2?

complete files of using service contracts Custom/Module/registration.php <?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::...
Asad Ullah's user avatar
  • 1,461
7 votes
Accepted

Error class AbstractDb not found

Change Magento\Framework\Model\Resource\Db\AbstractDb to Magento\Framework\Model\ResourceModel\Db\AbstractDb
Khoa TruongDinh's user avatar
6 votes
Accepted

Magento 2.1.0 : How to get custom table data in phtml file

You can load the Data by following below steps. Create a Block file or if you already created a block for your template use below code in the block in your module. Add below code to block public ...
Krishna ijjada's user avatar
6 votes
Accepted

It is possible to addStatusHistoryComment to order without call $order->save()?

If the order already exists in the system, you can mimic the core behaviour and call save() either on the order status history collection or the status history model itself. // just some random order ...
mam08ixo's user avatar
  • 2,963
6 votes
Accepted

Magento2 Get a list of all cms static blocks

Do a dependency injection of Magento\Cms\Model\BlockFactory class in your constructor public function __construct( ... \Magento\Cms\Model\BlockFactory $blockFactory, ... ) ...
Patri Dharmendra's user avatar
6 votes
Accepted

Custom Table Data not saving in Magento 2

Replace below code: $this->contactUS->setFullname($full_name); $this->contactUS->setCompany($company); $this->contactUS->setAddress($address); ...
Prashant Valanda's user avatar
5 votes

How to use resource model delete?

If we take a look: vendor/magento/framework/DB/Adapter/AdapterInterface.php /** * Deletes table rows based on a WHERE clause. * * @param mixed $table The table to update. ...
Khoa TruongDinh's user avatar
5 votes
Accepted

Fatal error: Call to a member function beginTransaction() on boolean in /var/www/html/app/code/core/Mage/Core/Model/Abstract.php on line 313

The problem comes from the declaration of the resources and the name used in the models. So instead of : <xmpieformbuilder> <class>Company_XMPieFormBuilder_Model</class> &...
Raphael at Digital Pianism's user avatar
5 votes

Custom Table Data not saving in Magento 2

try it like this: <?php namespace Learning\ContactUS\Controller\Index; class Save extends \Magento\Framework\App\Action\Action { /** * @var \Magento\Framework\View\Result\PageFactory ...
Marius's user avatar
  • 198k
5 votes

Magento 2 Get last and first item from model collections

This is Tested Solution feel free to implement $firstItem = $collections->getFirstItem(); $lastItem = $collections->getLastItem(); echo 'This First Record in Collection <br> '; print_r(...
HaFiz Umer's user avatar
  • 1,661
5 votes

magento 2 : model in custom module

You need to add another resource modal connection (CRUD) Step : 1 Create Model app/code/NameSpace/ModuleName/Model/Post.php Step : 2 Create Resource Model app/code/NameSpace/ModuleName/Model/...
Chirag Patel's user avatar
  • 6,126
4 votes

Serializable Fields in Magento Collections

Or more simply, in your resource model collection:- class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { protected function _afterLoad() { ...
Dallas Clarke's user avatar
4 votes
Accepted

Resource Model vs Repository in Magento 2

Resource models are the way models were handled in Magento 1 and are still available in Magento 2. Repositories are the way we are supposed to handle model storage and retrieval in Magento 2, but ...
Petar Dzhambazov's user avatar
4 votes

Magento 2.2 error: Unable to unserialize value

The problem is in /vendor/magento/framework/Serialize/Serializer/Json.php there is a function unserialize($string) which gives you a syntax error if the string is already serialized. There is a ...
Edmund's user avatar
  • 545
3 votes
Accepted

Why don't bound params work in an IN statement?

Magento, and most modern PHP database abstractions, ultimately rely on the PDO library's bound parameter implementation for bound parameter support. PDO doesn't support binding array to an IN ...
Alana Storm's user avatar
  • 44.4k
3 votes
Accepted

How to use resource model delete?

Here is what worked for me: $resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $myTable = $resource->getTableName('mytable'...
Aurelien C's user avatar
3 votes
Accepted

Mysql query to Model, Resource Model, Collection - Magento 2

Magento 2 still can work with Zend_Db_Expr for arbitrary SQL expressions in filters. Given a collection, use addFilter for the where condition: $chennaiCancelOrderCollection->addFilter( '...
Fabian Schmengler's user avatar
3 votes

Truncate table using resource model in Magento 2

Create a function in your ResourceModel app\code\Module\Namespace\Model\ResourceModel Inventory.php <?php namespace Module\Namespace\Model\ResourceModel; class Inventory extends \Magento\...
Rajeev Singh's user avatar
3 votes

Magento 2 Get last and first item from model collections

If you don't want to use a for-each loop then you should use the below code to get First and Last Item. For First Item, you can use an array of 0. e.g $collection[0]. This will give you the first ...
Abhishek Panchal's user avatar
3 votes
Accepted

Correct way to save entries to database

Make your class look like this: class ReservedItemRepository implements ReservedItemRepositoryInterface{ protected $collectionFactory; protected $reservedItemFactory; protected $...
Marius's user avatar
  • 198k
3 votes
Accepted

How to stop saving resource model and throw error messages inside _beforeSave function?

Just throw exception. protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if(!$object->getData('identifier')): throw new \Magento\Framework\...
Qaisar Satti's user avatar
  • 32.5k
3 votes
Accepted

Magento 2.2.5: Add Student Instead of Update Student

$model->setData($data); this line reset your data. If there id field present $data variable then your code working fine. Otherwise you need to set id for update. Check following code: $id = $this->...
Sohel Rana's user avatar
  • 35.8k
3 votes
Accepted

factory class duplicate insert check in magento2

Modify builder method following way: public function builder($pid,$type,$id,$date) { $log = $this->_builderFactory->create(); $log = $log->load($pid, 'p_id'); if (!$log->getId(...
Sohel Rana's user avatar
  • 35.8k
3 votes
Accepted

Grid not displaying in admin - custom Resource Model

I have Analysed the code you have shared there is no typo error. The Reason for Admin Grid Page not showing/blank is because magento is not able to read your adminhtml layout file. As per your code ...
mydons's user avatar
  • 491

Only top scored, non community-wiki answers of a minimum length are eligible