2

I have a webform on a Drupal site to which I need to post data programmatically using the following code:

// Get the node ID of the created Webform and load the node.
$node = node_load($nid);

global $user;
$uid  = $user->uid;

// Include files.
module_load_include('inc', 'webform', 'webform.module');  
module_load_include('inc', 'webform', 'includes/webform.submissions');

// Prepare the data for submission.
$data = array(
    2 => array('value' => array('question_id')),
    1 => array('value' => array('quiz_name')),
    3 => array('value' => array('your_feedback')),
);

$submission = (object) array(
    'nid' => $nid,
    'uid' => $user->uid,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'data' => $data,
);

print_r($submission);

$sid = webform_submission_insert($node, $submission);

return "Submission {$sid} received!";

The problem is the submission is created but it's entirely empty i:e the $data array is not represented in the submission.

halfer
  • 19,824
  • 17
  • 99
  • 186
sisko
  • 9,604
  • 20
  • 67
  • 139
  • Try this: http://drupal.stackexchange.com/questions/123292/submitting-data-updating-data-into-webform-programmatically – Jose D Feb 28 '17 at 10:08

1 Answers1

0
global $user;
$nid = 4; //nid is the node id of your webform.

$node = node_load($nid); 

// The values to save. Take case about array indexes! (see below)
$data = array(
    '1' => array('0' => $type),
    '2' => array('0' => $method),
    '5' => array('0' => $volume),
    '6' => array('0' => $comment),
    '7' => array('0' => $phone),
    '8' => array('0' => $length)
);

$submission = (object) array(
    'nid' => $nid,
    'uid' => $user->uid,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'data' => $data,
);

// Include the necessary files.
module_load_include('inc', 'webform', 'webform.module');
module_load_include('inc', 'webform', 'includes/webform.submissions');
webform_submission_insert($node, $submission); // Submit a submission.
webform_submission_send_mail($node, $submission); // Send webform's e-mails

The $type, $method, $volume and so on are just the variables which have to be written to the webform fields. Array indexes are webform's fields indexes.

How to get the indexes and find out which is where?

  1. Go to your webform components page (like /node/4/webform where '4' is a webform nid).
  2. Do mouse hover on the field 'Edit' link and see the link source (href). It should be something like this: http://[site-name]/node/4/webform/components/2?destination=node/4/webform , where '2' is the index for this field.
  3. Do the same for all the necessary fields.
  4. In case of troubles take a look at webform_submitted_data DB table. It has fields:
    • nid (the webform id),
    • sid (the submission id),
    • cid (the field index!),
    • no (have no idea, maybe delta for a multiple-values fields),
    • data (stored field data).