cancel
Showing results for 
Search instead for 
Did you mean: 

setData behaving differently for save and update on product

setData behaving differently for save and update on product

Hello All,

 

I have encountered something strange about setData() function for product and wanted to validate if this is correct behaviour.

 

I was doing a custom product import from command line, the same command should update the product if already exists in DB.

 

My $data for Add/Update is 

 

Array
(
    [category_ids] => Array
        (
            [0] => 46
        )

    [name] => Dummy Product 1
    [sku] => P03
    [price] => 1990
    [quantity_and_stock_status] => Array
        (
            [qty] => 50
        )

    [description] => <p>Product Description</p>
    [new] => 
    [special_price] => 
    [attribute_set] => Default
)

PHP lines to add product, what worked is 

$product->setData($data);

PHP lines to update product, what worked is

foreach ($data as $key => $value) {
    $product->setData($key, $value);
 }

So my result code become

 if (empty($product->getId())) {
    $product->setData($data);
} else {
    foreach ($data as $key => $value) {
        $product->setData($key, $value);
    }
}
$product->save();

So my question is, is this code correct? to update the product we need to setData() to each attribute. If yes, is this the case for all entities in Magento?

 

Regards,

Shashidhar.G