Tomáš Chylý
Tomáš Chylý

Reputation: 342

Programmatically created configurable product doesnt show on frontend

I have created module that imports products to Magento. It creates both simple and configurable products and adds those simple products to the configurable product. Products are added to their categories by

$product->setCategoryIds($categoryIds);

and just in case I also do this

    foreach($categoryIds as $i=>$v){
            Mage::getSingleton('catalog/category_api')->assignProduct($v, $product->getId());
    }

When I look in backend products have their categories checked, also when I look at categories they have their products added too.

So everything looks fine, but when I go on frontend to category, products are missing from there. Then all I have to do is open the configurable product and/or one of its simple products and WITHOUT changing anything I just hit save and then when I go to frontend the product is visible in category.

Ofcourse cashe is disabled and indexing is run after import is done, so no problem there.

EDIT

This creates the configurable product.

private function createParentProduct($productId){
    if($this->product&&!$productId){//create
        $name=$this->product->sGetName($this->language['value']);
        if(!$name||$name==''){
            return Mage::helper('shirtplugin')->__('failed, missing product name');
        }
        $data=$this->product->sGetData();

        $product = Mage::getModel('Mage_Catalog_Model_Product');
        $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE);
        $product->setTaxClassId($this->taxClass['value']);
        $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        $product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
        $product->setStoreId($this->scope['scopeId']);

        $store=Mage::getModel('Mage_Core_Model_Store')->load($this->scope['scopeId']);
        $product->setWebsiteIDs(array($store->getWebsiteId()));

        $product->setAttributeSetId(4);
        $product->setSku('shirtId-'.$this->product->sGetId());
        $product->setName($name);
        $product->setUrl(Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($name));
        $product->setPrice(floatVal($this->product->sGetPrice($this->language['value'])));
        $product->setCreatedAt(time());
        $product->setDescription($this->product->sGetDescription($this->language['value']));
        $product->setShortDescription($this->product->sGetShortDescription($this->language['value']));

        $product->setData('shirt_artNr', $data['artNr']);
        $product->setShirtModel($data['model']);
        $materials=$this->product->sGetAssignedMaterials();
        $assigMaterials=array();
        foreach($materials as $i=>$v){
            $material=$v->sGetMaterial()->sGetName();
            if(!$material||$material==''){
                continue;
            }
            $assigMaterials[]=$this->addNewValueToAttribute('shirt_material', $material, $v->sGetMaterial()->sGetId());
        }
        $product->setData('shirt_material', $assigMaterials);

        $categoryIds=array();
        $categories=$this->product->sGetAssignedCategories();
        foreach($categories as $i=>$v){
            $category=$v->sGetCategory()->checkIfCategoryExists();
            if($category){
                $categoryIds[]=$category;
            }
        }
        $product->setCategoryIds($categoryIds);

        $product->setStockData(array(
            //'is_in_stock'=>1,
            //'qty'=>null,
            'manage_stock'=>0,
            'use_config_manage_stock'=>0,
            'use_config_enable_qty_increments'=>0,
            //'use_config_notify_stock_qty'=>0,
            'enable_qty_increments'=>0,
        ));

        $newAttributes=array();
        foreach(array('shirt_color', 'shirt_size') as $attrCode){
            $super_attribute=Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$attrCode);
            $configurableAtt=Mage::getModel('catalog/product_type_configurable_attribute')->setProductAttribute($super_attribute);

            $newAttributes[] = array(
                'id'=>$configurableAtt->getId(),
                'label'=>$configurableAtt->getLabel(),
                'position'=>$super_attribute->getPosition(),
                'values'=>array(),
                'attribute_id'=>$super_attribute->getId(),
                'attribute_code'=>$super_attribute->getAttributeCode(),
                'frontend_label'=>$super_attribute->getFrontend()->getLabel(),
            );
        }

        $configurableData=array();
        $colors=$this->product->sGetAssignedColors();
        $sizes=$this->product->sGetAssignedSizes();
        $simpleProducts=array();
        $colorId=Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product','shirt_color')->getId();
        $sizeId=Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product','shirt_size')->getId();
        $filterColors=array();
        $filterSizes=array();
        foreach($colors as $i=>$v){
            $name=$v->sGetColor()->sGetName($this->language['value']);
            if(in_array($name, $filterColors)){
                unset($colors[$i]);
            }else{
                $filterColors[]=$name;

                $newAttributes[0]['values'][]=array(
                    'value_index'=>0,
                    'label'=>$name,
                    'is_percent'=>0,
                    'pricing_value'=>'0',
                    'attribute_id'=>$colorId,
                );
            }
        }
        foreach($sizes as $i=>$v){
            $name=$v->sGetSize()->sGetName($this->language['value']);
            if(in_array($name, $filterSizes)){
                unset($sizes[$i]);
            }else{
                $filterSizes[]=$name;

                $newAttributes[1]['values'][]=array(
                    'value_index'=>0,
                    'label'=>$name,
                    'is_percent'=>0,
                    'pricing_value'=>'0',
                    'attribute_id'=>$sizeId,
                );
            }
        }
        foreach($colors as $i=>$v){
            foreach($sizes as $si=>$sv){
                $clone=null;
                $clone=clone $product;
                $id=$this->createSimpleProduct($clone, $v->sGetColor(), $sv->sGetSize());
                $simpleProducts[$id]=$id;

                $configurableData[$id]=array();
                $configurableData[$id][]=array(
                    'attribute_id'=>$colorId,
                    'label'=>$v->sGetColor()->sGetName($this->language['value']),
                    'value_index'=>$this->addNewValueToAttribute('shirt_color', $v->sGetColor()->sGetName($this->language['value']), $v->sGetColor()->sGetId()),
                );
                $configurableData[$id][]=array(
                    'attribute_id'=>$sizeId,
                    'label'=>$sv->sGetSize()->sGetName($this->language['value']),
                    'value_index'=>$this->addNewValueToAttribute('shirt_size', $sv->sGetSize()->sGetName($this->language['value']), $sv->sGetSize()->sGetId()),
                );
            }
        }
        //echo "<pre>"; var_dump($newAttributes); echo "</pre>"; exit;
        $product->setConfigurableProductsData($configurableData);
        $product->setConfigurableAttributesData($newAttributes);
        $product->setCanSaveConfigurableAttributes(1);

        $product->save();

        foreach($categoryIds as $i=>$v){
            Mage::getSingleton('catalog/category_api')->assignProduct($v, $product->getId());
        }

        $key='importProduct_'.$this->product->sGetId();
        $setting=serialize(array(
            'magentoId'=>$product->getId(),
            'time'=>time()
        ));
        Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin')->saveSetting(Mage::helper('shirtplugin')->getCurrentAdminScope(), $key, $setting);
        $this->return=Mage::helper('shirtplugin')->__('created configurable product with %d simple products', count($simpleProducts));
        return intVal($product->getId());
    }elseif($this->product&&$productId){//update
        $name=$this->product->sGetName($this->language['value']);
        if(!$name||$name==''){
            return Mage::helper('shirtplugin')->__('failed, missing product name');
        }
        $data=$this->product->sGetData();

        $product = Mage::getModel('Mage_Catalog_Model_Product')->load($productId);
        $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE);
        $product->setTaxClassId($this->taxClass['value']);
        $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        $product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
        $product->setStoreId($this->scope['scopeId']);

        $store=Mage::getModel('Mage_Core_Model_Store')->load($this->scope['scopeId']);
        $product->setWebsiteIDs(array($store->getWebsiteId()));

        $product->setAttributeSetId(4);
        $product->setSku('shirtId-'.$this->product->sGetId());
        $product->setName($name);
        $product->setUrl(Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($name));
        $product->setPrice(floatVal($this->product->sGetPrice($this->language['value'])));
        $product->setCreatedAt(time());
        $product->setDescription($this->product->sGetDescription($this->language['value']));
        $product->setShortDescription($this->product->sGetShortDescription($this->language['value']));

        $product->setData('shirt_artNr', $data['artNr']);
        $product->setShirtModel($data['model']);
        $materials=$this->product->sGetAssignedMaterials();
        $assigMaterials=array();
        foreach($materials as $i=>$v){
            $material=$v->sGetMaterial()->sGetName();
            if(!$material||$material==''){
                continue;
            }
            $assigMaterials[]=$this->addNewValueToAttribute('shirt_material', $material, $v->sGetMaterial()->sGetId());
        }
        $product->setData('shirt_material', $assigMaterials);

        $categoryIds=array();
        $categories=$this->product->sGetAssignedCategories();
        foreach($categories as $i=>$v){
            $category=$v->sGetCategory()->checkIfCategoryExists();
            if($category){
                $categoryIds[]=$category;
            }
        }
        $product->setCategoryIds($categoryIds);

        $newAttributes=array();
        foreach(array('shirt_color', 'shirt_size') as $attrCode){
            $super_attribute=Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$attrCode);
            $configurableAtt=Mage::getModel('catalog/product_type_configurable_attribute')->setProductAttribute($super_attribute);

            $newAttributes[] = array(
                'id'=>$configurableAtt->getId(),
                'label'=>$configurableAtt->getLabel(),
                'position'=>$super_attribute->getPosition(),
                'values'=>array(),
                'attribute_id'=>$super_attribute->getId(),
                'attribute_code'=>$super_attribute->getAttributeCode(),
                'frontend_label'=>$super_attribute->getFrontend()->getLabel(),
            );
        }

        $configurableData=array();
        $colors=$this->product->sGetAssignedColors();
        $sizes=$this->product->sGetAssignedSizes();
        $simpleProducts=array();
        $colorId=Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product','shirt_color')->getId();
        $sizeId=Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product','shirt_size')->getId();
        $filterColors=array();
        $filterSizes=array();
        foreach($colors as $i=>$v){
            $name=$v->sGetColor()->sGetName($this->language['value']);
            if(in_array($name, $filterColors)){
                unset($colors[$i]);
            }else{
                $filterColors[]=$name;
            }
        }
        foreach($sizes as $i=>$v){
            $name=$v->sGetSize()->sGetName($this->language['value']);
            if(in_array($name, $filterSizes)){
                unset($sizes[$i]);
            }else{
                $filterSizes[]=$name;
            }
        }
        foreach($colors as $i=>$v){
            foreach($sizes as $si=>$sv){
                $clone=null;
                $clone=clone $product;
                $id=$this->createSimpleProduct($clone, $v->sGetColor(), $sv->sGetSize());
                $simpleProducts[$id]=$id;

                $configurableData[$id]=array();
                $configurableData[$id][]=array(
                    'attribute_id'=>$colorId,
                    'label'=>$v->sGetColor()->sGetName($this->language['value']),
                    'value_index'=>$this->addNewValueToAttribute('shirt_color', $v->sGetColor()->sGetName($this->language['value']), $v->sGetColor()->sGetId()),
                );
                $configurableData[$id][]=array(
                    'attribute_id'=>$sizeId,
                    'label'=>$sv->sGetSize()->sGetName($this->language['value']),
                    'value_index'=>$this->addNewValueToAttribute('shirt_size', $sv->sGetSize()->sGetName($this->language['value']), $sv->sGetSize()->sGetId()),
                );
            }
        }
        $product->setConfigurableProductsData($configurableData);
        //$product->setConfigurableAttributesData($newAttributes);//Shouldnt be needed here in update, but might need future modification
        $product->setCanSaveConfigurableAttributes(1);

        $product->save();

        foreach($categoryIds as $i=>$v){
            Mage::getSingleton('catalog/category_api')->assignProduct($v, $product->getId());
        }

        $key='importProduct_'.$this->product->sGetId();
        $setting=serialize(array(
            'magentoId'=>$product->getId(),
            'time'=>time()
        ));
        Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin')->saveSetting(Mage::helper('shirtplugin')->getCurrentAdminScope(), $key, $setting);
        $this->return=Mage::helper('shirtplugin')->__('updated configurable product with %d simple products', count($simpleProducts));
        return intVal($product->getId());
    }
}

And here is simple product.

private function createSimpleProduct($product, $color, $size){
    $productId=$this->checkIfSimpleProductExists($this->product, $color, $size);
    if(!$productId){//create
        $product->setName($this->product->sGetName($this->language['value']).'-'.$color->sGetName($this->language['value']).'-'.$size->sGetName($this->language['value']));
        $product->setUrl(Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($product->getName()));
        $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE);
        $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        $product->setSku('shirtId-'.$this->product->sGetId().'-'.Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($color->sGetName($this->language['value'])).'-'.Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($size->sGetName($this->language['value'])));
        $product->setWeight(0);

        $product->setData('shirt_color', $this->addNewValueToAttribute('shirt_color', $color->sGetName($this->language['value'])), $color->sGetId());
        $product->setData('shirt_size', $this->addNewValueToAttribute('shirt_size', $size->sGetName($this->language['value'])), $size->sGetId());

        $product->save();

        foreach($categoryIds as $i=>$v){
            Mage::getSingleton('catalog/category_api')->assignProduct($v, $product->getId());
        }

        $key='importProduct_'.$this->product->sGetId().'_'.$color->sGetId().'_'.$size->sGetId();
        $setting=serialize(array(
            'magentoId'=>$product->getId(),
            'time'=>time()
        ));
        Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin')->saveSetting(Mage::helper('shirtplugin')->getCurrentAdminScope(), $key, $setting);
    }else{//update
        $data=$this->product->sGetData();
        $product=Mage::getModel('Mage_Catalog_Model_Product')->load($productId);

        $product->setName($this->product->sGetName($this->language['value']).'-'.$color->sGetName($this->language['value']).'-'.$size->sGetName($this->language['value']));
        $product->setUrl(Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($product->getName()));
        $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE);
        $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        $product->setSku('shirtId-'.$this->product->sGetId().'-'.Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($color->sGetName($this->language['value'])).'-'.Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin_Import')->removeDiacritic($size->sGetName($this->language['value'])));
        $product->setWeight(0);
        $product->setDescription($this->product->sGetDescription($this->language['value']));
        $product->setShortDescription($this->product->sGetShortDescription($this->language['value']));

        $product->setData('shirt_artNr', $data['artNr']);
        $product->setShirtModel($data['model']);
        $materials=$this->product->sGetAssignedMaterials();
        $assigMaterials=array();
        foreach($materials as $i=>$v){
            $material=$v->sGetMaterial()->sGetName();
            if(!$material||$material==''){
                continue;
            }
            $assigMaterials[]=$this->addNewValueToAttribute('shirt_material', $material, $v->sGetMaterial()->sGetId());
        }
        $product->setData('shirt_material', $assigMaterials);
        $product->setData('shirt_color', $this->addNewValueToAttribute('shirt_color', $color->sGetName($this->language['value'])), $color->sGetId());
        $product->setData('shirt_size', $this->addNewValueToAttribute('shirt_size', $size->sGetName($this->language['value'])), $size->sGetId());

        $categoryIds=array();
        $categories=$this->product->sGetAssignedCategories();
        foreach($categories as $i=>$v){
            $category=$v->sGetCategory()->checkIfCategoryExists();
            if($category){
                $categoryIds[]=$category;
            }
        }
        $product->setCategoryIds($categoryIds);

        $product->save();

        foreach($categoryIds as $i=>$v){
            Mage::getSingleton('catalog/category_api')->assignProduct($v, $product->getId());
        }

        $key='importProduct_'.$this->product->sGetId().'_'.$color->sGetId().'_'.$size->sGetId();
        $setting=serialize(array(
            'magentoId'=>$product->getId(),
            'time'=>time()
        ));
        Mage::getModel('PSDCoding_Shirtplugin_Model_Shirtplugin')->saveSetting(Mage::helper('shirtplugin')->getCurrentAdminScope(), $key, $setting);
    }
    if($product->getId()){
        return $product->getId();
    }else{
        return false;
    }
}

Upvotes: 0

Views: 2969

Answers (3)

Tom&#225;š Chyl&#253;
Tom&#225;š Chyl&#253;

Reputation: 342

The problem was that Magento didnt update stock status. So when you create product programmatically dont forget to add at least:

$stockStatus = Mage::getModel('cataloginventory/stock_status');
$stockStatus->assignProduct($product);
$stockStatus->saveProductStatus($product->getId(), 1);

It is also good to create stock item object and use category api to assign products.

Upvotes: 2

Rajiv Ranjan
Rajiv Ranjan

Reputation: 1869

Same issue I have faced earlier. Reindex all solved my issue. You can also try.

Upvotes: 0

user2752661
user2752661

Reputation:

From your description it seems like the products are fine and it's merely a problem of visibility:

$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
// why VISIBILITY_NOT_VISIBLE?

is that intended? should be visible by default.

If that does not work check your values for:

$product->setWebsiteIDs(...) and $product->setStoreId(...) 

Upvotes: 0

Related Questions