Better to create a service so you can use it anywhere:
<?php
namespace Drupal\my_module\Services;
use Drupal\Core\Archiver\ArchiverManager;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\webform\Entity\WebformSubmission;
use Drupal\webform\Plugin\WebformElementManagerInterface;
use Drupal\webform\Plugin\WebformExporterManagerInterface;
use Drupal\webform\WebformSubmissionExporter;
use Drupal\webform\WebformSubmissionForm;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Database\Connection;
use PDO;
/**
* Class DailySubmissionCSVExport.
*/
class DailySubmissionCSVExport extends WebformSubmissionExporter
{
protected $connection;
/**
* {@inheritDoc}
*/
public function __construct(
ConfigFactoryInterface $config_factory,
FileSystemInterface $file_system,
EntityTypeManagerInterface $entity_type_manager,
StreamWrapperManagerInterface $stream_wrapper_manager,
ArchiverManager $archiver_manager,
WebformElementManagerInterface $element_manager,
WebformExporterManagerInterface $exporter_manager,
Connection $connection
)
{
parent::__construct($config_factory, $file_system, $entity_type_manager, $stream_wrapper_manager, $archiver_manager, $element_manager, $exporter_manager);
$this->connection = $connection;
}
/**
* {@inheritdoc}
*/
public function generate()
{
$entity_ids = $this->getQuery()->execute()->fetchAll(PDO::FETCH_COLUMN, 'sid');
$webform_submissions = WebformSubmission::loadMultiple($entity_ids);
$this->writeHeader();
$this->writeRecords($webform_submissions);
$this->writeFooter();
}
/**
* {@inheritdoc}
*/
public function getQuery()
{
$webform = $this->getWebform();
/** @var SelectInterface $query * */
$query = $this->connection->select('webform_submission_data', 'wsd');
$query->join('webform_submission', 'ws', 'wsd.sid = ws.sid');
$query->fields('wsd', array('sid'));
$query->orderBy('wsd.sid', 'DESC');
return $query;
}
}
Define service in my_module.service.yml
file
my_module.exporter:
class: Drupal\my_module\Services\DailySubmissionCSVExport
arguments: ['@config.factory', '@file_system', '@entity_type.manager', '@stream_wrapper_manager', '@plugin.manager.archiver', '@plugin.manager.webform.element', '@plugin.manager.webform.exporter', '@logger.factory', '@database']
drush webform-export
to generate the CSV and then call a custom drush command to upload the file to an FTP server. The challenge with programmatically generating a CSV is that the WebformSubmissionExporter services uses batch processing which can be difficult to programmatically trigger.