I need to create programmatically order from other content like a subscription node on cron task.

This is my code to get data from the subscription node called 'abonnement' and then create an order.

  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'abonnement');
  $query->condition('field_livraison', 3);//livraison le vendredi
  $entity_ids = $query->execute();

  foreach ($entity_ids as $entity_id) {
    $abo = Node::load($entity_id);

    $user_array= $abo->get('field_utilisateur')->getValue();
    $user = $user_array[0]['target_id'];
    $nid= $abo->id();

    //ligne de commande
    $items = array();
    $items_array= $abo->get('field_abo_produits')->getValue();

    for($i=0; $i<count($items_array); $i++) {

    //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,
      'placed' => time(),      
      'state' => 'completed',
      'completed' => time(), 
      'uid' => $user,
      'cart' => FALSE,
      'order_items' =>$items,
      'field_abonnement' => $nid

It works, but line items are line items from the subscriptions. If I delete the order, I delete the line items in the subscription too.

How can I duplicate the line items (as with $cloned_items = clone($items);)?

  • You can't just clone the PHP objects, target_id will refer to the same products in the database. You need to create new line item entities, and use the target_ids from those for the new order – Clive Jul 2 '18 at 8:49
  • Thank's, Can you just tell me how to create programmatically line item? – christophe Natale Jul 2 '18 at 10:48
  • You can find a complete example in the question/answer here: drupal.stackexchange.com/questions/14668/… – Clive Jul 2 '18 at 11:16
  • it's drupal 7, I'm looking for a drupal 8 example. – christophe Natale Jul 2 '18 at 13:11
  • I can't find documentation for getting line_item informations like in drupal 7 : $order_wrapper = entity_metadata_wrapper('commerce_order', $order); $line_items = $order_wrapper->commerce_line_items; $quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types()); $total = commerce_line_items_total($line_items, commerce_product_line_item_types()); print_r($quantity); – christophe Natale Jul 2 '18 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.