I have Drupal 8 and Commerce 2. I created a "Merchant" and "Premium Merchant" role. By default, users who create a store have the "Merchant" role.
What I am trying to do is the following.
- If the user has the "Merchant" role, the "Add to Cart" button on his products is deactivated for all users and visitors
- If the user has the "Premium Merchant" role, the "Add to Cart" button on his products is activated for all users and visitors
How do I activate or deactivate the "Add to cart" button of a store's products according to the role of the store owner?
The Rules module is of no use because it has been in development for several years and is still not usable.
To summarize, the rule should be:
- If the shop owner has the role "Premium Merchant", the products of his stores are purchasable
- If the shop owner has the role "Merchant", the products of his stores are not purchasable
I also installed the Commerce Add To Cart Link module, which may be useful in my use case.
Option 1
In template files, may have conditions like the following.
{% if logged_in %}
...
{% else %}
...
{% endif %}
I discover programming. Can we write the rules of my questions in a template file?
<div{{ attributes }}>
<a href="{{ url }}" class="add-to-cart-link" data-variation="{{ product_variation.id }}">{{ 'Add to cart'|t }}</a>
</div>
https://twig.symfony.com/doc/2.x/tags/if.html
Option 2
I'm trying to create a custom module, but I do not know how to do it.
commerce_add_to_cart_access.info.ymlname: 'Commerce Add To Cart Access'
type: module
description: "Commerce Add To Cart Access for working with the commerce cart module."
# core: 8.x
package: Commerce
dependencies:
- commerce:commerce_cart
- commerce:commerce_product
# Information added by Drupal.org packaging script on 2018-10-25
version: '8.x-1.0'
core: '8.x'
project: 'commerce_add_to_cart_link'
datestamp: 1524519795
commerce_add_to_cart_access.module
<?php
/**
* @file
* Hook implementations of commerce_add_to_cart_access module.
*/
use Drupal\commerce_product\Entity\ProductType;
use Drupal\commerce_product\Entity\ProductVariationType;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
/**
* Implements ????? for commerce_product_variation.
*/
function ????? {
/** @var \Drupal\commerce_store\CurrentStoreInterface $current_store */
$current_store = \Drupal::service('commerce_store.current_store');
$owner = $current_store->getStore()->getOwner();
$build['add_to_cart_link']['#access'] = $owner->hasRole('premium_merchant');
$form['access_denied'] = ['#markup' => t('No online sales'),];
}