1

I need to get in hook_node_insert and hook_node_update the value of a field I manually added to a form.

function hook_form_FORMID_alter(&$form, FormStateInterface $formState, $form_id) {

  $form['newfield'] = [
    '#title' => 'New field',
    '#type' => 'checkbox',
  ];
}

In Drupal 7 every form field is copied to the entity and it's easy to access it as explained here Get data form into hook_node_insert / hook_node_update

Is there a way in Drupal 8 too?

1 Answer 1

3

Use an entity builder callback on the form, for example:

function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // ...
  $form['#entity_builders'][] = 'menu_ui_node_builder';
}

/**
 * Entity form builder to add the menu information to the node.
 */
function menu_ui_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->menu = $form_state->getValue('menu');
}
2
  • It works despite I get the warning "Field declared dynamically", but I can live with it :) Dec 12, 2018 at 8:05
  • Well, depending on what you do with it, you can also just use a regular submit callback, you can access the entity with $form_state->getFormObject()->getEntity() for an entity form. Only use this if you actually need that information to be able during the hooks and then maybe consider to just make it a field..
    – Berdir
    Dec 13, 2018 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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