magento2 – Limit Cart Items to Add in Cart

I want to limit cart items to be added in cart.
Limit Checkout Order or Add to Cart Limit to allow only 6 type of items.
These 6 items can have variable Qty value.

I have done the below code using Event/Observer but not working.

etc/events.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_add">
        <observer name="ishaq_limit_items_in_cart_checkout_before" instance="IshaqLimitCartItemsObserverCheckoutCartAdd" />
    </event>
</config>

Observer/Checkout/Cart/Add.php

<?php

namespace IshaqLimitCartItemsObserverCheckoutCart;

use MagentoCheckoutModelSession;
use MagentoFrameworkAppActionFlag;
use MagentoFrameworkAppResponseRedirectInterface as ResponseRedirect;
use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkMessageManagerInterface as MessageManager;

class Add implements ObserverInterface
{
    /** @var Session $session */
    private $session;

    /** @var ActionFlag $flag */
    private $flag;

    /** @var ResponseRedirect $redirect */
    private $redirect;

    /** @var MessageManager $messageManager */
    private $messageManager;

    /**
     * Add constructor.
     *
     * @param Session          $session
     * @param ActionFlag       $flag
     * @param ResponseRedirect $redirect
     * @param MessageManager   $messageManager
     */
    public function __construct(
        MagentoFrameworkAppRequestInterface $request,
        MagentoCheckoutModelCart $cart,
        ResponseRedirect $redirect,
        MessageManager $messageManager
    ) {
        $this->_request        = $request;
        $this->_cart           = $cart;
        $this->redirect        = $redirect;
        $this->messageManager  = $messageManager;
    }

    /**
     * @param Observer $observer
     *
     * @return $this|void
     * @throws MagentoFrameworkExceptionLocalizedException
     * @throws MagentoFrameworkExceptionNoSuchEntityException
     */
    public function execute(Observer $observer)
    {
        $controller = $observer->getControllerAction();
        $postValues = $this->_request->getPostValue();
        $cartQuote = $this->_cart->getQuote()->getData();
        $cartItemsCount = $this->_cart->getQuote()->getItemsCount();
        $cartItemsAll = $this->_cart->getQuote()->getAllItems();
 
        if($cartItemsCount > 6)
        {
            $observer->getRequest()->setParam('product', false);
            $observer->getRequest()->setParam('return_url', $this->redirect->getRefererUrl());
            $observer->getRequest()->setParam('backUrl', $this->redirect->getRefererUrl());
            $this->messageManager->addErrorMessage(
                __('Only 6 types of products per purchase allowed. Please complete this order first and place another order afterwards.')
            );
        }
    }
}


magento2 – Setting Up Custom URLs For Each Option/Swatch of a Variable Product

A client wanted to setup where he sells fabric and related stuff and wanted each variation on a different URL.

So example, he sells a shirt with the colors red, blue, and black. Upon landing on the product page, the URL would be: http://example.com/base-t-shirt and upon clicking on a color, it would be http://example.com/base-t-shirt/red (where the “red” after the base-t-shirt/ is the option SKU or whatever identifier)

I believe that this is not a native feature of Magento but is there any workaround?

magento2 – in env.php correct?

I have noticed that when I run bin/magento index:reindex && bin/magento cache:flush my cache folder continues to grow until the server runs out of space (around 350GB).

The only thing I have changed is adding consumers to the env.php file.

Can someone confirm that the following is correct

'queue' => (
        'amqp' => (
            'host' => 'hidden',
            'port' => 'hidden',
            'user' => 'hidden',
            'password' => 'hidden',
            'virtualhost' => "https://magento.stackexchange.com/"
        )
    ),
    'cron_consumers_runner' => (
        'cron_run' => true,
        'max_messages' => 2000,
        'only_spawn_when_message_available' => 1,
        'maxIdleTime' => 5,
        'consumers' => (
            'product_action_attribute.update',
            'product_action_attribute.website.update',
            'exportProcessor',
            'inventory.source.items.cleanup',
            'inventory.mass.update',
            'inventory.reservations.cleanup',
            'inventory.reservations.update',
            'media.storage.catalog.image.resize',
            'codegeneratorProcessor',
            'import_export.import_db',
            'inventory.reservations.updateSalabilityStatus',
            'inventory.indexer.sourceItem',
            'inventory.indexer.stock',
            'media.content.synchronization',
            'media.gallery.synchronization',
            'async.operations.all',
            'import_export.import_amqp'
        )
    ),

The server is running Litespeed, Magento 2.4.1 and RabbitMQ.

Thanks

magento2 – Magento 2 – Ko Js – Multiple Instance of component in the same page

I am trying to add two templates with the same component, but i need that each template do not share observables and computed this with the other template. I need each one have it own instance of the component.

Is it possible? i spend some hours and i could not find the solution even in this forum.

    <div id="inbox" class="inbox-wrapper" data-bind="scope:'inbox'">
    <div class="inbox" data-bind="click: toggle">
        <i class="fas fa-envelope fa-lg"></i>
        <span class="counter" data-bind="text: messageCount, visible: messageCount, css: pop" style="display: none;"></span>
    </div>
    <!-- ko template: getTemplate() --><!-- /ko -->
</div>
<div id="notifications" class="inbox-wrapper" data-bind="scope:'notifications'">
    <div class="inbox" data-bind="click: toggle">
        <i class="fas fa-bell fa-lg"></i>
        <span class="counter" data-bind="text: messageCount, visible: messageCount, css: pop" style="display: none;"></span>
    </div>
    <!-- ko template: getTemplate() --><!-- /ko -->
</div>
<script type="text/x-magento-init">
    {
        "#notifications": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "notifications": {
                        "component": "Digibart_Notifications/js/component/notifications",
                        "template": "Digibart_Notifications/notifications",
                        "identifier": "<?= $block->getIdentifier(); ?>",
                        "options": <?= $block->getJsonOptions();?>,
                        "elementsId": "#notifications"
                    }
                }
            }
        },
        "#inbox": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "inbox": {
                        "component": "Digibart_Notifications/js/component/notifications",
                        "template": "Digibart_Notifications/inbox",
                        "identifier": "<?= $block->getIdentifier(); ?>",
                        "options": <?= $block->getJsonOptions();?>,
                        "elementsId": "#inbox"
                    }
                }
            }
        }
    }
    </script>

magento2 – Linking InsertListings – Magento Stack Exchange

I have two database tables, zones and rules. The rules includes a foreign key to the zones table (i.e. zone_id) and I wish to create an admin form to edit these.

The zone edit form includes the various fields of the zone in one fieldset and an insertListings ui component in another. At the moment the rules listings shows all listings, for every single zone, but I want to limit this to the zone that is being editted.

How do I connect the insertListings to only show the rules associated with the id of the form?

Any help will be appreciated.

magento2 – Magento 2 set product image role programmatically

Hello and this is my code:

$imgURL = 'path/to/my/image.png';
$fileSystem = $objectManager->create('MagentoFrameworkFilesystem');
$mediaPath = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath();

$product->addImageToMediaGallery($mediaPath.'catalog/product'.$data('thumbnail_image'),('thumbnail', 'swatch'), false, false);
$product->setThumbnail($mediaPath.'catalog/product'.$imgURL);
$product->save();

What I want to achive, is to assign programmatically and image and set it as a thumbnail.
The above code, uploads the image, but it’s role: the thumbnail and swatch are not selected. Not sure why ? See img:
enter image description here

Can you tell me what am i doing wrong ? thank you

magento2 – Applied Theme not showing on store

I have created 2 custom themes for the site, and applied one of theme as the theme store.
But my webpage/store is loading the layout of the theme which is not been applied. I have been struggling with this since 2 days, still no luck.

I have tried to modify the theme table from the db as well where I made all the types to 0. cleared caches n number if times, removed pub/static/frontend folder, Even if I delete the theme it is not loading the layout of the applied theme.

Anything which I have not tried yet?

magento version: 2.4.1

magento2 – How to add Item Status to order confirmation email Magento 2.3.1

Is there a way to add the Item status (Ordered/Backordered) to the order confirmation email?

I tried below code.

getQtyBackordered()): ?>
getQtyBackordered()*1 ?> Backordered.

<?php endif; ?>

It displayed below value:

enter image description here

But it should be ordered and backordered.
https://prnt.sc/wr9jez

magento2 – Migrating code & data from 1.9 to 2

Our site is currently running in PHP 5.4 with Magento 1.9. I want to migrate the site to the latest version of Magento along with PHP 7.

We have created & used a lot of custom modules & using a custom theme.

What is the best & easiest way to migrate the code & data?

Also, I’ve come across official “code migration” tool, but it is leading to 404 page. Is this link outdated? Is there any new document available for code migration?

Thanks in advance.

magento2 – Magento 2 How to override MagentoCatalogBlockProductView to add getStoreCode () function

I need to overwrite the block MagentoCatalogBlockProductView to add the getStoreCode () function and be able to call it from a phtml file that uses this block.
I have followed a tutorial to create a module that does this, but I am getting the following error on the product page:

1 exception(s):
Exception #0 (MagentoFrameworkExceptionRuntimeException): Type Error occurred when creating object: VendorIconosPorIdiomasBlockRewriteProductViewInterceptor

I put all the code of my module below in case someone can tell me what I’m doing wrong.

VendorIconosPorIdiomasregistration.php

<?php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Vendor_IconosPorIdiomas',
__DIR__
);

VendorIconosPorIdiomasetcmodule.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Vendor_IconosPorIdiomas" setup_version="1.0.0">
</module>
</config>

VendorIconosPorIdiomasetcdi.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogBlockProductView" type="VendorIconosPorIdiomasBlockRewriteProductView" />
</config>

VendorIconosPorIdiomasBlockRewriteProductView I have just copied the View class and added the StoreManagerInterface class to the constructor and the getStoreCode () function

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace VendorIconosPorIdiomasBlockRewriteProduct;

use MagentoCatalogApiProductRepositoryInterface;
use MagentoCatalogModelCategory;
use MagentoStoreModelStoreManagerInterface;

/**
 * Product View block
 * @api
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 * @since 100.0.2
 */
class View extends MagentoCatalogBlockProductView
{
    /**
     * Magento string lib
     *
     * @var MagentoFrameworkStdlibStringUtils
     */
    protected $string;

    /**
     * @var MagentoFrameworkJsonEncoderInterface
     */
    protected $_jsonEncoder;

    /**
     * @var MagentoFrameworkPricingPriceCurrencyInterface
     * @deprecated 102.0.0
     */
    protected $priceCurrency;

    /**
     * @var MagentoFrameworkUrlEncoderInterface
     */
    protected $urlEncoder;

    /**
     * @var MagentoCatalogHelperProduct
     */
    protected $_productHelper;

    /**
     * @var MagentoCatalogModelProductTypesConfigInterface
     */
    protected $productTypeConfig;

    /**
     * @var MagentoFrameworkLocaleFormatInterface
     */
    protected $_localeFormat;

    /**
     * @var MagentoCustomerModelSession
     */
    protected $customerSession;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @param Context $context
     * @param MagentoFrameworkUrlEncoderInterface $urlEncoder
     * @param MagentoFrameworkJsonEncoderInterface $jsonEncoder
     * @param MagentoFrameworkStdlibStringUtils $string
     * @param MagentoCatalogHelperProduct $productHelper
     * @param MagentoCatalogModelProductTypesConfigInterface $productTypeConfig
     * @param MagentoFrameworkLocaleFormatInterface $localeFormat
     * @param MagentoCustomerModelSession $customerSession
     * @param ProductRepositoryInterface|MagentoFrameworkPricingPriceCurrencyInterface $productRepository
     * @param MagentoFrameworkPricingPriceCurrencyInterface $priceCurrency
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param array $data
     * @codingStandardsIgnoreStart
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        MagentoCatalogBlockProductContext $context,
        MagentoFrameworkUrlEncoderInterface $urlEncoder,
        MagentoFrameworkJsonEncoderInterface $jsonEncoder,
        MagentoFrameworkStdlibStringUtils $string,
        MagentoCatalogHelperProduct $productHelper,
        MagentoCatalogModelProductTypesConfigInterface $productTypeConfig,
        MagentoFrameworkLocaleFormatInterface $localeFormat,
        MagentoCustomerModelSession $customerSession,
        ProductRepositoryInterface $productRepository,
        MagentoFrameworkPricingPriceCurrencyInterface $priceCurrency,
        MagentoStoreModelStoreManagerInterface $storeManager,
        array $data = ()
    ) {
        $this->_productHelper = $productHelper;
        $this->urlEncoder = $urlEncoder;
        $this->_jsonEncoder = $jsonEncoder;
        $this->productTypeConfig = $productTypeConfig;
        $this->string = $string;
        $this->_localeFormat = $localeFormat;
        $this->customerSession = $customerSession;
        $this->productRepository = $productRepository;
        $this->priceCurrency = $priceCurrency;
        $this->_storeManager = $storeManager;
        parent::__construct(
            $context,
            $data
        );
    }

    // @codingStandardsIgnoreEnd

    /**
     * Get Store code
     *
     * @return string
     */
    public function getStoreCode()
    {
        return $this->_storeManager->getStore()->getCode();
    }

    /**
     * Return wishlist widget options
     *
     * @return array
     * @deprecated 101.0.1
     */
    public function getWishlistOptions()
    {
        return ('productType' => $this->getProduct()->getTypeId());
    }

    /**
     * Retrieve current product model
     *
     * @return MagentoCatalogModelProduct
     */
    public function getProduct()
    {
        if (!$this->_coreRegistry->registry('product') && $this->getProductId()) {
            $product = $this->productRepository->getById($this->getProductId());
            $this->_coreRegistry->register('product', $product);
        }
        return $this->_coreRegistry->registry('product');
    }

    /**
     * Check if product can be emailed to friend
     *
     * @return bool
     */
    public function canEmailToFriend()
    {
        return false;
    }

    /**
     * Retrieve url for direct adding product to cart
     *
     * @param MagentoCatalogModelProduct $product
     * @param array $additional
     * @return string
     */
    public function getAddToCartUrl($product, $additional = ())
    {
        if ($this->hasCustomAddToCartUrl()) {
            return $this->getCustomAddToCartUrl();
        }

        if ($this->getRequest()->getParam('wishlist_next')) {
            $additional('wishlist_next') = 1;
        }

        $addUrlKey = MagentoFrameworkAppActionInterface::PARAM_NAME_URL_ENCODED;
        $addUrlValue = $this->_urlBuilder->getUrl('*/*/*', ('_use_rewrite' => true, '_current' => true));
        $additional($addUrlKey) = $this->urlEncoder->encode($addUrlValue);

        return $this->_cartHelper->getAddUrl($product, $additional);
    }

    /**
     * Get JSON encoded configuration which can be used for JS dynamic price calculation depending on product options
     *
     * @return string
     */
    public function getJsonConfig()
    {
        /* @var $product MagentoCatalogModelProduct */
        $product = $this->getProduct();

        if (!$this->hasOptions()) {
            $config = (
                'productId' => $product->getId(),
                'priceFormat' => $this->_localeFormat->getPriceFormat()
            );
            return $this->_jsonEncoder->encode($config);
        }

        $tierPrices = ();
        $priceInfo = $product->getPriceInfo();
        $tierPricesList = $priceInfo->getPrice('tier_price')->getTierPriceList();
        foreach ($tierPricesList as $tierPrice) {
            $tierPrices() = $tierPrice('price')->getValue() * 1;
        }
        $config = (
            'productId'   => (int)$product->getId(),
            'priceFormat' => $this->_localeFormat->getPriceFormat(),
            'prices'      => (
                'oldPrice'   => (
                    'amount'      => $priceInfo->getPrice('regular_price')->getAmount()->getValue() * 1,
                    'adjustments' => ()
                ),
                'basePrice'  => (
                    'amount'      => $priceInfo->getPrice('final_price')->getAmount()->getBaseAmount() * 1,
                    'adjustments' => ()
                ),
                'finalPrice' => (
                    'amount'      => $priceInfo->getPrice('final_price')->getAmount()->getValue() * 1,
                    'adjustments' => ()
                )
            ),
            'idSuffix'    => '_clone',
            'tierPrices'  => $tierPrices
        );

        $responseObject = new MagentoFrameworkDataObject();
        $this->_eventManager->dispatch('catalog_product_view_config', ('response_object' => $responseObject));
        if (is_array($responseObject->getAdditionalOptions())) {
            foreach ($responseObject->getAdditionalOptions() as $option => $value) {
                $config($option) = $value;
            }
        }

        return $this->_jsonEncoder->encode($config);
    }

    /**
     * Return true if product has options
     *
     * @return bool
     */
    public function hasOptions()
    {
        if ($this->getProduct()->getTypeInstance()->hasOptions($this->getProduct())) {
            return true;
        }
        return false;
    }

    /**
     * Check if product has required options
     *
     * @return bool
     */
    public function hasRequiredOptions()
    {
        return $this->getProduct()->getTypeInstance()->hasRequiredOptions($this->getProduct());
    }

    /**
     * Define if setting of product options must be shown instantly.
     * Used in case when options are usually hidden and shown only when user
     * presses some button or link. In editing mode we better show these options
     * instantly.
     *
     * @return bool
     */
    public function isStartCustomization()
    {
        return $this->getProduct()->getConfigureMode() || $this->_request->getParam('startcustomization');
    }

    /**
     * Get default qty - either as preconfigured, or as 1.
     *
     * Also restricts it by minimal qty.
     *
     * @param null|MagentoCatalogModelProduct $product
     * @return int|float
     */
    public function getProductDefaultQty($product = null)
    {
        if (!$product) {
            $product = $this->getProduct();
        }

        $qty = $this->getMinimalQty($product);
        $config = $product->getPreconfiguredValues();
        $configQty = $config->getQty();
        if ($configQty > $qty) {
            $qty = $configQty;
        }

        return $qty;
    }

    /**
     * Get container name, where product options should be displayed
     *
     * @return string
     */
    public function getOptionsContainer()
    {
        return $this->getProduct()->getOptionsContainer() == 'container1' ? 'container1' : 'container2';
    }

    /**
     * Check whether quantity field should be rendered
     *
     * @return bool
     */
    public function shouldRenderQuantity()
    {
        return !$this->productTypeConfig->isProductSet($this->getProduct()->getTypeId());
    }

    /**
     * Get Validation Rules for Quantity field
     *
     * @return array
     */
    public function getQuantityValidators()
    {
        $validators = ();
        $validators('required-number') = true;
        return $validators;
    }

    /**
     * Return identifiers for produced content
     *
     * @return array
     */
    public function getIdentities()
    {
        $identities = $this->getProduct()->getIdentities();

        return $identities;
    }

    /**
     * Retrieve customer data object
     *
     * @return int
     */
    protected function getCustomerId()
    {
        return $this->customerSession->getCustomerId();
    }
}

VendorIconosPorIdiomasviewfrontendlayoutcatalog_product_view.xml

<?xml version="1.0"?>

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>     
      <referenceBlock name="product.detail.info" remove="true"/>   
       <referenceContainer name="content">
           <block class="MagentoCatalogBlockProductView" name="product.detail.info" as="product_detail_info" template="Vendor_IconosPorIdiomas::detail_layout.phtml" after="-" />
       </referenceContainer>
   </body>
</page>

And finally in my VendorIconosPorIdiomasviewfrontendtemplatesdetail_layout.phtml file I have added:

<?php echo $block->getStoreCode()?>

I appreciate any help.