2

I'd like to be able to create a node out of a webform submission in Drupal 8. It can happen either on successful submission or as an additional task after the webform has been submitted. I've seen some info on creating content entities via REST/GET (https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities) and I know that you can post a webform submission to a URL with Webform (yamlform) using either x-www-form-urlencoded or JSON, but I'm not sure if this is even the right thing to be looking at.

The webform, submissions, and content type I'd like to use are all on the same site.

I know this question came up for Drupal 7 and the direction was to have them use a content type, but we're not able to allow the submitters to use content types at this time because of the way the site is setup.

  • 1
    Nodes and Webform submissions are both content entity types, so quite similar in a few ways already. What do you need from nodes that you don't get from submissions? It might (only might) be easier to enable the missing functionality in submissions than creating almost duplicate entities of different types – Clive Apr 27 '17 at 15:59
  • Right now we're running into issues with webform views--particularly filters/exposed filters, and it might be easier for us to convert the submissions to nodes and then use views content instead of views webform submissions. – owenpm3 Apr 27 '17 at 17:34
4
<?php

/**
 * Convert webform submission to "Bulletin" content type.
 */

namespace Drupal\subtonode\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\webform\Entity\WebformSubmission;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SubToNodeController extends ControllerBase {
  public function subtonode($webform_submission) {
    //$sid = 2;
    $node_details = WebformSubmission::load($webform_submission);
    $submission_array = $node_details->getOriginalData();
    $title = $submission_array['title'];
    $body = $submission_array['body'];
    $contact_name = $submission_array['contact_name'];
    $contact_email = $submission_array['contact_email'];
    $contact_website_uri = $submission_array['website'];
    $contact_website_title = $submission_array['website'];
    $des_pub_date = $submission_array['bulletin_publish_date'];
    $image_fid = $submission_array['image'];


// Create file object from remote URL.
    if (!empty($image_fid)) {
      $file = \Drupal\file\Entity\File::load($image_fid);
      $path = $file->getFileUri();
      $data = file_get_contents($path);
      $node_img_file = file_save_data($data, 'public://' . $file->getFilename(), FILE_EXISTS_REPLACE);
    }

    $timestamp = date("Y-m-d\TH:i:s", strtotime($des_pub_date));

// Create node object with attached file.
    $node = Node::create([
      'type' => 'bulletin',
      'title' => $title,
      'body' => [
        'value' => $body,
        'summary' => '',
        'format' => 'markdown',
      ],
      'field_bulletin_contact_name' => $contact_name,
      'field_bulletin_contact_email' => $contact_email,
      'field_bulletin_desired_publicati' => $timestamp,
      'field_bulletin_reference_submiss' => [
        'target_id' => $webform_submission,
      ],
      'field_bulletin_contact_website' => [
        'uri' => $contact_website_uri,
        'title' => $contact_website_title,
      ],
      'field_photo' => [
        'target_id' => (!empty($node_img_file) ? $node_img_file->id() : NULL),
        'alt' => 'Hello world',
        'title' => 'Goodbye world'
      ],
    ]);

    if (!empty($submission_array['audience'])) {
      $target_ids_aud = $submission_array['audience'];
      foreach ($target_ids_aud as $target_id) {
        $node->field_bulletin_audience->AppendItem($target_id);
      }
    }

    if (!empty($submission_array['category'])) {
      $target_ids_cat = $submission_array['category'];
      foreach ($target_ids_cat as $target_id) {
        $node->field_bulletin_category->AppendItem($target_id);
      }
    }

    $node->save();

    $url = '/admin/content/webform';
    $response = new RedirectResponse($url);
    //$response->send(); // don't send the response yourself inside controller and form.

    drupal_set_message(t('You have successfully created a node from webform submission @sid', array('@sid' => $webform_submission)), 'success');
    return $response->send();
  }
}
  • After days and days of searching, this is exactly what I am looking for! Can you please clarify where i should place this code in my drupal 8 website? – user86221 Jul 9 '18 at 23:03
  • @ElieMasaad Here's a link to the module I build out, it might help to see it all in context there: github.com/owenmorrill/subtonode – owenpm3 Jul 13 '18 at 17:51
2

The answer from @owenpm3 is great for adding this as an administrative duty.

In order to automate this and make it occur on a successful submission, I would create a custom WebformHandler that you add to your form in the configuration settings, the same way you configure your form to send an email upon a successful submission. So under your web forms Settings tab, under the sub-tab: Emails / Handlers.

To build this you would need to create a custom module, mymodule and place the custom webform handler in: mymodule/src/Plugin/WebformHandler/

I will call the WebformHandler MyWebformHandler.php. Aside from this you will need an info file and that should do it.

Code for MyWebformHandler.php as follows:

<?php

namespace Drupal\mymodule\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;


/**
 * Create a new Article node from a webform submission.
 *
 * @WebformHandler(
 *   id = "article_from_webform",
 *   label = @Translation("Create a node on submit"),
 *   category = @Translation("Content"),
 *   description = @Translation("Creates a new Article node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class MyWebformHandler extends WebformHandlerBase {

  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Get an array of form field values.
    $submission_array = $webform_submission->getData();

    // Dump the $submission_array to acquire the fields if you don't know what fields you're working with. 

    // Prepare variables for use in the node.  
    $title = $submission_array['subject'];
    $body = "<p>" . $submission_array['name'] . "<br/>";
    $body .= $submission_array['email'] . "</p>";
    $body .= $submission_array['message'];

    // Create the node.
    $node = Node::create([
      'type' => 'article',
      'status' => FALSE,
      'title' => $title,

      'body' => [
        'value' => $body,
        'format' => 'basic_html',
      ],

    ]);

    // Save the node. 
    $node->save();
  }
}
0

Also, check out the Webform Content Creator module.

This module provides the ability to create nodes after submitting webforms, and do mappings between the fields of the created node and webform submission values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.