Domanda

I am trying to add product programmatically on catalog_product_save_after observer.

Basically what i try to achieve is create a Duplicate Sample product of current product if PRODUCT-SKU-sample does not exist otherwise Update the price of PRODUCT-SKU-sample Sample product.


Update

Can i use Plugin or interceptor instead of using Observer to create Sample Product on Save Product Event ?


File : Namespace/Modulename/Observer/Catalog/ProductSaveAfter.php

$_product = $observer->getProduct();
$isSampleOrderEnabled = $observer->getProduct()->getData('enable_sample_order');

if($isSampleOrderEnabled == 1){

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();
    $_mediapath = BP.'/pub/media/'. 'catalog/product' . $_product->getImage();
    $imageUrl  =  $store->getBaseDir(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'catalog/product' . $_product->getImage();

    $getProduct = $objectManager->get('Magento\Catalog\Model\Product');
    $sampleSkuExists = $getProduct->getIdBySku($_product->getSku().'-sample');

    $sampleProductPrice = $observer->getProduct()->getData('sample_price');
    if($sampleSkuExists == FALSE) {

        $product = $objectManager->create('Magento\Catalog\Model\Product');
        try {
            $product->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
                    ->setAttributeSetId($_product->getAttributeSetId()) //ID of a attribute set named 'default'
                    ->setTypeId('simple') 
                    ->setCreatedAt(strtotime('now')) 
                    ->setSku($_product->getSku().'-sample') //SKU
                    ->setName($_product->getName()."-sample")
                    ->setWeight(4.0000)
                    ->setStatus(1) 
                    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                    ->setVisibility(1) 
                    ->setPrice($sampleProductPrice) 
                    ->setMetaTitle($_product->getMetaTitle())
                    ->setMetaKeyword($_product->getMetaKeyword())
                    ->setMetaDescription($_product->getMetaDescription())
                    ->setDescription($_product->getDescription())
                    ->setShortDescription($_product->getShortDescription())
                    ->setStockData(
                        array(
                           'use_config_manage_stock' => 0, //'Use config settings' checkbox
                           'manage_stock'=>1, //manage stock
                           'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
                           'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
                           'is_in_stock' => 1, //Stock Availability
                           'qty' => 99999//qty
                        )
                    );

            echo "BEFORE SAVING THE NEW PRODUCT";
            $res = $product->save();
            echo "AFTER SAVING THE NEW PRODUCT";

            var_dump($res); 
            echo $product->getEntityId();
            // Save the new Sample Product ID to original product Attribute. 
        } catch (Exception $e ) {
            echo    $e->getMessage();
        }
    } else {
        echo "UPDATE CODE GOES HERE";
    }
}

I cant get past $product->save();. Code execution stop right there without any notice/error.

Checked all the log files. there is no relevent information there as well.

È stato utile?

Soluzione 2

Solved this by adding conditional logic.
Set the Session variable for session while executing Observer.

$_SESSION['NameSpace']['ModuleName'] = 'Y'; 

And then checked the very first thing in function if session variable exist. And return if value is set

if(isset($_SESSION['NameSpace']['ModuleName']) && $_SESSION['ModuleName']['ModuleName'] == 'Y' ){
    unset($_SESSION['NameSpace']);
    return '';
}

Altri suggerimenti

It is logical an issue in your code.

you have another save()[ $res = $product->save();] function inside call catalog_product_save_after observer.

it make recursive call of your observer. because of save() call catalog_product_save_after which fire again your observer.

That make recursive call of your observer.

So, you should avoid it by some logic

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top