Replacement for clone_view() in Drupal 8

Posted on January 29, 2016

In Drupal 8, view::clone_view() (Drupal 7) and its inital replacement ViewExecutable::cloneView() was removed in #1858054: Remove ViewExecutable::cloneView(). Occasionally, a module may have the need to copy a view to perform additional query modifications without affecting the original view (think attachments and aggregation).

Luckily, there are a couple of ways to perform a similar cloning.


    $cloned = $view->createDuplicate();

where $view is a ViewExecutable



use Drupal\views\Views;

$cloned = Views::executableFactory()->get($view->storage);

where $view is a ViewExecutable

Both produce new objects, verified with spl_object_hash():

SPL Hash of cloned and original objects

And both unset identifiers and built values, retaining the storage info and Drupal\views\ViewsData we can use:

Cloned view with clened properties