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?
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();
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 won't get lost and you are able to send the email to the correct address.
$node->field_email = NULL; $node->save();
in your node_presave hook also. To avoid saving the email in DB – user72672 May 20 '19 at 9:47