What is Difference between $_product->setData() & $_product->save()?
I will show you an example. Suppose we have a product A with quantity 1 by default. Now we need to
programmatically change the quatity of the product to 5. So for that we have wrote the following code.
Without save()
$_product = Mage::Registry('current_product');
$qty_before = $_product->getQty();
$_product->setData('qty', 5);
$qty_after = $_product->getQty();
echo "Quantity Available before setting the quantity property =".$qty_before."<br>";
echo "Quantity Available after setting the quantity property =".$qty_after."<br>";
Now it will show the following result
Quantity Available before setting the quantity property = 1.
Quantity Available after setting the quantity property = 5.
Now we have commented out the third line of code and then refreshed our page. Now our result will be look
like this.
Quantity Available before setting the quantity property = 1.
Quantity Available after setting the quantity property = 5.
With save()
$_product = Mage::Registry('current_product');
$qty_before = $_product->getQty();
$_product->setData('qty', 5);
$qty_after = $_product->getQty();
$_product->save();
echo "Quantity Available before setting the quantity =".$qty_before."<br>";
echo "Quantity Available after setting the quantity =".$qty_after."<br>";
Now it will show the following result
Quantity Available before setting the quantity = 1. || Quantity Available after setting the quantity = 5.
Now, again we have commented out the third line of code and then refreshed our page. Now our result will be
look like this.
Quantity Available before setting the quantity = 5. || Quantity Available after setting the quantity = 5.
So what is the difference? If we are setting a property means, it will update that field value for that time. But
actually the value is not saving in database. In order to save the data to the database, we have to use save()
method. Otherwise your changes that you made by setData() will be ignored by Magento.