I need to change price according to the role of the user.
In drupal 7 there was a rules solution
But now rules can't support calculate sell price etc...
Can you give me the best approach for doing this.

I have create a new field in Product variation types which is "role" en entity reference of the user role.
So I can create price with role attribute, but how to display only prices according to the user role ?

Comments

zorax created an issue. See original summary.

bojanz’s picture

zorax’s picture

thank's a lot it works !

<?php
namespace Drupal\prix_role\Service;

use Drupal\commerce\Context;
use Drupal\commerce\PurchasableEntityInterface;
use Drupal\commerce_price\Resolver\PriceResolverInterface;
use Drupal\commerce_price\Price;
use \Drupal\user\Entity\User;

/**
 * Returns the price based on the current user being a role user.
 */
class PrixRoleResolver implements PriceResolverInterface {
  /**
   * {@inheritdoc}
   */
  public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
    $current_user_id = \Drupal::currentUser()->id();
    $account = User::load($current_user_id);

    if ($account->hasRole('biocoop')) {
      $role_price = $entity->get('field_prix_biocoop');
      return new Price($role_price->number, $role_price->currency_code);
    }

    return $entity->getPrice();
  }
}
Bala.addweb’s picture

You can use Commerce Pricelist for that. In further option;

- Load the product with commerce_product_load($product_id);
- Get User Role and decide Price for that.
- Change Unit price (commerce_price) of loaded product related to new decided price.

Hope this helps you.

bojanz’s picture

Status: Active » Fixed

@nikunj.addweb
You're replying to a D8 issue with D7 advice.

Bala.addweb’s picture

Pricelist is now available for Drupal 8.

For customization, you can get help from here

load any product with;
    // Loading is based off of the primary key [Integer]
    $product = \Drupal\commerce_product\Entity\Product::load('ACTUAL PRODUCT ID'); 

    with the help of that get varions of that product's variantion with the help of;
    // Loading is based off of the primary key [Integer]
    $variation = \Drupal\commerce_product\Entity\ProductVariation::load('ACTUAL PRODUCT VARIANCE ID');
    and $variation->price->number = 'Your Price'

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

zorax’s picture

thanks for your answer, but I will try without pricelist (even if it sounds good ).
But I have another question, all prices displayed on the site are now function of the role user.
But When the administrator need to create order with certain price list based on the customer role how can I do that ?
I wonder if masquerade will do the job, but the administrator will have to switch between different connection it will be a nightmare...
I probably need to :
1 - alter the order form
2 - get the client role
3 - apply price of that role