Search code examples
phpdrupaldrupal-modulesdrupal-8drupal-comments

How to display the store name in the shopping cart?


I have a site with Drupal 8.6 and Commerce 2.11

I have several stores belonging to different owners (maketplace).

When a customer how in 2 stores, this will create 2 shopping carts.

How to display above the shopping carts, the name of the store?

I created the 4 files below in a custom module.

My problem :

An authenticated user adds products to his shopping cart, he has a 403 error when he goes to the shopping cart page.

I checked the permissions and they are correctly set.

If I uninstall my custom module, the shopping cart is accessible again.

Why ?

commerce_marketplace_cart.info.yml :

name: Commerce Marketplace Cart
description: Implements Commerce Marketplace Cart.
type: module
core: 8.x
package: Commerce (contrib)
dependencies:
  - commerce:commerce_cart
  - commerce:commerce_product

commerce_marketplace_cart.module :

<?php

/**
 * @file
 * Commerce Marketplace Cart.
 */

commerce_marketplace_cart.routing.yml :

commerce_cart.page:
  path: '/cart'
  defaults:
    _controller: '\Drupal\commerce_marketplace_cart\Controller\MarketplaceCartController::cartPage'
    _title: 'Shopping carts'
  requirements:
    _permission: 'access cart'

In the folder /src/Controller there is the file MarketplaceCartController.php :

<?php

namespace Drupal\commerce_marketplace_cart\Controller;

use Drupal\commerce_cart\Controller\CartController;

/**
 * Overrides the cart page controller.
 */
class MarketplaceCartController extends CartController {

  /**
   * {@inheritdoc}
   */
  public function cartPage() {
    $build = parent::cartPage();
    $carts = $this->cartProvider->getCarts();
    $carts = array_filter($carts, function ($cart) {
      /** @var \Drupal\commerce_order\Entity\OrderInterface $cart */
      return $cart->hasItems();
    });

    if (!isset($build['empty'])) {
      foreach ($build as $key => $value) {
        if (isset($value['#prefix'])) {
          $store_name = $carts[$key]->getStore()->getName();
          $build[$key]['#prefix'] = "<h2 class='cart cart-store-name'>{$store_name}</h2>" . $value['#prefix'];
        }
      }
    }

    return $build;
  }

}

Solution

  • You have given a permission called access_cart. Define this permission in a permission.yml file and assign this permission to the user.