0

Getting my feet wet with price resolvers, and I have figured out how to set a new price for all entities that have field_discount_percentage. I am then getting the price and multiplying it for the sake of this example by .95 to get a 5% discount.

public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && $entity->hasField('field_discount_percentage')) {
    return $entity->getPrice()->multiply('0.95');
  }
}

What I trying to do, is to use ->getValue or ->getString for the field_dicount_percentage so that I can set the percentage value in the field from the front end.

public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && $entity->hasField('field_discount_percentage')) {

    //here is where i would like to create a variable for the number value of the field, but I get lost...
    $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];

    // I have also tried this
    $discount = $entity->get('field_discount_percentage')->getString();

    return $entity->getPrice()->multiply($discount);
  }
}

I am getting empty quotes back from $discount = $entity->get('field_discount_percentage')->getString(); which is making me wonder if I cannot use a variable to a numerical field value.

InvalidArgumentException: The provided value "" is not a numeric value. in Drupal\commerce_price\Calculator::assertNumberFormat() (line 261 of MY-Site\web\modules\contrib\commerce\modules\price\src\Calculator.php).

So what is the best way to do this in a Drupal commerce context?

Any help would be appreciated. :)

1 Answer 1

0

I was able to get this to work by checking that field_discount_percentage is not empty, rather than just checking if the entity has field_discount_percentage. The error must have been from all the other entities that were returning empty fields as a non-numerical value of ""

public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && !$entity->get('field_discount_percentage')->isEmpty()) {
     $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];
     return $entity->getPrice()->multiply($discount);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.