3

I've tried many methods over the web including here too but still I can't seem to be able to get items currently in cart, tried checkout sessions cart model, cart helper nothing works, It sometimes work randomly (using same code), anyone have an idea about how can I get items in cart to place them in my custom module view.

Magento 2.2.4

Update :

Mahran/Whatsapp/Block/Display.php

<?php
namespace Mahran\Whatsapp\Block;

class Display extends \Magento\Framework\View\Element\Template {

public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        array $data = [],
        \Magento\Checkout\Model\Session $session
    )
    {
        parent::__construct($context, $data);
        $this->checkoutSession = $session;
       }



public function yourFunction()
{
    echo 'Executed';
    $items = $this->checkoutSession->getQuote()->getAllVisibleItems();
    foreach($items as $item) {

      echo " Product Name :- ".$item->getName();
      echo " Product Name :- ".$item->getSku();
      // You can use $item->getData(), it'll return all the information of cart item 
   }

   return $items;
}


}

And I am calling the function in the view phtml file.

Mahran/Whatsapp/view/frontend/templates/whatsappview.phtml

<?php

/**
 * @var \Mahran\Whatsapp\Block\Display $block
 */
$items = $block->yourFunction();
$string = "Items";
foreach($items as $item){
  $string = $string."*".$item['sku'];
}
?>


    <h1>Checkout via WhatsApp</h1>

   <form id="whatsappForm" action="<?php echo $block->getFormAction() ?>" method="GET">
    <h3>Please enter your information to confirm order via WhatsApp</h3>
    <div class="form-group">
    <label for="fullname">Fullname</label>
    <input type="text" class="form-control" name="fullname" id="fullname" placeholder="Enter name" required="true">
  </div>
  <div class="form-group">
    <label for="address">Address</label>
    <input type="text" class="form-control" name="address" id="address" placeholder="Enter address" required="true">
  </div>
  <div class="form-group">
    <label for="city">City</label>
    <input type="text" class="form-control" name="city" id="city" placeholder="Enter city" required="true">
  </div>
  <input type="hidden" name="message" id="message" value="<?php echo $string; ?>">
  <input type="hidden" name="utm_source" value="whatsapp">
  <input type="hidden" name="utm_medium" value="order">
    <button type="submit" class="btn btn-primary">Submit</button>

</form>
1

You can try below code to get cart items.

public function __construct(
    \Magento\Checkout\Model\Session $session
) {
     $this->checkoutSession = $session;
 }

public function yourFunction()
{
    $items = $this->checkoutSession->getQuote()->getAllVisibleItems();
    $cartItems = [];
    foreach($items as $item) {
      $cartItems[] = [
       'name' => $item->getName(),
       'sku' => $item->getSku(),
       ];
      // You can use $item->getData(), it'll return all the information of cart item 
   }
   return $cartItems;
}

Let me know if you need further help.

  • I've added this to the page block but still no luck what is the best practice to apply this code ? – Mostafa Mahran Nov 25 '18 at 15:16
  • where you want cart items? I mean is there any specific page? – Ramkishan Suthar Nov 25 '18 at 15:18
  • Yes, I am placing the cart items in a view I have in user frontend. – Mostafa Mahran Nov 25 '18 at 15:19
  • can you please let me know where you add this code, you can update it in your question. – Ramkishan Suthar Nov 25 '18 at 15:20
  • Updated the question with requested info. – Mostafa Mahran Nov 25 '18 at 15:25
1

Try to use this below code and check it test.log file in var/log folder.

public function __construct(
    \Magento\Checkout\Model\Session $session
) {
     $this->checkoutSession = $session;
 }

public function yourFunction()
{
    $quoteId = $this->checkoutSession->getQuoteId();
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $itemsIds = [];
    if(!empty($quoteId)){
      $cartItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
      foreach ($cartItems as $cartItem) {
        $itemsIds[] = $cartItem->getProduct()->getId();
      }
      $logger->info('If function call');
    } else {
      $logger->info('Else function call');
    }
    return $itemsIds;
}
  • 2018-11-26T16:52:59+00:00 INFO (6): Else function call – Mostafa Mahran Nov 26 '18 at 16:55
  • If possible observer result sent via whatsapp message? – zus Aug 29 at 10:37
0

try this code

    function getitems(){
       $quote = $this->cartObj->getQuote()->loadByCustomer($customerId);
       $items = $quote->getAllItems();
       $a=array();
       $i=1;

       foreach($items as $item) {
          $a[$i]['ProductId'] = $item->getProductId();
          $a[$i]['ProductName'] = $item->getName();
          $a[$i]['ProductSku'] = $item->getSku();
          $a[$i]['ProductQty'] = $item->getQty();
          $a[$i]['ProductPrice'] = $item->getPrice();
          $i++;            
       }
     }
0

add below code in your file

public function __construct(
     \Magento\Framework\ObjectManagerInterface $_objectManager,
    )
    {
        $this->_objectManager       =   $_objectManager;
    }

    function yourFunction(){
    $cart = $this->_objectManager->get('\Magento\Checkout\Model\Cart')

    // retrieve quote items collection
    $itemsCollection = $cart->getQuote()->getItemsCollection();

    // get array of all items what can be display directly
    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    // retrieve quote items array
     $items = $cart->getQuote()->getAllItems();

    foreach($items as $item) {
         echo 'ID: '.$item->getProductId().'<br />';
         echo 'Name: '.$item->getName().'<br />';
         echo 'Sku: '.$item->getSku().'<br />';
         echo 'Quantity: '.$item->getQty().'<br />';
         echo 'Price: '.$item->getPrice().'<br />';
         echo "<br />";            
      }
    }

I hope it help...!!!

  • Tried this didn't work too, it seems impossible to get it to work. – Mostafa Mahran Nov 25 '18 at 19:06
0

Can you try by replacing

\Magento\Backend\Block\Template\Context $context

with

\Magento\Framework\View\Element\Template\Context $context

in your __construct method.

Please remove generated/code files after updating the dependency.

Not verified but should work.

Updates

Update mentioned files with given code below:

Mahran\Whatsapp\Block\Display.php

<?php
namespace Mahran\Whatsapp\Block;

class Display extends \Magento\Framework\View\Element\Template 
{
    protected $cart;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Checkout\Model\Cart $cart,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    )
    {
        $this->cart = $cart;
        $this->_logger = $logger;
        parent::__construct($context, $data);
    }



    public function getCartItems()
    {
        $items = null;
        try{
            $items = $this->cart->getQuote()->getAllVisibleItems(); 
        }catch(\Exception $e){
            $this->_logger->debug($e->getMessage());
        }

        return $items;
    }
}

Mahran/Whatsapp/view/frontend/templates/whatsappview.phtml

<?php
$items = $block->getCartItems();
$string = "Items";
if($items != "null")
{
   foreach($items as $item){
     echo $string = $string."*".$item->getSku()."<br />";
   }
}
?>


    <h1>Checkout via WhatsApp</h1>

   <form id="whatsappForm" action="<?php echo $block->getFormAction() ?>" method="GET">
    <h3>Please enter your information to confirm order via WhatsApp</h3>
    <div class="form-group">
    <label for="fullname">Fullname</label>
    <input type="text" class="form-control" name="fullname" id="fullname" placeholder="Enter name" required="true">
  </div>
  <div class="form-group">
    <label for="address">Address</label>
    <input type="text" class="form-control" name="address" id="address" placeholder="Enter address" required="true">
  </div>
  <div class="form-group">
    <label for="city">City</label>
    <input type="text" class="form-control" name="city" id="city" placeholder="Enter city" required="true">
  </div>
  <input type="hidden" name="message" id="message" value="<?php echo $string; ?>">
  <input type="hidden" name="utm_source" value="whatsapp">
  <input type="hidden" name="utm_medium" value="order">
    <button type="submit" class="btn btn-primary">Submit</button>

</form>

Remove generation files and check with it. Let me know if still it doesn't work.

  • I still can't seem to get the items in the page I can see the items in minicart but they dont appear on the page. – Mostafa Mahran Nov 25 '18 at 17:16
  • Check my updated answer and try with it. – Himmat Paliwal Nov 26 '18 at 6:22
  • @Mostafa Mahran Did that work for you? – Himmat Paliwal Nov 27 '18 at 13:03
0

All of your solutions would work just fine, the problem was full page cache which was affecting the current session make sure to add cacheable=false in the block layout xml file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.