How do I automatically duplicate an order? I use Drupal 8 and Drupal Commerce 2. I need to duplicate some orders, each week, automatically.

Orders have a Boolean field (recurrent_order). When the field is filled, the web site has to create the same order at the end of the week.

I have achieved this with rules and VBO on Drupal 7: On maintenance task, a rule finds an array filled by a VBO view, and a component duplicates the content.

In Drupal 8 there isn't VBO view access from a rule.

How can I achieve this? Regards,


Here is the code for duplicate order with a cron job:

function commande_et_paiement_cron() {
$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 = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
$utilisateur = \Drupal\user\Entity\User::load($user);

$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($user);  

$nid= $abo->id();

$date_livraison = new DateTime();
$date_livraison->modify('next friday');

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

foreach ($abo_array as $abo_item) {
    $ligne = $abo_item['target_id'];        
    //load produit abonnement      
    $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
    $quantite = $item->getQuantity();
    $produit = $item->getPurchasedEntity();

    $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
    'type' => 'default',
    'purchased_entity' => $produit,
    'quantity' => $quantite,
    //'unit_price' => $role_price,


//creation de la commande
$order = \Drupal\commerce_order\Entity\Order::create([
      'type' => 'default',
      'store_id' => 1,
      'checkout_flow' => 'boulangerie',      
      'uid' => $user,
      'billing_profile' =>$profile,
      'field_abonnement' => $nid,
      'placed' => time(),
      'field_date_livraison' =>$date_livraison->format('Y-m-d'),
      'order_items' =>$line_items,
      'state' => 'draft'
    //'completed' => time(),

    $order->set('order_number', $order->id()); 
    $order->set('state', 'complete');
    /*$comment = 'blabla';
     $logStorage = \Drupal::entityTypeManager()->getStorage('commerce_log');        
    $logStorage->generate($order, 'order_comment', ['comment' => $comment])->save();      */
| improve this answer | |

Your Answer

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

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