0

I'm altering a node creation form using the form_alter hook in a custom module. In this particular case, I'm adding an email field which is not part of the content type structure. At the node creation, I need to send an email to the address entered in the field. Using the hook entity_presave or entity_insert I have access to the entity field that are part of its structure, but not to the programmatically added email field. How can I get that value at the form submit?

  • Is there any reason why you add the field using form_alter and not on the content type in the interface? – Jdrupal May 20 at 9:36
  • @Jdrupal for privacy reasons we cannot store the entered email in the db. Also, we only need to send the email notification once, at node creation, and not in case of updates (I know I can manage the difference in the hooks, but it would be not clear for the user). – Gabriele May 20 at 9:41
  • @Jdrupal I don't understand your second comment sorry, can you make an example? – Gabriele May 20 at 9:43
  • 1
    OK, I see. What about adding the field on the content type, then send mail in hook_node_presave, and then do $node->field_email = NULL; $node->save(); in your node_presave hook also. To avoid saving the email in DB – Jdrupal May 20 at 9:47
  • Hope it makes sense. – Jdrupal May 20 at 9:49
1

A field added in the form_alter hook is not created on the entity. Therefore you cannot retrieve the value in either hook_entity_presave or hook_entity_insert.

What you want however you can do by creating an additional submit handler for the form.

function _MODULE_NAME_custom_submit_handler($form, FormStateInterface $form_state) {
  $email = $form_state->getValue('email_field_name');
  // send email.
}

You can also get the saved entity (which does not have the email field) using $form_state->getFormObject();

1

So you added this MY_EMAIL_FIELD to the form with form_alter. Add the following as well:

$form['actions']['submit']['#submit'][] = 'MYMODULE_node_form_send_email';

Add another function to your file:

function MYMODULE_node_form_send_email($form, FormStateInterface $form_state) {
  $email = $form_state->getValue('MY_EMAIL_FIELD'); 
  // send email here
}

In this way, the email data will get lost and you are able to send the email to the correct address.

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.