2

how can I get product id from new product before save event.I have used below code but it will create blank product in database every time.

$newProduct = $product->duplicate();
echo $product_id = $newProduct->getId();

any other way to get product id before product save.

Bijal Bhavsar
  • 1,331
  • 10
  • 29
Zahirabbas
  • 2,073
  • 3
  • 24
  • 48

3 Answers3

3

What you could do is load the next value in the product table's auto_increment field. This should most of the time give you the id that will belong to the next product created.

$product = Mage::getModel('catalog/product');
$product_entity_table = $product->getResource()->getEntityTable();    
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$result = $connection->showTableStatus($product_entity_table);
$next_product_id = $result['Auto_increment']);
David Manners
  • 27,241
  • 9
  • 76
  • 220
2

You cannot get the new product id before saving it because the product does not have an ID before it is added to the db.
But I don't see the problem here. $product->duplicate() will call save() on the new product. You should get a valid id.

Marius
  • 197,939
  • 53
  • 422
  • 830
  • Thanks @marius but it create duplicate product and display it on grid.and it did not give current new product id but it will give id of just created duplicated product.i don't want duplicated product id but need new product id that i have creating. – Zahirabbas Jan 17 '14 at 10:19
0

You can try below code -

Mage::getSingleton('core/resource')->getConnection('core_read')->fetchOne('SELECT last_insert_id()')

after

$newProduct = $product->duplicate();

Tejas Shah
  • 598
  • 4
  • 10