Skip to main content
Image
Webform

Export 'Webform Submissions' in a customized way

In this article we will talk a little -without extendings- about Webform for Drupal 8 and a specific case: how to generate an export of webform submissions in a custom field.

But as always, let's go in parts...

What is Webform

Webform is a contributed module, in fact it is one of the most complete and flexible modules when creating forms in Drupal. All this together with a user-friendly interface and a wide range of field types (textfield, textarea, list, radio groups... etc.) Webform has a stable version for both Drupal 7 and Drupal 8 and is used in more than 478 thousand Drupal websites.

Custom export of Webform submissions

One of the needs that a project required was to provide the administrator user with a button or link that would allow them to download all the submissions. Webform submissions are the submissions that a user makes in a webform, that is, when a user completes a form and makes the 'submit'. Submissions are collected in the Drupal administration interface, specifically in the 'Webform' section of the 'Structure' menu. Now, you will think:

Why create a link or button if submissions already have their place in the administration menu?

With this you will get a custom link that you can place in a view or in a block of your portal, giving the user a lot of flexibility and organization when downloading the shipment report from a webform. You also have an extra advantage: when it is encoded you can choose the output format (normally .csv is used) and many other options that we will see later! For example, you can place this link in a view that is filtering some type of content related to the webform, so that user X can obtain this report in a very friendly way. Once a small explanation of the use cases has been made, let's get to the topic!

First of all, we have to create a field plugin to use the views. I don't want to go into this too much, since the interesting part comes later. We will create a basic plugin that generates a link. Remember that for this it is necessary to create a custom module, and create this plugin in /test_results/src/Plugin/views/field.

<?php
 namespace Drupal\test_results\Plugin\views\field;

use Drupal\Core\Url;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Field handler to download results.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("download_results")
 */
    class DownloadResults extends FieldPluginBase {
  /**
   * @{inheritdoc}
   */
  public function render(ResultRow $values) {
    $node = $values->_entity;
    $webform_id = $values->_entity->get('webform')[0]->target_id;
    $params = ['wid' => $webform_id];

    $output['results_link'] = [
      '#title' => t('Download CSV'),
      '#type' => 'link',
      '#url' => Url::fromRoute('test_results.export_webform_results', $params)
    ];

    return $output;
  }
}

This plugin 'DownloadResults' is nothing more than β€œthe transport” to the route 'test_results.export_webform_results', which will be responsible for passing the necessary parameters -webform_id in this case- to the controller. In addition to the previous plugin, it is necessary to add the following in our 'test_results.views.inc' so that the custom field is detected and recognized by the views, since otherwise it will not appear in the list of available fields:

  $data['node']['download_results'] = [
    'title' => t('Download CSV link'),
    'field' => [
      'title' => t('Download CSV link'),
      'help' => t('Download Webform submissions results with a CSV file.'),
      'id' => 'download_results',
    ],
  ];

The next step is to configure the test.routing.yml:

test_results.export_webform_results:
  path: '/results/{wid}'
  defaults:
    _controller: '\Drupal\test_results\Controller\WebformExportResults::export'
  requirements:
    _permission: 'administer site configuration'

This route will be responsible for passing the necessary parameter to the controller, which is the webform_id in this case. And finally we are going to create the controller, which will ensure that the link generates an output with all the webform submissions.

<?php
namespace Drupal\test_results\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\webform\Entity\Webform;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;


class WebformExportResults extends ControllerBase {

  /**
   * Generate a CSV file.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   * @param string $wid
   *   The webform_id parameter.
   * @param bool $download
   *   Download the generated CSV file. Default to TRUE.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response object containing the CSV file.
   */
	public function export(Request $request, $wid = NULL, $download = TRUE) {
	  // Load the webform and the export configuration, then modify it and generate a binary file response.
    $webform = Webform::load($wid);
    $submission_exporter = \Drupal::service('webform_submission.exporter');
    $export_options = $submission_exporter->getDefaultExportOptions();
    $submission_exporter->setWebform($webform);
    $submission_exporter->setExporter($export_options);
    $submission_exporter->generate();
    $file_path = $submission_exporter->getExportFilePath();
    $file = file_get_contents($file_path);   
    $response = new BinaryFileResponse($file_path, 200, [], FALSE, $download
      ? 'attachment' : 'inline');
    $response->deleteFileAfterSend(TRUE);

    return $response;
	}
}

With this we would have a field prepared to be placed in a view, which would print a link that would download to the user a .csv with all the submissions of the associated webform. But there is much more here, since we can change the export options ($export_options) to our liking, excluding the fields we want when exporting the data.

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Latest posts

Featured

Last news