For some reason I need to replace some characters (if exist) in every single textfields in any form just right before they stored in database. In other words I need a hook in which I could get all submitted data and replace their characters.
I found this solution:

function hook_form_alter($form, $form_state, $form_id) {
  $form['#submit'] = 'my_custom_submission_function';

But this isn't a good idea since I have to take care of the rest of the submission progress too. I just need to replace some characters. Is there any hook to do this? What are the solutions?

3 Answers 3


$form['#submit'] stores an array of form submit handlers. With the code you provided you're overwriting it by adding only your own. To get the result you want you should add your submit handler as the first element in the array like this:

array_unshift($form['#submit'], 'mymodule_custom_submission');

Getting the right values in the right forms and replacing some characters is probably a bigger issue in itself. You may want to narrow down the forms/fields you need to change to make sure you don't break anything.


Perhaps it would be better to perform these modifications during validation instead of submission as suggested by Drupal (see form_set_value function at https://api.drupal.org/api/drupal/includes!form.inc/function/form_set_value/7).

So in your hook_form_alter you could even add it to the end of existing validation functions if you like:

$form['#validate'][] = 'mymodule_custom_validation';

On Drupal 8 or 9 it's almost the same solution :

Add a hook in a custom module file and a custom function :

File my_module.module :


use Drupal\Core\Form\FormStateInterface;

 * Implements hook_form_alter().
function my_module_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['#submit'][] = 'submit_form_custom';

 * Custom form submit handler.
function submit_form_custom(&$form, FormStateInterface &$form_state) {
  $value = $formState->getValue('field_name');
  // Do what you need with the value...
  $value = str_replace("old", "new", $value);
  $formState->setValue('field_value', $value);

Your Answer

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

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