Get shopping cart details in Magento2 - magento2

I know in Magento 1 you can get the shopping cart details on any page with:
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
$productId = $item->getProduct()->getId();
$productPrice = $item->getProduct()->getPrice();
}
How do I do the same thing in Magento 2?

protected $_checkoutSession;
public function __construct (
\Magento\Checkout\Model\Session $_checkoutSession
) {
$this->_checkoutSession = $_checkoutSession;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$cartData = $this->_checkoutSession->getQuote()->getAllVisibleItems();
$cartDataCount = count( $cartData );
}
you can get the quote data in observer

I figured this out by myself in the end:
<?php
$om = \Magento\Framework\App\ObjectManager::getInstance();
$cartData = $om->create('Magento\Checkout\Model\Cart')->getQuote()->getAllVisibleItems();
$cartDataCount = count( $cartData );
?>
<div class="bagDrop" id="bagDrop">
<h4>Quote Basket</h4>
<?php if( $cartDataCount > 1 ): ?>
<?php endif; ?>
<div class="bagDropWindow">
<?php if( $cartDataCount > 0 ): ?>
<div class="bagDropList" id="bagDropList">
<?php foreach( $cartData as $item ): ?>
<?php $product = $item->getProduct(); ?>
<?php $image = $product['small_image'] == '' ? '/pub/static/frontend/Clear/usb2u/en_GB/images/default-category-image_1.png' : '/pub/media/catalog/product' . $product['small_image']; ?>
<a href="<?php echo $product['request_path']; ?>" class="bagDropListItem">
<img src="<?php echo $image; ?>">
<p>
<span class="name"><?php echo $product['name']; ?></span><br>
<span class="qty">x <?php echo $item->getQty(); ?></span>
</p>
</a>
<?php endforeach; ?>
</div>
<?php else: ?>
<div class="emptyList">No products in your basket.</div>
<?php endif; ?>
</div>
<?php if( $cartDataCount > 1 ): ?>
<?php endif; ?>
</div>

Get Product Details in Checkout Page
<?php
namespace namespace\modulename\Block\xxx;
class xxx extends \Magento\Framework\View\Element\Template {
public function __construct(
\Magento\Checkout\Model\Cart $cart,
\namespace\modulename\Model\CrossSellFactory $crosssell,
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $data = []
) {
parent::__construct($context, $data);
$this->cart = $cart;
$this->_crosssell = $crosssell;
$this->customerSession = $customerSession;
$this->_objectManager = $objectManager;
}
public function getProductIds()
{
$productInfo = $this->cart->getQuote()->getItemsCollection();
foreach ($productInfo as $item) {
$item[] = $item->getProductId();
echo"<pre>";print_r($item->getProductId());
}
return $item;
}
}
Put the above .php file in your block and return the value in phtml file like i shown below.
<?php
$Productdetails = $block->getProductIds();
echo"<pre>";print_r($Productdetails->getName());
?>

You can easily get the shopping cart details in the Magento 2 by implementing the below-mentioned code:
<?php
$object = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $object->create('Magento\Checkout\Model\Cart')->getQuote()->getAllVisibleItems();
$cartCount = count( $cart );
if($cartCount > 0){
echo $cartCount;
} else{
echo "0" ;
}
?>

Usage examples:
\Magento\Checkout\Block\Cart\AbstractCart::getQuote():
/**
* Get active quote
*
* #return Quote
*/
public function getQuote()
{
if (null === $this->_quote) {
$this->_quote = $this->_checkoutSession->getQuote();
}
return $this->_quote;
}
\Magento\Checkout\Block\Cart\Totals::getQuote():
/**
* Get active or custom quote
*
* #return \Magento\Quote\Model\Quote
*/
public function getQuote()
{
if ($this->getCustomQuote()) {
return $this->getCustomQuote();
}
if (null === $this->_quote) {
$this->_quote = $this->_checkoutSession->getQuote();
}
return $this->_quote;
}
\Magento\Checkout\Helper\Cart::getQuote():
/**
* Retrieve current quote instance
*
* #return \Magento\Quote\Model\Quote
* #codeCoverageIgnore
*/
public function getQuote()
{
return $this->_checkoutSession->getQuote();
}

Related

Magento 2 get order in custom block

I have a custom module which sends email to custom email address after successful purchase. It works well but now I need to get gift message from order.
Here is my Block code
<?php
namespace Test\Test2\Block\Vendor\Shipment;
class Items extends \Magento\Framework\View\Element\Template
{
const DEFAULT_TYPE = 'default';
public function getItemRenderer($type)
{
/** #var \Magento\Framework\View\Element\RendererList $rendererList */
$rendererList = $this->getRendererListName() ? $this->getLayout()->getBlock($this->getRendererListName()) : $this->getChildBlock('renderer.list');
if (!$rendererList) {
throw new \RuntimeException('Renderer list for block "' . $this->getNameInLayout() . '" is not defined');
}
$overriddenTemplates = $this->getOverriddenTemplates() ?: [];
$template = isset($overriddenTemplates[$type]) ? $overriddenTemplates[$type] : $this->getRendererTemplate();
$renderer = $rendererList->getRenderer($type, self::DEFAULT_TYPE, $template);
$renderer->setRenderedBlock($this);
return $renderer;
}
public function getItemHtml(\Magento\Framework\DataObject $item)
{
$block = $this->getItemRenderer($item->getProductType())->setItem($item);
return $block->toHtml();
}
}
and email template .phtml
<?php $_items = $block->getItems() ?>
<?php $_order = $block->getOrder() ?>
<?php if ($_items): ?>
<table class="items email-items shipment-items order-items">
<thead>
<tr>
<th class="item-info">
<?= /* #escapeNotVerified */ __('Items'); ?>
</th>
<th class="item-price">
<?= /* #escapeNotVerified */ __('Price'); ?>
</th>
<th class="item-qty">
<?= /* #escapeNotVerified */ __('Qty'); ?>
</th>
<th class="row-total">
<?= /* #escapeNotVerified */ __('Total'); ?>
</th>
</tr>
</thead>
<?php foreach ($_items as $_item): ?>
<?php
if ($_item->getParentItem()) {
continue;
}
?>
<tbody>
<?= $block->getItemHtml($_item) ?>
</tbody>
<?php endforeach; ?>
</table>
<?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?>
<?php if ($_giftMessage): ?>
<br />
<table class="message-gift">
<tr>
<td>
<h3><?= /* #escapeNotVerified */ __('Gift Message for this Order') ?></h3>
<strong><?= /* #escapeNotVerified */ __('From:') ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?>
<br /><strong><?= /* #escapeNotVerified */ __('To:') ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?>
<br /><strong><?= /* #escapeNotVerified */ __('Message:') ?></strong>
<br /><?= $block->escapeHtml($_giftMessage->getMessage()) ?>
</td>
</tr>
</table>
<?php endif; ?>
<?php endif; ?>
Obviously, I receive this error message:
Uncaught Error: Call to a member function getGiftMessageId()
since my block does not have the method getOrder.
But if I try to copy getOrder method from Magento\Sales\Block\Order\Items:
/**
* Retrieve current order model instance
*
* #return \Magento\Sales\Model\Order
*/
public function getOrder()
{
return $this->_coreRegistry->registry('current_order');
}
with __construct part
/**
* #param \Magento\Framework\View\Element\Template\Context $context
* #param \Magento\Framework\Registry $registry
* #param array $data
* #param \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory|null $itemCollectionFactory
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = [],
\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $itemCollectionFactory = null
) {
$this->_coreRegistry = $registry;
$this->itemCollectionFactory = $itemCollectionFactory ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory::class);
parent::__construct($context, $data);
}
it still shows an error that order object in null. What am I doing wrong? Or how can I obtain order object in my case? Thanks.

validate capcha zend not correct

I have code:
$messages = array();
$isValid = TRUE;
$captcha = $this->_getParam('captcha_code', '');
if ( ! Captcha::validate($captcha)){
$isValid = FALSE;
$messages = array_merge($messages, array('Incorrect capcha.'));
}
}
if ($isValid AND count($messages) == 0) {
.............
}
else {
Captcha::destroy();
}
$this->view->register_messages = $messages;
and view:
<input name="captcha_code" type="text" class="input-text"/>
<?php if (isset($this->register_messages) && count($this->register_messages) > 0): ?>
<div class="alert-3">
<?php foreach ($this->register_messages as $message): ?>
<div><?= $message ?></div>
<?php endforeach; ?>
But when i enter correct capcha, it still showing "Incorrect capcha". I use zend 1
Please help me find this bug. Thanks a lot!

Create Button in last page pagination codeigniter

Hello there I have problem
I wanna create button in my pagination codeIgniter just in last page for submit form
here my code:
Controller:
function index() {
/* pagination config */
$this->load->library('pagination');
$config['base_url'] = site_url('dcm/index');
$config['per_page'] = 6;
$config['num_link'] = 5;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev' ;
$config['total_rows'] = $this->db->get('soal')->num_rows();
/* this my form still have problem but I have different post for this one */
/* if you have any Idea for this please check my Question */
$data['form_action'] = site_url('dcm/index');
$jawab = $this->input->post('jawab');
$id_soal = $this->input->post('id_soal');
$this->dcm_model->inputJawab();
/* */
/* pagination setting */
$this->pagination->initialize($config);
$data['query'] = $this->db->get('soal', $config['per_page'], $this->uri->segment(3));
$data['link'] = $this->pagination->create_links();
$this->load->view('dcm/soal', $data);
}
in view:
<form action="<?php echo $form_action; ?>">
<?php foreach($query->result() as $row) { ?>
<?php echo $row->id_soal . '. ' . $row->soal; ?>
<input type="checkbox" checked="checked" value="<?=$row->id_soal;?>" name="jawab[]" />
<?php } ?>
<?php echo $link; ?>
</form>
<input align="center" type="submit" value="selesai" />
You can check if you are on the last page with this code:
if($this->pagination->cur_page >=
ceil($this->pagination->total_rows / $this->pagination->per_page))
{
$isLastPage = true;
}
else
{
$isLastPage = false;
}
You can pass the $isLastPage variable to your view.

zend paginator invalid url

I trying use zend paginator in my project.
And i have problem-when i trying use paginator in news controller, i have links in paginator on index controller!
<?php
class NewsController extends Zend_Controller_Action
{
/**
*
* #var Model_News_Gateway
*/
protected $_newsGateway;
protected $_newsPerPage = 10;
public function init()
{
$this->_newsGateway = new Model_News_Gateway();
}
public function indexAction()
{
$crit = new ExtZF_Model_Criteria();
$crit->addWhere('active', true);
$crit->addDescOrderBy('publish_date');
$paginator = new Zend_Paginator($this->_newsGateway->getPaginatorAdapter($crit));
$paginator->setCurrentPageNumber($this->_getParam('page', 0));
$paginator->setItemCountPerPage($this->_newsPerPage);
$this->view->paginator = $paginator;
}
In view
$this->paginationControl($this->paginator, 'Sliding', '_partials/paginator/default.phtml');
And in default
<?php if ($this->pageCount && count($this->pagesInRange) > 1): ?>
<!--noindex-->
<div class="paginationControl">
(<?= $this->firstItemNumber ?>-<?= $this->lastItemNumber?>/<?= $this->totalItemCount ?>)
<?php if (isset($this->previous)): ?>
<a href="<?php echo $this->url(array('page' => $this->previous)); ?>">
< <?= $this->translate('previous') ?>
</a> |
<?php else: ?>
<span class="disabled">< <?= $this->translate('previous') ?></span> |
<?php endif; ?>
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?php echo $this->url(array('page' => $page)); ?>">
<?php echo $page; ?>
</a> |
<?php else: ?>
<?php echo $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
<?php if (isset($this->next)): ?>
<a href="<?php echo $this->url(array('page' => $this->next)); ?>">
<?= $this->translate('next') ?> >
</a>
<?php else: ?>
<span class="disabled"><?= $this->translate('next') ?> ></span>
<?php endif; ?>
</div>
<!--/noindex-->
<?php endif; ?>
I am trying use one default paginator for don't same controllers, but i always have links in paginator like /index/index/page/2.
I need links like /news/index/page/2
But i always have links /index/index/page/2
And i in news controller now. I don't understand why it don't work.
<?
//Ужасный хак, мне стыдно за него
$controller = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
function replaceController ($search, $replace, $text)
{
$pos = strpos($text, $search);
$secondPos =strpos ($text, $search, $pos+1);
if ($secondPos !== false) {
return $pos !== false ? substr_replace($text, $replace, $pos, strlen($search)) : $text;
} else {
return $text;
}
}
?>

Type of Flash Messenger in Zend

Is it possible or How can i give a type to a FlashMessage in Zend?
For example
/* This is a "Success" message */
$this -> _helper -> FlashMessenger('You are successfully created a post.');
/* This is an "Error" message */
$this -> _helper -> FlashMessenger('There is an error while creating post.');
/* This is just a "Notification" message */
$this -> _helper -> FlashMessenger('Now you can see your Post');
I think the best way to do this is by using the flashmessenger namespaces:
/* success message */
$this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Post created!');
/* error message */
$this->_helper->FlashMessenger()->setNamespace('error')->addMessage('You have no permissions');
And then in your layout you can get the messages added to each namespace:
<?php $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
<?php if ($flashMessenger->setNamespace('success')->hasMessages()): ?>
<div class="message success">
<?php foreach ($flashMessenger->getMessages() as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($flashMessenger->setNamespace('error')->hasMessages()): ?>
<div class="message error">
<?php foreach ($flashMessenger->getMessages() as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
At one time you used assoc arrays to do this... Im not ure if this is still current or not...
/* This is a "Success" message */
$this -> _helper -> FlashMessenger(array('success' => 'You are successfully created a post.'));
/* This is an "Error" message */
$this -> _helper -> FlashMessenger(array('error' => 'There is an error while creating post.'));
/* This is just a "Notification" message */
$this -> _helper -> FlashMessenger(array('notice' => 'Now you can see your Post'));
It is possible. Sample implementation in described in this blog post:
Zend Framework: View Helper Priority Messenger | emanaton
Excerpt:
class AuthController extends Zend_Controller_Action {
function loginAction() {
. . .
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($this->view->form->isValid($formData)) {
. . .
} else {
$this->view->priorityMessenger('Login failed.', 'error');
}
. . .
}
}
Method signatures in Zend Framework 1.12.x for FlashMessenger:
public function addMessage($message, $namespace = null)
public function getMessages($namespace = null)
public function hasMessages($namespace = null)
public function clearMessages($namespace = null)
So to set messages the following will work:
/* success message */
$this->_helper->flashMessenger()->addMessage('Post created!', 'success');
/* error message */
$this->_helper->flashMessenger()->addMessage('You have no permissions', 'error');
And for the view, the following should work:
<?php $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
<?php if ($flashMessenger->hasMessages('success')): ?>
<div class="message success">
<?php foreach ($flashMessenger->getMessages('success') as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($flashMessenger->hasMessages('error')): ?>
<div class="message error">
<?php foreach ($flashMessenger->getMessages('error') as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>