Add webform field programmatically In older versions of Webform (Drupal 7), the function webform_component_insert() can be used to add fields to a webform, for example inside a hook_node_insert() implementation, so they are added when the webform is created.
Does anyone know how to do that in Webform 6.x? I would like to add fields to webforms automatically after they are created.
You can alter a webform by modifying the YAML content of the config field elements:
use Drupal\webform\Entity\Webform;
use Drupal\Core\Serialization\Yaml;

  $webform = Webform::load('contact');
  $elements = Yaml::decode($webform-&gt;get('elements'));

  // add a field
  $elements['additional_field'] = [
    '#type' =&gt; 'textfield',
    '#title' =&gt; 'Additional field',
  ];

  $webform-&gt;set('elements', Yaml::encode($elements));
  $webform-&gt;save();