Set value of a webform field programatically 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-&gt;condition('status', NODE_PUBLISHED);
    $entity_ids = $query-&gt;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-&gt;setElementProperties('node_reference', [
        '#type'=&gt; 'textfield',
        '#wrapper_attributes' =&gt; array(
          'style' =&gt; 'display:none',
         ),
        '#webform_id' =&gt; 'mywebform--node_reference',
        '#webform_key' =&gt; 'node_reference',
        '#value' =&gt; $node-&gt;get('nid')-&gt;value,
      ]);

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

      $node-&gt;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:


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


Here is the code:

use Drupal\webform\Entity\WebformSubmission;

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

$data = $submission-&gt;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-&gt;setData();
$submission-&gt;save();