phpimportopencartopencart-3opencart-module

Why categories relation with products disappear when I update products in Opencart?


I'm developing an extension in Opencart when I try updating existing products with a relationship to some categories, the products get uncategorized and leave their categories although I disabled all kinds of categorizing in product importing or updating.

Here a snippet of product import & update function:

    public function format_product( $product, $update = false, $force_update = false ){
    if( empty( $product ) ){
        return $product;
    }

    if( !$update || $force_update ){

        $temp = array(
            'product_description' => array(),
            'model'             => isset( $product->sku ) ? $product->sku : '',
            'sku'               => isset( $product->sku ) ? $product->sku : '',
            'upc'               => '',
            'ean'               => '',
            'jan'               => '',
            'isbn'              => '',
            'mpn'               => '',
            'location'          => '',
            'price'             => '0',
            'points'            => '',
            'tax_class_id'      => '0',
            'quantity'          => '0',
            'minimum'           => '1',
            'subtract'          => '1',
            'stock_status_id'   => '5',
            'shipping'          => '1',
            'date_available'    => date( 'Y-m-d', strtotime( '-1 day') ),
            'length'            => '',
            'width'             => '',
            'height'            => '',
            'length_class_id'   => '1',
            'weight'            => '',
            'weight_class_id'   => '1',
            'status'            => '1',
            'sort_order'        => '0',
            'manufacturer'      => '',
            'manufacturer_id'   => '0',
            'product_store'     => array(0),
            // 'product_category'  => array(),
            'product_option'    => array(),
            'image'             => ''  // This is Pending.
        );

        //  Add to selected stores.
        if ( !empty( $this->all_stores ) ) {
            $temp['product_store'] = $this->all_stores;
        }

        $languageCodes = array();
        foreach ( $this->languages as $key => $lng ) {
            // Check for name in current language.
            $lng_code = explode( '-', $lng['code'] );
            $lng_code = $lng_code[0];

            $name = $product->name;
            $description = $product->description;

            /*$product_name = array_key_exists( $lng_code, $name ) ? $name[$lng_code] : $name['en'];
            $product_desc = array_key_exists( $lng_code, $description ) ? $description[$lng_code] : $description['en'];*/
            $product_name = isset( $name->$lng_code ) ? $name->$lng_code : '';
            if( empty( $product_name )){
              $product_name = isset( $name->en ) ? $name->en : '';
          }
          /*set url*/
         if(version_compare(VERSION, '3.0.0','<') ) {
            if(isset($name->en)){
                $urlData = $name->en;
            }elseif (isset($name->$lng_code)) {
                $urlData = $name->en;
            }
            if(!empty($urlData)){
                $url = strtolower($urlData);
                $urlKey = str_replace(' ', '-', $url); 
                $temp['keyword'] = $urlKey;
            }
          }
          /*set url*/
          $product_desc = isset( $description->$lng_code ) ? $description->$lng_code : '';
          if( empty( $product_desc )){
              $product_desc = isset( $description->en ) ? $description->en : '';
          }
          $temp['product_description'][$lng['language_id']] = array(
            'name'              => $product_name,
            'description'       => $product_desc,
            'meta_title'        => $product_name,
            'meta_description'  => '',
            'meta_keyword'      => '',
            'tag'               => '',
        );
          $languageCodes[] = $lng_code;
          $languageIds[$lng_code] = $lng['language_id'];

      }
      /*attribute group code*/
      if(!empty($languageCodes)){
        $language_code = $languageCodes[0];
        $attributeGrouplanguageId = $languageIds[$language_code];
    }
    /*load model*/
    if( $this->is_admin ){
        $this->load->model('catalog/attribute_group');
    }else{
        $admin_dir = str_replace( 'system/', 'admin/', DIR_SYSTEM );
        require_once $admin_dir . "model/catalog/attribute_group.php";
        $this->model_catalog_attribute_group = new ModelCatalogAttributeGroup( $this->registry );
    }
    /*load model*/
    $attribute_group_id = $this->model_extension_module_knawat_dropshipping->getAttributeGroup('knawat');
    if(!$attribute_group_id){
        /*add attribute set*/
        $attributeGroupArray = array();
        $attributeGroupArray['sort_order'] = 2;
        $attributeGroupArray['attribute_group_description'][$attributeGrouplanguageId] = array(
            'name'              => 'Knawat'
        );
        $attribute_group_id = $this->model_catalog_attribute_group->addAttributeGroup($attributeGroupArray); 
    }
    /*add attribute set*/
    /*attribute group code*/
    /*load model*/
    if( $this->is_admin ){
        $this->load->model('catalog/attribute');
    }else{
        $admin_dir = str_replace( 'system/', 'admin/', DIR_SYSTEM );
        require_once $admin_dir . "model/catalog/attribute.php";
        $this->model_catalog_attribute = new ModelCatalogAttribute( $this->registry );
    }
    /*load model*/
    /*variation array*/
    if (isset($product->variations[0]->attributes) && !empty($product->variations[0]->attributes)) {
        $attribute = $product->variations[0]->attributes;
        if($attribute[0]){
            if (isset($attribute[0]->name) || !empty($attribute[0]->name) ) {
                $variationdata = (array)$attribute[0]->name;
            }
        }
    }
    /*variation array*/
    /*attribute code*/
    if (isset($product->attributes) && !empty($product->attributes)) {
        $subArray = array();
        foreach ($product->attributes as $key => $attribute) {
            $attributeNames =  (array)$attribute->name;
                foreach ($attributeNames as $key => $value) {
                if(!empty($variationdata[$key]) && !in_array($variationdata[$key], $attributeNames)){
                    if(in_array($key, $languageCodes)){
                        $attributeId = $this->model_extension_module_knawat_dropshipping->getAttributeData($value);
                        if(!$attributeId){
                            $languageId = $languageIds[$key];
                            $newArray[$languageId] = array(
                                'language_id' => $languageId,
                                'name'  => $value
                            );
                        }               
                    } 
                }

                }
                if(!empty($newArray)){
                    $subArray['attribute_group_id'] = $attribute_group_id;
                    $subArray['sort_order'] = 2;
                    $subArray['attribute_description'] = $newArray; 
                    $this->model_catalog_attribute->addAttribute($subArray);         
                }
        }
    }
    /*attribute code*/
    /*product code*/
   if(!empty($product->attributes)){
    foreach ($product->attributes as $key => $attribute) {
        $attributeNames =  (array)$attribute->name;
        if($variationdata != $attributeNames){
            $productAttributes = array();
            foreach ($attributeNames as $key => $value) {
                if(in_array($key, $languageCodes)){
                    $languageId = $languageIds[$key];
                    if(isset($attribute->options[0]->$key)){
                        $options = $attribute->options[0]->$key;
                    }else{
                        if(isset($attribute->options[0]->en)){
                            $options = $attribute->options[0]->en;
                        }else if (isset($attribute->options[0]->ar)) {
                            $options = $attribute->options[0]->ar;
                        }else if (isset($attribute->options[0]->tr)){
                            $options = $attribute->options[0]->tr;
                        }
                    }
                    $attributeId = $this->model_extension_module_knawat_dropshipping->getAttributeData($value);
                    $productAttributes[$languageId] = array(
                        'text' => $options
                    );
                    $attributeId = (int) $attributeId;
                    $temp['product_attribute'][] = array(
                        'attribute_id'  => $attributeId,
                        'product_attribute_description' => $productAttributes
                    );
                }
            }
        }
    }
}
    /*product code end*/

        /**
         * Setup Product Category.
         */
        //make products get uncategorized in both import and update.

        // if( isset( $product->categories ) && !empty( $product->categories ) ) {
        //     $new_cats = array();
        //     foreach ( $product->categories as $category ) {
        //         if( isset( $category->name ) && !empty( $category->name ) ){
        //             $new_cats[] = (array)$category->name;
        //         }
        //     }
        //     $temp['product_category'] = $this->model_extension_module_knawat_dropshipping->parse_categories( $new_cats );
        // }

        /**
         * Setup Product Images.
         */
        if( isset( $product->images ) && !empty( $product->images ) ) {
            $images = (array)$product->images;
            $product_sku = isset( $product->sku ) ? $product->sku : '';

            $product_images = $this->parse_product_images( $images, $product_sku );
            if( !empty( $product_images ) ){
                $temp['image'] = $product_images[0];
                unset( $product_images[0] );
                if( count( $product_images ) > 0 ){
                    foreach ($product_images as $pimage ) {
                        $temp_image['image'] = $pimage;
                        $temp_image['sort_order'] = '0';
                        $temp['product_image'][] = $temp_image;
                    }
                }
            }
        }

    }else{
        $temp = array();
    }

    if( isset( $product->variations ) && !empty( $product->variations ) ){
        $quantity = 0;
        $price = $product->variations[0]->sale_price;
        if( isset( $product->variations[0]->market_price ) ){
            $market_price = $product->variations[0]->market_price;
        }
        if( empty( $market_price ) ){
            $market_price = $price;
        }
        foreach ( $product->variations as $vvalue ) {
            $quantity += $vvalue->quantity;
        }
        if(isset($product->variations[0]->weight)){
            $weight = $product->variations[0]->weight;
            $temp['weight']     = $weight;
        }
        $temp['price']      = $market_price;
        $temp['quantity']   = $quantity;
        if( $quantity > 0 ){
            $temp['stock_status_id'] = '7';
        }else{
            $temp['stock_status_id'] = '5';
        }
        if(!empty($price)){
            if($price < $market_price){
                $temp['product_special'][] = array(
                    'customer_group_id' => 1,
                    'price'  => $price,
                    'priority' => 1,
                    'date_start' => 0000-00-00,
                    'date_end' => 0000-00-00
                );    
            }
        }
        $temp['product_option'] = $this->model_extension_module_knawat_dropshipping->parse_product_options( $product->variations, $price,$update );
    }
    if(!empty($temp['product_option'])){
        foreach ($temp['product_option'] as $key) {
            $i = 0;
                if(isset($key['product_option_value'])){
                    $j = count($key['product_option_value']);
                }else{
                    $j = 0;
                }
                foreach ($key['product_option_value'] as $value) {
                    if($value['quantity'] == 0){
                        $i++;
                    }
                }
            }
            if($i == $j){
                $temp['stock_status_id'] = '5';
            }
    }
    if(empty($temp['product_option']) && !$update){
         $this->log->write("Product Failed , It's variations not available or available with zero quantity, Sku : ".$temp['sku']);
            return false;
    }
    ///////////////////////////////////
    /////// @TODO Custom Fields ///////
    ///////////////////////////////////
    error_log("Orginal Product: " . json_encode($product));
    error_log("temp Product: " . json_encode($temp));
    return $temp;
}

If anyone can help me with this problem. Thank you


Solution

  • So the answer to this question is as follows:

    editProduct function in CatalogModel class in Opencart removes all relation_id_to_category before beginning to modify an existing product, so in order to not make the attached categories in a product be removed you should comment out this line of code and everything as it should but it may affect other modules working in Opencart so do it at your own risk.