Get product changes

后端 未结 3 1217
难免孤独
难免孤独 2021-02-14 00:33

Situation is:

Admin logs in to system and he changes product somehow.

For example:

Sets qty to 10 Adds 2 images Changes description

Is there any

3条回答
  •  时光取名叫无心
    2021-02-14 01:18

    just in case some people still coming up to this one: @clockworkgeek's answer is not correct, as soon as you turn on developer mode and displaying errors (php>=5.4) you will get exceptions and warnings:

    Array to string conversion in...

    as solution for recursive comparison:

    public function onCatalogProductSaveBefore($observer)
    {
      $product = $observer->getProduct();
      if ($product->hasDataChanges()) {
        $newValues = $this->_compareArrayAssocRecursive($product->getData(), $product->getOrigData());
        $oldValues = $this->_compareArrayAssocRecursive($product->getOrigData(), $product->getData());
      }
    }
    
    protected function _compareArrayAssocRecursive($array1, $array2) 
    {
        $diff = array();
        foreach ($array1 as $key => $value) {
            if (is_array($value)) {
                if (!isset($array2[$key]) || !is_array($array2[$key])) {
                    $diff[$key] = $value;
                } else {
                    $newDiff = $this->_compareArrayAssocRecursive($value, $array2[$key]);
                    if (!empty($newDiff)) {
                        $diff[$key] = $newDiff;
                    }
                }
            } elseif (!array_key_exists($key,$array2) || $array2[$key] !== $value) {
                $diff[$key] = $value;
            }
        }
        return $diff;
    }
    

    Hope that helps Personally i would recommend to put that function into a helper class and make it public :)

    UPDATE: according to problems with numeric values was float and decimal the better solution would be:

    /**
     * return diff according to product changes 
     * 
     * @param Mage_Catalog_Model_Product $product
     * @return array
     */
    protected function _compareArrayAssocRecursive($product)
    {
        $diff = array();
        $attributes = $product->getTypeInstance(true)->getEditableAttributes($product);
    
        foreach ($attributes as $key => $value) {
            if ($product->dataHasChangedFor($key)) {
                $diff[$key] = $product->getData($key);
            }
        }
        return $diff;
    }
    

提交回复
热议问题