TransWikia.com

Special Price Not Applying in Magento2 Cart

Magento Asked by Dinesh on December 14, 2020

I am creating simple products through API call. Product is created finely and showing all attributes finely in admin part but when ever i am seeing product in frontend it is not showing any special price. It is directly displaying price.

I am using magento 2.2.4 version. Here is the API code.

   $name = $prod_data['name'];
            $price = $prod_data['price'];
            $category_id = 229;
            $qty = $prod_data['qty'];
            $desc=$prod_data['description'];
            $product->setName($name);
            $product->setTypeId('simple');
            $product->setAttributeSetId(10);
            $product->setSku($sku);
            $product->setWebsiteIds(array(1));
            $product->setVisibility(1);
            $product->setPrice($price);
            //$product->setCategoryIds(array($category_id));
            $product->setDescription($desc);
            $product->setItemCode($prod_data['name']);
            $product->setUrlKey($url_key);
            $product->setStockData(array(
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                    'qty' => $qty
                )
            );
         
          
 

            if ($product->save()) {
            /** add saved file to the $product gallery */
            $categoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
            $categoryIds = array('229');
            $categoryLinkRepository->assignProductToCategories($sku, $categoryIds);
  
            $succ = 1;
            $msg = "Product created successfully";
            $logger->info("SKU Not Existed, So Creating new SKU for ". $prod_data['sku']);
              }else{
                $succ = 0;
                $msg = "Unable to create product";
                 $logger->info("SKU Not Existed, But there is problem in creating sku ". $prod_data['sku']);

              }

For updating special price i used the following code. In admin it is updating finely but final_price in index table is not changing.

if($prod_data['special_price'] > 0){
                       $product2 = $objectManager->get('MagentoCatalogModelProduct')->load($pid);
                    
                      $product2->setSpecialPrice($prod_data['special_price']);
                      $productResource = $objectManager->create('MagentoCatalogModelResourceModelProduct');
                      $productResource->saveAttribute($product2 , 'special_price');
                      $product2->save();

I tried indexer:reindex but no use of it. Cleared cache, verified store id and everything is correct.

But still special price not showing in product detail page as well as cart page. How can i debug it.

2 Answers

I debugged and removed one by one extensions that we installed as well. There is no issue with the code or extensions. The problem is in catalog_product_entity_datetime table it is automatically taken special price end date as special price updated date and time.

So manually i removed those entries from DB and verified the website. Now all the special prices showing finely and for adding special price from and to dates . i modified my code as follows.

$today = date('Y-m-d', time());
                       $nextYear = date('Y-m-d', time() + (60*60*24*7*52));

                       $specialPrice=$prod_data['special_price'];
                       $price=$product2->getPrice();

                       if($specialPrice <='0') {
                          $specialPrice = null;
                          $today = null;
                          $nextYear = null;
                      }
                     
                        $product2->setSpecialPrice($specialPrice);
                        $product2->setOfferCode($prod_data['offer_code']);
                        $product2->setSpecialFromDate($today);
                        $product2->setSpecialFromDateIsFormated(true);
                        $product2->setSpecialToDate($nextYear);
                        $product2->setSpecialToDateIsFormated(true);
                      $productResource = $objectManager->create('MagentoCatalogModelResourceModelProduct');
                      $productResource->saveAttribute($product2 , 'offer_code');
                      $productResource->saveAttribute($product2 , 'special_price');
                      $productResource->saveAttribute($product2, 'special_from_date');
                      $productResource->saveAttribute($product2, 'special_to_date');

Answered by Dinesh on December 14, 2020

As I can see your code might be wrong.

please check following code for set special price programmatically.

use MagentoCatalogApiSpecialPriceInterface;
use MagentoCatalogApiDataSpecialPriceInterfaceFactory;

public function __construct(
    SpecialPriceInterface $specialPrice,
    SpecialPriceInterfaceFactory $specialPriceFactory
) {
    $this->specialPrice = $specialPrice;
    $this->specialPriceFactory = $specialPriceFactory;
}

public function setSpecialPriceData()
{
    $sku = '24-MB01';
    $price = 10.99; //Special Price
    try {
        $priceFrom = '2020-12-01'; // future date to current date
        $priceTo = '2025-10-15'; // future date to price from

        $updateDatetime = new DateTime();
        $priceFrom = $updateDatetime->modify($priceFrom)->format('Y-m-d H:i:s');
        $priceTo = $updateDatetime->modify($priceTo)->format('Y-m-d H:i:s');

        $prices[] = $this->specialPriceFactory->create()
            ->setSku($sku)
            ->setStoreId(0)
            ->setPrice($price)
            ->setPriceFrom($priceFrom)
            ->setPriceTo($priceTo);

        $product = $this->specialPrice->update($prices);
    } catch (Exception $exception) {
        throw new Exception($exception->getMessage());
    }

    return $product;
}

If this answer helps then hit like.

Enjoy your coding :)!!!

Thank you
Hiren Patel

Answered by Hiren Patel on December 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP