I'm trying to programmatically create nodes through form submit in Drupal 8 (because I need to validate the submitted values) in this way.

try {
  $node = \Drupal::entityTypeManager()
    ->create(array('type' => 'my_bundle_id'));

  $node->set('my_field', 'my_value');

  $node_form_object = \Drupal::entityTypeManager()
    ->getFormObject('node', 'default')

  $form_state = new FormState();
  $form_state->setValue('my_field', $node->get('my_field')->getValue());
  $form_state->setValue('op', $this->t('Save'));
  \Drupal::formBuilder()->submitForm($node_form_object, $form_state);
catch(Exception $e) {

Before setting any $form_state value, I'm evaluating the field type case (datetime, created and so on) to pass a right value getting it from $node.

Everything works correctly, except in case of a field referencing existing users which is passed to $form_state as follows.

$form_state->setValue('user_ref_field', array (
  0 =>  array (
    'target_id' => '1', // right uid of user

Same happens with fields referencing taxonomy terms unless in default node form mode I don't set client hierarchical select (coming from a third-party module) as widget, while in case of user reference (with any widget type set in node default form) I get a There are no entities matching '1' (my user ID).

What am I doing wrong?

  • 1
    What am I doing wrong? you're putting a number inside quotes; thus, making it a string rather than integer. Should be 'target_id' => 1, – No Sssweat Mar 13 at 19:46
  • I didn't try a number instead of string because inside values of a $form_state of a node submitted through a normal node form (not programatically) it is a string not a number. I had this doubt while writing code in my question. I will give it a try anyway. Thanks – Nicoschi Mar 13 at 21:02
  • Despite my previous comment, it seems weird to me, but it works, tomorrow i will analize it again. Thank you again @NoSssweat – Nicoschi Mar 13 at 21:37

Your Answer

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

Browse other questions tagged or ask your own question.