1

Hi I'm pretty new in magento.

I need to create a blank page that, when visited by a client, automatically adds an specific item to the cart in and redirects him to the checkout screen.

How should I approach this scenario?

1

Create a custom page using routes.xml

app/code/Vendor/Module/etc/frontend/routes.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="custom" id="custom">
            <module name="Vendor_Module"/>
        </route>
    </router>
</config>

And your controller must be in below path

app/code/Vendor/Module/Controller/Index/Index.php

<?php
namespace Vendor\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $cart;

    protected $formKey;

    protected $_productRepository;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\Data\Form\FormKey $formKey,
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->cart = $cart;
        $this->formKey = $formKey;
        $this->_productRepository = $productRepository;
        return parent::__construct($context);
    }

    public function execute()
    {
        $productSku =10;
        $product = $this->_productRepository->get($productSku);
        $params = array(
            'form_key' => $this->formKey->getFormKey(),
            'product' => $product->getId(), 
            'qty'   =>1
        );
        $this->cart->addProduct($product, $params);
        $this->cart->save();
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('checkout/index/index');
        return $resultRedirect;
    }
}

You can access the page using {{Your base url}}/custom/index/index

  • I forgot to menction my version of magento is 2.3.3 – Adrian Lopez Dec 12 '19 at 11:35
  • 1
    Did you get any error ? – Ranganathan Dec 12 '19 at 11:37
  • 1
    By default it doesn't....You need to create code folder for creating custom extensions – Ranganathan Dec 12 '19 at 11:40
  • 1
    And vendor means your company name module means your extension name. – Ranganathan Dec 12 '19 at 11:41
  • 1
    Study about How to create an extension here - mageplaza.com/magento-2-module-development/… and apply my answer. It will work – Ranganathan Dec 12 '19 at 11:50

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.