You are here

function commerce_product_update_8209 in Commerce Core 8.2

Update all existing views using a reference to stores or variations.

File

modules/product/commerce_product.install, line 204
Install, update and uninstall functions for the Product module.

Code

function commerce_product_update_8209() {
  $config_factory = \Drupal::configFactory();
  foreach ($config_factory
    ->listAll('views.view.') as $view_config_name) {
    $view = $config_factory
      ->getEditable($view_config_name);
    if (!in_array($view
      ->get('base_field'), [
      'product_id',
      'variation_id',
    ])) {

      // Not a commerce_product / commerce_product_variation SQL view.
      continue;
    }
    $displays = $view
      ->get('display');
    foreach ($displays as $display_name => $display) {
      if (!empty($display['display_options']['relationships'])) {
        foreach ($display['display_options']['relationships'] as $relationship_name => $relationship) {
          if ($relationship_name == 'stores' || $relationship_name == 'variations') {

            // Update the relation field and add entity information.
            $base = "display.{$display_name}.display_options.relationships.{$relationship_name}";
            $view
              ->set($base . '.field', $relationship_name . '_target_id');
            $view
              ->set($base . '.entity_type', 'commerce_product');
            $view
              ->set($base . '.entity_field', $relationship_name);
          }
        }
      }
      if (!empty($display['display_options']['fields'])) {
        foreach ($display['display_options']['fields'] as $field_name => $field) {
          if ($field_name == 'stores' || $field_name == 'variations') {

            // Update the relation field and add entity information.
            $base = "display.{$display_name}.display_options.fields.{$field_name}";
            $view
              ->set($base . '.field', $field_name . '_target_id');
          }
        }
      }
    }
    $view
      ->save(TRUE);
  }
}