Create order : how to set price?

In my module, on a cron_job function I need to create an order with specific order_item price. Here is my code :

        switch ($role[1]) {             case 'biocoop':                 $role_price = $produit->get('field_prix_biocoop');                 break;             case 'montagne':                 $role_price = $produit->get('field_prix_montagne');                  break;             case 'vente_directe':                 $role_price = $produit->get('field_prix_vd');                 break;               /* default:               $role_price = $produit->getPrice();               break; */         }               $order_item = Drupalcommerce_orderEntityOrderItem::create([             'type' => 'default',             'purchased_entity' => $produit,             'quantity' => $quantite,         ]);         $unit_price = new Drupalcommerce_pricePrice($role_price->number, $role_price->currency_code);         $order_item->setUnitPrice($unit_price);         $order_item->save();         Drupal::logger('commande_et_paiement')->notice('Prix @role : @prix',         array(             '@prix' => $order_item->getUnitPrice(),             '@role' => $role[1],          ));            $line_item[$i]=$order_item;     }      //creation de la commande     $entity_type_manager = Drupal::service('entity_type.manager');     $order_storage = $entity_type_manager->getStorage('commerce_order');     $new_order = Order::create([       'type' => 'default',       'store_id' => 1,       'checkout_flow' => 'boulangerie',             'uid' => $user,       'billing_profile' =>$profile,       'order_items' =>$line_item,       //'state' => 'draft',         'field_abonnement' => $nid,       'placed' => time(),       'field_date_livraison' =>$date_livraison->format('Y-m-d'),      ]);      $new_order->save();     $new_order->set('order_number', $new_order->id());     $new_order->save();  } 

In the watchdog the price is good, but not in my order. If I try to set quantity of the order_item just after the setPrice function, the quantity is OK in my order too :

// Set the quantity with setQuantity.     $order_item->setQuantity(50); 

It seems that when the order is saved the order_item price has been updated?

Here is my resolver class :

class PrixRoleResolver implements PriceResolverInterface {     public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {         //kint($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);         }          if ($account->hasRole('montagne')) {             $role_price = $entity->get('field_prix_montagne');             return new Price($role_price->number, $role_price->currency_code);         }          if ($account->hasRole('vente_directe')) {             $role_price = $entity->get('field_prix_vd');             return new Price($role_price->number, $role_price->currency_code);         }          if ($account->hasRole('administrateur_boutique')) {             //l'administrateur quand il créé une commande le site applique le prix lié au role du client              $client=$context->getCustomer();             $client_uid = $client->uid;             if (!empty($client_uid))  {                  $uid = $client_uid->getString();                 //kint($uid);                  if (!empty($uid)) {                     $client_user_id = $uid;                ÷    $account = User::load($client_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();     } } 
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Create order : how to set price?

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.