function mymodule_update_8000(&$sandbox) { $message = ''// Only create if the redirect view doesn't exist and views is enabled.
$new_view_id = 'YOURVIEWID'; if (\Drupal::moduleHandler()->moduleExists('views') && !\Drupal\views\Entity\View::load($new_view_id)) { $config_path = \Drupal::service('extension.list.module')->getPath('YOURMODULENAME') . '/config/install/views.view.' . $new_view_id .'.yml'; $data = \Symfony\Component\Yaml\Yaml::parseFile($config_path); \Drupal::configFactory()->getEditable('views.view.' . $new_view_id)->setData($data)->save(TRUE); $message .= 'The new "' . $new_view_id . '" view has been created.';}
else { $message .= 'Not creating the "' . $new_view_id . '" view, since it already exists.';}
return $message;}
Also see: Drupal 8: Delete view programmatically
Here's a combined example to delete an old view and replace it by a new view from the config/install directory of a module in an install hook:
function mymodule_update_8000(&$sandbox) { $message = ''; $old_view_id = 'YOUROLDVIEWID';// Only delete the old view, if it is existing.
if (\Drupal::moduleHandler()->moduleExists('views') && \Drupal\views\Entity\View::load($old_view_id)) {// Delete the old view
$oldViewConfig = \Drupal::service('config.factory')->getEditable('views.view.' . $old_view_id); $oldViewConfig->delete(); $message .= 'The old "' . $old_view_id . '" view has been deleted.'; } else { $message .= 'Not deleting the old "' . $old_view_id . '" view, since it does not exists.';}
$message .= "\n";// Only create if the new view doesn't exist and views is enabled.
$new_view_id = 'YOURNEWVIEWID'; if (\Drupal::moduleHandler()->moduleExists('views') && !\Drupal\views\Entity\View::load($new_view_id)) { $config_path = \Drupal::service('extension.list.module')->getPath('MODULENAME') . '/config/install/views.view.' . $new_view_id .'.yml'; $data = \Symfony\Component\Yaml\Yaml::parseFile($config_path); \Drupal::configFactory()->getEditable('views.view.' . $new_view_id)->setData($data)->save(TRUE); $message .= 'The new "' . $new_view_id . '" view has been created.';}
else { $message .= 'Not creating the "' . $new_view_id . '" view, since it already exists.';}
return $message;}