How to limit the list of stores to my own stores?

by user90437   Last Updated November 08, 2018 19:07 PM

I have a site with Drupal 8.6 and Commerce 2.11

I have a marketplace with several stores and shop owners.

When a store owner creates a product or a payment gateway, I want the list of stores to be limited to their own stores?

I found a code on drupal.org :

https://www.drupal.org/project/commerce/issues/2499645 (comment #16)

I tried to use it in a custom module, but it does not work.

In a commerce_marketplace_view_own_stores folder, I created the following files.

Here is my custom module :

commerce_marketplace_view_own_stores.info.yml :

name: Commerce Marketplace View Own Stores
description: Commerce Marketplace View Own Stores for working with the commerce store module.
type: module
core: 8.x
package: Commerce (contrib)
dependencies:
  - commerce:commerce_store

commerce_marketplace_view_own_stores.module :

<?php

/**
 * @file
 * Commerce Marketplace View Own Stores.
 */

/scr/EventSubscriber/QueryAccessSubscriber.php :

<?php

namespace Drupal\commerce_marketplace_view_own_stores\EventSubscriber;

use Drupal\entity\QueryAccess\ConditionGroup;
use Drupal\entity\QueryAccess\QueryAccessEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class QueryAccessSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      'entity.query_access.commerce_store' => 'onQueryAccess',
    ];
  }

  /**
   * Adds conditions for the "view own" permission.
   *
   * @param \Drupal\entity\QueryAccess\QueryAccessEvent $event
   *   The event.
   */
  public function onQueryAccess(QueryAccessEvent $event) {
    $conditions = $event->getConditions();
    $operation = $event->getOperation();
    $account = $event->getAccount();

    if ($operation != 'view') {
      return;
    }
    // The user already has full access due to a
    // "administer commerce_store" or "view commerce_store"
    // permission.
    if (!$conditions->count() && !$conditions->isAlwaysFalse()) {
      return;
    }

    // Or skip the permission check completely if you want
    // to always restrict the user to viewing their own store.
    if ($account->hasPermission('view own commerce_store')) {
      $conditions->addCacheContexts(['user']);
      $conditions->addCondition('uid', $account->id());
      $conditions->alwaysFalse(FALSE);
    }
  }

}


Related Questions


Updated April 27, 2018 17:07 PM

Updated May 01, 2018 19:07 PM

Updated June 18, 2018 23:07 PM