Feature request from flancer64, posted on GitHub Jun 08, 2016
Hello,
I create new stock object in case there is no stock with given ID (I know that ID is autoincremented value, this is code to create test data):
try {
/** @var \Magento\CatalogInventory\Api\StockRepositoryInterface $mageRepoStock */
$stock = $mageRepoStock->get(self::DEF_STOCK_ID);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
/** @var \Magento\Framework\ObjectManagerInterface $manObj */
$stock = $manObj->create(\Magento\CatalogInventory\Model\Stock::class);
$stock->setStockId(self::DEF_STOCK_ID); // this string should be removed to create new object
} finally {
$stock->setStockName('Stock Name');
$mageRepoStock->save($stock);
}
There is no errors in this code and no new object is created. New object will be created if I remove following string from code:
$stock->setStockId(self::DEF_STOCK_ID);
I debugged code and found that updateObject
is called instead of saveNewObject
in \Magento\Framework\Model\ResourceModel\Db\AbstractDb::save
method:
if ($this->isObjectNotNew($object)) {
$this->updateObject($object);
} else {
$this->saveNewObject($object);
}
This is a code for isObjectNotNew
:
protected function isObjectNotNew(\Magento\Framework\Model\AbstractModel $object)
{
return $object->getId() !== null && (!$this->_useIsObjectNew || !$object->isObjectNew());
}
I suppose we need additional validation in isObjectNotNew
method or we need a error message.
OK, I will remove the ID setter from code but this behavior is not expected - no result and no error.