0

I have a content type with a text field that I need Javascript to do some work on (when in the content type add/edit form). I prefer to have Javascript identify the form element by it's id so I would like to set the id of the form element to something meaningful.

I've attempted to set the id in with a hook_form_alter() but to no success. If I kint() out the template with the form I do see the id being set in the kint() info however the actual form element html is unchanged. My hook_form_alter():

function hook_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_element_name']['#id'] = 'element_name_id';
}

Is what I'm attempting possible and if so does anyone know how to do this? Or is there some completely different way of achieving this?

Thanks!

1 Answer 1

0

I figured it out by digging through the kint() statement. Turns out the id is buried deeper in the $form array. Here is what worked for me:

function hook_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_element_name']['widget']['0']['value']['#id'] = 'element_name_id';
}

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.