Why am I failing to programmatically create a webform in hook_entity_insert? I need to create a webform programmatically when a node is created.
I refer and follow https://www.drupal.org/project/webform/issues/3038697
Here are the steps to reproduce:

Create new module via console, and install module.

In module.module add:
use Drupal\Core\Entity\EntityInterface; 
use Drupal\Core\Serialization\Yaml;
use Drupal\webform\Entity\Webform;

Add hook with webform create function:
function module_entity_insert(EntityInterface $entity){
  // Build a render array of elements.
  $elements = [
    'name' =&gt; [
      '#type' =&gt; 'textfield',
      '#title' =&gt; t('Name'),
    ],
  ];

  $settings = [
    // Define settings.
  ];

  // Append default settings.
  $settings += Webform::getDefaultSettings();

  // Create a webform.
  $webform = Webform::create([
    'id' =&gt; 'custom_id',
    'title' =&gt; 'Title',
    'elements' =&gt; Yaml::encode($elements),
    'settings' =&gt; $settings,
  ]);

  $webform-&gt;save();
}


Now, after save and cache clear, go to add new content (any type will do).
Suppose I have new sample webform created along the new node creation, but here is the error message:

The website encountered an unexpected error. Please try again later.Drupal\Core\Entity\EntityStorageException: Object support when dumping a YAML file has been disabled. in Drupal\Core\Entity\Sql\SqlContentEntityStorage-&gt;save() (line 847 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).



Drupal version is latest, fresh install. What am I doing wrong? Or what's missing?
The problem was at line:
'elements' =&gt; Yaml::encode($elements)

The solution is to replace the Yaml in the use statement:
from:
use Drupal\Component\Serialization\Yaml;

to:
use Symfony\Component\Yaml\Yaml;

I don't know the exact explanation, it just works on my code.