Skip to main content
minor change for clarity to establish that I don't want to create this using a contributed module
Link
Amy
  • 5.8k
  • 13
  • 66
  • 133

Programmatically Duplicate EntityQueues

Source Link
Amy
  • 5.8k
  • 13
  • 66
  • 133

Duplicate EntityQueues

I'm attempting to create a duplicate of an entity queue that includes all the nodes inside it.

Here is my current code

$entityQueueId = 'hero_images';
$langcode = 'test'
$clones = [];
$subqueue = \Drupal::entityTypeManager()->getStorage('entity_subqueue')->load($entityQueueId);
$nodes = $subqueue->get('items')->referencedEntities();
    foreach ($nodes as $node) {
         $clone = $node->createDuplicate();
         $clone->title->value = $clone->title->value . ' - ' . $langcode;
         $clone->set('langcode', $langcode);
         $clone->setCreatedTime(time());
         $clone->setChangedTime(time());
         $clone->save();
         $clones[] = [
             'target_id' => $clone->id(),
         ];
    }

    $subqueue_clone = $subqueue->createDuplicate();
    $subqueue_clone->set('name', $langcode . '-' . $subqueue->id() . '-' . uniqid());
    $subqueue_clone->set('title', $langcode . '-' . $subqueue->id() . '-' . uniqid());
    $queue = $subqueue->getQueue();   
    $queue_clone = $queue->createDuplicate();
    $queue_clone->set('id', $langcode . '-' . $queue->id() . '-' . uniqid());
    $queue_clone->set('title', $langcode . '-' . $queue->id() . '-' . uniqid());
    $queue_clone->save();
    $subqueue_clone->setQueue($queue_clone);
    $subqueue_clone->set('items', $clones);
    $subqueue_clone->save();

The queue does get created, but there are no items within it. In case there was an issue with my node duplication code as a test I just set

$subqueue_clone->set('items', $subqueue->get('items')->getValue());

but that didn't work either. Is there an issue with my code? Or should I go about this in a completely different manner? What's the best way to duplicate an entityqueue while preserving or duplicating the list of the nodes inside it?