2

I am trying to create a custom button to remove items from the shopping cart.

Example of remove button in cart

I've tried the following code <a href="<?php echo $this->getUrl('checkout/cart/delete', array('id' => $this->getProduct()->getId()))?>"> in vendor\magento\module-checkout\view\frontend\templates\cart\item\default.phtml but it doesn't seem to be working.

I must be putting something in the wrong place or not using correct code but I found this on another post.

Just need a point in the right direction

2 Answers 2

8

You can simply use in app/design/frontend/Vendor/Themename/Magento_Checkout/templates/cart/item/default.phtml below code.

<a href="#"
           title="<?= $block->escapeHtml(__('Remove item')) ?>"
           class="action action-delete"
           data-post='<?= /* @escapeNotVerified */ $this->helper('Magento\Checkout\Helper\Cart')->getDeletePostJson($_item) ?>'>
            <span>
                <?= /* @escapeNotVerified */ __('Remove item') ?>
            </span>
        </a>
1
2

You can use below code.

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cartHelper = $objectManager->create("Magento\Checkout\Helper\Cart");
    $json=$cartHelper->getDeletePostJson($_item);
?>
<a href="#"
   title="<?= $block->escapeHtml(__('Remove item')) ?>"
   class="action action-delete"
   data-post='<?= /* @escapeNotVerified */ $json ?>'>
    <span>
        <?= /* @escapeNotVerified */ __('Remove item') ?>
    </span>
</a>

This code you can put where you need to show delete link. It will remove product from cart.

For more details you can see below Files so you can get idea what we have done above.

vendor/magento/module-checkout/view/frontend/templates/cart/item/renderer/actions/remove.phtml

vendor/magento/module-checkout/Block/Cart/Item/Renderer/Actions/Remove.php
4
  • I have used object manager just for example purpose :) Aug 1, 2018 at 10:09
  • Works like a charm :) I'm guessing I'm going to have to find a way of including the variables needed other than using the object manager?
    – Howliee
    Aug 1, 2018 at 10:11
  • You can inject helper in block and get data in phtml file :) Aug 1, 2018 at 10:26
  • If it is working for you then you may accept answer :) Aug 1, 2018 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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