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:

  1. create new module via console, and install module
  2. 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' => [ '#type' => 'textfield', '#title' => t('Name'), ], ];

$settings = [ // Define settings. ];

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

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

$webform->save(); }

(notice 'title' => 'Title', is originally had extra ' and remove that extra)

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->save() (line 847 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Drupal version is latest, fresh install


problem was at line : 'elements' => Yaml::encode($elements)

after days I found out the solution is repace the yaml in use statement:

from : use Drupal\Component\Serialization\Yaml; to: use Symfony\Component\Yaml\Yaml;

it just a work around. Don't know what the explanation, just it works on my code.

|improve this answer|||||

I just ran into this error...just change t('Name') to 'Name' and it should work.

Apparently the translate function expands out to an object (instead of what you might expect...'Name' or 'Nombre'...etc): and dumping objects to yaml is apparently no longer "allowed".


Drupal\Core\StringTranslation\TranslatableMarkup Object
    [translatedMarkup:protected] =>
    [options:protected] => Array

    [stringTranslation:protected] =>
    [string:protected] => Name
    [arguments:protected] => Array

|improve this answer|||||
  • There is a render() method on TranslatableMarkup that returns a string...I wonder if using t('name')->render() might do the trick, although I'd never think that'd be the way to handle this. It probably won't work but may be worth a shot – Mrweiner Nov 8 '19 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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