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?