View source
<?php
namespace Drupal\vbo_export\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Views;
use Drupal\Core\Url;
abstract class VboExportBase extends ActionBase {
const THEME = '';
protected function sendToFile($csv_string, $filename) {
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$wrappers = $stream_wrapper_manager
->getWrappers();
if (isset($wrappers['private'])) {
$wrapper = 'private';
}
else {
$wrapper = 'public';
}
if (!empty($csv_string)) {
$destination = $wrapper . '://' . $filename;
$file = file_save_data($csv_string, $destination, FILE_EXISTS_REPLACE);
$file
->setTemporary();
$file
->save();
$file_url = Url::fromUri(file_create_url($file
->getFileUri()));
$link = \Drupal::l(t('Click here'), $file_url);
drupal_set_message(t('Export file created, @link to download.', array(
'@link' => $link,
)));
}
}
public function executeMultiple(array $entities) {
$params = \Drupal::routeMatch()
->getRouteObject()
->getDefaults();
if (!empty($params['view_id'])) {
$view = Views::getView($params['view_id']);
$view
->setDisplay($params['display_id']);
$nids = array();
foreach ($entities as $entity) {
$id = $entity
->id();
$nids[$id] = $entity
->id();
}
$view
->build();
$base_table = $view->storage
->get('base_table');
$alias = $view->query->tables[$base_table][$base_table]['alias'];
$view->build_info['query']
->condition($alias . '.' . $view->storage
->get('base_field'), $nids, 'in');
$view->query
->execute($view);
$view->result = array_values($view->result);
$renderable = [
'#theme' => static::THEME,
];
$structure = [];
foreach ($view->field as $id => $field) {
if ($id == 'node_bulk_form' || $field->options['exclude'] || empty($field->options['entity_field'])) {
continue;
}
$structure[$id] = [
'id' => $id,
'label' => $field->options['label'],
'entity_type' => $field->options['entity_type'],
'field' => $field->options['entity_field'],
'plugin_id' => $field->options['plugin_id'],
];
}
if (!empty($structure) && !empty($view->result)) {
foreach ($structure as $item) {
$renderable['#header'][] = $item['label'];
}
$view->style_plugin
->preRender($view->result);
foreach ($view->result as $num => $row) {
foreach ($structure as $field_id => $item) {
$renderable['#rows'][$num][$field_id] = $view->style_plugin
->getField($num, $field_id)
->__toString();
}
}
$renderer = \Drupal::service('renderer');
$csv_string = $renderer
->render($renderable);
$rand = substr(hash('ripemd160', uniqid()), 0, 8);
$filename = $params['view_id'] . '_' . date('Y_m_d_H_i', REQUEST_TIME) . '-' . $rand . '.' . static::EXTENSION;
$this
->sendToFile($csv_string, $filename);
}
}
}
public function execute($entity = NULL) {
$this
->executeMultiple([
$entity,
]);
}
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
$access = $object
->access('view', $account, TRUE);
return $access
->isAllowed();
}
}