I am using a custom block in which all nodes of a specific type are loaded and then a webform is loaded and attached to each of these nodes. The webform has a hidden textfield field which I am trying to programatically set to the id of the parent node:

class CustomBlock extends BlockBase {

  public function build() {
    // Load all nodes
    $query = \Drupal::entityQuery('node');
    $query->condition('status', NODE_PUBLISHED);
    $entity_ids = $query->execute();  
    $nodes = \Drupal\node\Entity\Node::loadMultiple($entity_ids);

    // Loop through all nodes, connecting the webform.
    foreach ($nodes as $node) {
      $form = \Drupal\webform\Entity\Webform::load('MYWEBFORM');

      // Set the value for the hidden field pointing to the 'parent' node.
      $form->setElementProperties('node_reference', [
        '#type'=> 'textfield',
        '#wrapper_attributes' => array(
          'style' => 'display:none',
         ),
        '#webform_id' => 'mywebform--node_reference',
        '#webform_key' => 'node_reference',
        '#value' => $node->get('nid')->value,
      ]);

      // Render form an assign it to each node.
      $rendered_form = \Drupal::entityManager()
        ->getViewBuilder('webform')
        ->view($form);

      $node->form = $rendered_form;
    }
  }

}

If I look at the generated markup for each nodes form it see different values in the node_reference field, but when I submit the form and then look at the submission all forms have the same node_reference value? Can anyone help me figure out what I am doing wrong here or perhaps this could be solved in a much easier way?

It seems like the the value always are set to the nid of the first node in the array? Perhaps this is some kind of strange caching issue?

I don't know if your problem could be solved in an easier way. A lot of our solutions at my workplace seem equally convoluted. In fact, we use WebformSubmissions to hold a lot of submitted data.

Here is how you set a value in a WebformSubmission:

  1. Load the submission.
  2. Get the submission's data as an associative array.
  3. Change the submission's data however you want.
  4. Set the submission's data to this modified array.
  5. Save the submission.

Here is the code:

use Drupal\webform\Entity\WebformSubmission;

// $sid contains the submission id
$submission = WebformSubmission::load($sid);

$data = $submission->getData();

// you can find the machine name in the devel tab
// or just do what I do and var_dump($data);
$data["field_machine_name"] = "new value";

$submission->setData();
$submission->save();

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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