7

In hook_form_alter(), I am trying to disable/hide a field label in a custom form. I know I could use $form['my_field']['#enableLabel'] = FALSE;.

Is there a way without unsetting the title?

3 Answers 3

9

Unsetting not really, hide yes : use #title_display and its get accessible to screenreader :

$form['my_field']['#title_display'] = 'invisible';
2
  • Just to mention that if you're using, say a List (text) field, you need to refer to the widget to hide the title: $form['my_field']['widget']['#title_display'] = 'invisible'; Oct 31, 2018 at 11:17
  • Every field has a different array structure to set invisible values. I didn't find #title_display with dropdown widget, Apr 15, 2021 at 16:27
2

In my case I was trying to hide the label on quantity field provided by Drupal Commerce cart module and the following wasn't working:

$form['my_field']['#title_display'] = 'invisible';

I had to do this inside my hook_form_alter

$form['quantity']['widget'][0]['value']['#title_display'] = 'invisible';
1
  • Thank u. That's also works for me.
    – macherif
    Feb 11, 2022 at 14:51
-1

you can try:

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

    $form['title']['widget']['0']['value']['#title_display']=none;

 }

Note: change "title" by your machine name field.

2
  • I do not understand how they put votes down if the code works well for me. Could you explain this to me? They should prohibit putting votes down if an explanation is not given. Dec 7, 2017 at 15:41
  • Downvotes are anonymous by design, that's not going to change. You can avoid them quite easily, though. For example, you said the code works well for me, when any PHP developer will be able to tell you that's simply not true, just by glancing at your answer. First of all, it's invalid PHP. You haven't quoted a string. Second of all, it's invalid in the context of hiding a title in Drupal. The correct string to hide a title is "invisible", as you can see in the accepted answer above. It's always a good idea to check your work before trying to lay blame at the feet of others
    – Clive
    Dec 7, 2017 at 16:14

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.