How to disable a field or make it readonly in Drupal 7
Asked Answered
T

2

6

I am trying to disable couple of fields and make them readonly via hook_page_alter(). I was able to do check if user is viewing the page edit section (the form edit)

$page['content']['system_main']['#node_edit_form'] == TRUE)

then when I tried to disable couple of fields, I found that select list can be disabled by this code:

$page['content']['system_main']['field_my_field_name_a_select_list']['und']['#attributes']['disabled'] = TRUE;

but if I use the following code it doesn't work:

$page['content']['system_main']['field_my_field_name_a_select_list']['und']['#disabled'] = TRUE;

I also found that I can not use the same code to disable a text area field:

$page['content']['system_main']['field_my_text_area']['und']['#attributes']['disabled'] = TRUE;

The above code doesn't disable the text area, but the same code can disable the select list!

Then I tried hook_form_alter() to do the same thing, and I was able to disable fields and when I checked the rendered array from $page array, I saw that it shows:

$page['content']['system_main']['field_my_field_name_a_select_list']['und']['#disabled'] = TRUE;

but when I set the same code in hook_page_alter(), it didn't work. Looks like something else will override it, I thought that hook_page_alter() is the last place to change markup.

Any idea what is the best way to disable/readonly any kind of field, inside hook_page_alter() in drupal 7?

Thank you

Trottier answered 23/3, 2011 at 0:3 Comment(0)
R
21

It works for text fields^

$form['field_secured_title']['und']['0']['value']['#attributes']['disabled'] = TRUE;
Reisinger answered 24/3, 2011 at 11:46 Comment(5)
Thanks for reply. I don't have issue with $form, what I am asking is how to do it by $page array, they way Drupal 7 like it. I mean using the new hook_page_alter() function.Trottier
if you want to change fields from a form, the way Drupal like it is to do it with hook_form_alterStrata
API doc is wrong and misguiding api.drupal.org/api/drupal/…Digestible
Sivaji - you are linking the D6 API doc, not D7.Telegonus
There is a #disabled parameter in Form API api.drupal.org/api/drupal/…Crackbrained
S
2

Like it said in the docs

You can use attributes :

$form['#attributes'] = array('disabled' => TRUE);
Sharkey answered 27/7, 2014 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.