Skip to main content
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
  • 14.1k
25 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,064
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
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
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,471
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
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
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,690
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
  • 199k
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,166
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

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

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

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
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

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
  • 199k
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
  • 36.1k
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
  • 36.1k
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
3 votes
Accepted

Magento 2 Save and Load functions

So, first of all, you always should use Repository to load and save objects. If there is a reason not to do this, everything is in phpDoc of load and save methods: /** * Save object data * * @...
Maciej's user avatar
  • 56
2 votes
Accepted

Get Categories of Products on Special Offer

So you already have the products inside the $collection object. You can do this. $categoryIds = array(); foreach ($collection as $product) { $categoryIds = array_merge($categoryIds, $product->...
Marius's user avatar
  • 199k
2 votes

Get Categories of Products on Special Offer

As you said you got product collection let assume product collection is $collection. $cat = array(); foreach ($collection as $col) { foreach ($col->getCategoryIds() as $catId) { ...
Vaibhav Ahalpara's user avatar
2 votes
Accepted

Magento2 - Creating Purchase Order Grid based on Sales Order Grid

The problem is that you have the di.xml with your collection handle in the etc/adminhtml directory while Magento puts these declarations in the base area, /etc/di.xml. This is resulting in the handle ...
Aaron Allen's user avatar
  • 9,029
2 votes

Magento 2: Delete data in custom module

If you want avoid do a foreach, you can use a collection walk. $modelcollection->walk('delete');
raumatbel's user avatar
  • 1,275
2 votes
Accepted

Magento 2: Delete data in custom module

Use \Magento\Ui\Component\MassAction\Filter class for massDelete protected $zipcodeFactory; public function __construct( \Magento\Ui\Component\MassAction\Filter $filter, \Vendor\Module\Model\...
Prince Patel's user avatar
  • 22.9k
2 votes
Accepted

Magento2 Override Resource Model does not Work

It appears to me that the only problem with your code is capitalization. The class you are writing preference for is actually: ...\Backend\Tierprice not ...\Backend\TierPrice (note the 'P') I have ...
austris's user avatar
  • 101
2 votes

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

Note: As per ECGM2 coding standard you should not use object manager direct in template files By ObjectManager //get product collection $objectManager = \Magento\Framework\App\ObjectManager::...
Prince Patel's user avatar
  • 22.9k

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