Drupal - How to alter a form element's properties before rendering?

In hook_template_preprocess_form_element the (input-)tags is already rendered. You can use

function hook/template_preprocess_input(&$variables) {
  $variables['attributes']['title'] = 'my-title';
  $variables['attributes']['placeholder'] = 'my-placeholder';
}

to alter the input tag. use the same method for all other desired tags. Here's a nice tutorial.

You could make use of hook/template_preprocess to go a more generic way.


here is a piece of code :

function MODULE_preprocess_input(&$variables) {
    if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
        $field = $variables['element'];
        if ($field['#type'] == 'email') {
            if (isset($field['#attributes']['placeholder'])) {
                $placeholder = $field['#attributes']['placeholder'];
                $variables['element']['#attributes']['title'] = $placeholder;
            }
        }
    }
}

Tags:

Forms

8