You are here

function draggableviews_views_submit in DraggableViews 8

Same name and namespace in other branches
  1. 7.2 draggableviews.module \draggableviews_views_submit()
  2. 2.0.x draggableviews.module \draggableviews_views_submit()

Submit handler.

1 string reference to 'draggableviews_views_submit'
draggableviews_form_alter in ./draggableviews.module
Implements hook_form_alter().

File

./draggableviews.module, line 165
Contains draggableviews.module.

Code

function draggableviews_views_submit(&$form, FormStateInterface $form_state) {
  $input = $form_state
    ->getUserInput();

  /** @var \Drupal\views\ViewExecutable $view */
  $view = $form_state
    ->getBuildInfo()['args'][0];
  $view_name = $view
    ->id();
  $view_display = $view->current_display;
  $view_args = !empty($view->args) ? json_encode($view->args) : '[]';
  $connection = Database::getConnection();
  $transaction = $connection
    ->startTransaction();
  try {
    foreach ($input['draggableviews'] as $item) {

      // Remove old data.
      $connection
        ->delete('draggableviews_structure')
        ->condition('view_name', $view_name)
        ->condition('view_display', $view_display)
        ->condition('args', $view_args)
        ->condition('entity_id', $item['id'])
        ->execute();

      // Add new data.
      $record = [
        'view_name' => $view_name,
        'view_display' => $view_display,
        'args' => $view_args,
        'entity_id' => $item['id'],
        'weight' => $item['weight'],
      ];

      // Save parent if exists.
      if (isset($item['parent'])) {
        $record['parent'] = $item['parent'];
      }
      $connection
        ->insert('draggableviews_structure')
        ->fields($record)
        ->execute();
    }

    // We invalidate the entity list cache, so other views are also aware of the
    // cache.
    $views_entity_table_info = $view->query
      ->getEntityTableInfo();

    // Find the entity type used by the view.
    $result = array_keys(array_filter($views_entity_table_info, function ($info) {
      return $info['relationship_id'] == 'none';
    }));
    $entity_type_id = reset($result);
    $list_cache_tags = \Drupal::entityTypeManager()
      ->getDefinition($entity_type_id)
      ->getListCacheTags();

    // Add the view configuration cache tag to let third-party integrations to
    // rely on it.
    $list_cache_tags[] = 'config:views.view.' . $view_name;
    Cache::invalidateTags($list_cache_tags);
  } catch (\Exception $e) {
    $transaction
      ->rollback();
    \Drupal::logger('draggableviews')
      ->error('Failed with @message', [
      '@message' => $e
        ->getMessage(),
    ]);
    \Drupal::messenger()
      ->addMessage(t('There was an error while saving the data. Please, try again.'), 'warning');
  }
}