cancel
Showing results for 
Search instead for 
Did you mean: 

Buy Sample Button on Magento2

   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

Buy Sample Button on Magento2

Hello,

 

I want to implement buy sample button on magento2 product details page. I added my phtml file to display a button. Now i want to know user clicked on Buy Sample button or Add to Cart.

 

I tried to implement following controller but its not changing default product price to my sample product price. How can i do it? Please guide me. My controller function as follows.

 

public function execute()
    {

         $post = $this->getRequest()->getPostValue();
         //echo ' in post';exit;

          $cart = $this->_objectManager->create ('Magento\Checkout\Model\Cart');
      try{
         
           
            
             $productobj = $this->_objectManager->create ('Magento\Catalog\Model\Product' )->load ($post['product']);
            
             $params = array(
                  'product' => $post['product'], // This would be $product->getId()
                  'qty' => 2,
                  'price'=>10
                 
              
              );

              if(!$productobj->getId())
              {
                $this->messageManager->addError(__('Product Does Not Exist. Contact Administrator'));
              }
                   $price=$productobj->getSampleCost();
                    $new_price = $productobj->getSampleCost();
                    //$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
                    
                    //$productobj->setName($new_name);
                    $productobj->setCustomPrice($new_price);
                    $productobj->setOriginalCustomPrice($new_price);
                    $productobj->getProduct()->setIsSuperMode(true);
              //$cart->truncate();
              $cart->addProduct($productobj,$params);
            
              
        
          $cart->save();
          if (!$cart->getQuote()->getHasError()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $productobj->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
          }
      }
      catch(\Exception $e)
      {
        $this->messageManager->addException($e, __($e->getMessage()));
      }    

  }
1 REPLY 1

Re: Buy Sample Button on Magento2

Hello @dineshprim

 

https://github.com/prince108/Magento2-Buynow

Use this module. Install it by copying into your Magento.

 

Run below commands:

php bin/magento cache:clean
php bin/magento setup:upgrade

If still doesn't work:

 

php bin/magento setup:di:compile

If this response was helpful to you, kudos it.

Manish Mittal
https://www.manishmittal.com/