What's the difference between setData() and addData()?
Is there a connection if I update a product or set a new one?
- 1,339
- 2
- 15
- 34
2 Answers
setData overrides the existing data and can receive as parameter either a pair key-value either an array.
if you set as parameters a pair key-value then $_data[key] becomes value. If you set as parameter an array $_data becomes that array overwriting what ever it contained previously.
Example:
$_data = array('k1' => 'v1' , 'k2' => 'v2');
calling $obj->setData('k3','v3') results in
$_data = array('k1' => 'v1' , 'k2' => 'v2', 'k3'=>'v3');
calling $obj->setData(array('k3'=>'v3')) results in
$_data = array('k3'=>'v3');
calling $obj->setData('k2','v2000') results in
$_data = array('k1' => 'v1' , 'k2' => 'v2000')
calling $obj->setData(array('k2'=>'v2000')) results in
$_data = array('k2'=>'v2000');
addData receives as parameter only an array and it merges that array with the existing data.
Example:
$_data = array('k1' => 'v1' , 'k2' => 'v2');
calling $obj->addData(array('k3'=>'v3')) results in
$_data = array('k1' => 'v1' , 'k2' => 'v2', 'k3'=>'v3');
but calling $obj->addData(array('k2'=>'v2000')) results in
$_data = array('k1' => 'v1' , 'k2' => 'v2000');
setData()
function is only set one field value on one call. it can set multiple field value using multiple call of setData function.
addData() function is set multiple field values using array with array key as field index.
Just Example:
You want two field to set at object.
- field a>Value->X
- field b>Value->Y
If i using setData() then you need to do this type of works.need For two field you need call setData function two wise.
$ObVarien->setData('fieldA',$X);
$ObVarien->setData('fieldB',$Y);
But if i using addData() then you can do this array key as field name
$Data=array('fieldA'=>$X,'fieldb'=>$Y)
$ObVarien->addData($Data)
addData() and setData() are two Library Varien_Object class function.
addData() using setData() at lib file for set field value using loop.
public function addData(array $arr)
{
foreach($arr as $index=>$value) {
$this->setData($index, $value);
}
return $this;
}
- 77,456
- 20
- 123
- 237
-
4
-
@Marius i have check the lib class. and you answer more clear then me – Amit Bera Apr 01 '15 at 08:26
$obj->setData('k2'=>'v2399393')then? :-) (great if you add this specific point in your answer) – Rajeev K Tomy Apr 01 '15 at 08:11$obj->setData('k2'=>'v2399393')and not$obj->setData(array('k2'=>'v2000'))– Rajeev K Tomy Apr 01 '15 at 08:16$_data = array('k1' => 'v1', 'k2' => 'v2')then what happens if we do$obj->setData('k2'=>'v2000'). (means what happens if we set already existing value?)I think that is what the point your answer lags. Did you get my point now ? – Rajeev K Tomy Apr 01 '15 at 08:25