Manage programmatically added fields I'm working on a custom module that allow anonymous users who add a new content, to register himself in the same form providing a simple email field (user name is the same as email).

In my module I hook the node_form_alter to add the email field from the user registration form:

function mymodule_form_node_form_alter(&amp;$form, FormStateInterface $form_state) {
  if (\Drupal::currentUser()-&gt;isAnonymous()) {

    // Add drupal registration form
    $entity = \Drupal::entityTypeManager()-&gt;getStorage('user')-&gt;create(array());
    $formObject = \Drupal::entityTypeManager()
      -&gt;getFormObject('user', 'register')
      -&gt;setEntity($entity);
    $user_register_form = \Drupal::formBuilder()-&gt;getForm($formObject);

    //kint($user_register_form['account']);
    $form['user_registration'] = $user_register_form['account'];
    unset($form['user_registration']['name']);
  }
}


And this works good.
In node_presave I'm expecting the field to register, but i get an error "Field user_registration is unknown."

function mymodule_node_presave(NodeInterface $node) {
  kint($node);

  $email = $node-&gt;get('user_registration')-&gt;value; // This throws the error

  if ($email) {
    $email_user = user_load_by_mail($email);

    if (!$email_user) {
      /* Create user */
      $email_user = _create_user($email);
    }

    /* Set user as author */
    if ($email_user) $node-&gt;setOwnerId($email_user);
  }
}


What am I missing?
You have to add a custom submit handler to handle these fields. The form fields you add are custom, so they won't be attached to the node.

$form['user_registration']['#submit'] = 'custom_user_registration_handler';


In the submit handler you'll be able create the user like you're doing no in your presave function. The presave function should load the user and attach it to the node.

Edit \

Problem: The node_presave hook does not contain the email adres so it's not able to lookup the right user.

Solution: The default node form has an author form field. You probably hid that field but I think your still able to fill the value. What if you fill the 'author' field with the email value, this will be the user name.

So in your custom submit handler:


Create the user;
Fill the (hidden) author form field with the right value (fill the right value in the form_state object/array?).


The the default form submit handler will do all the hard work for you.