Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 340
Mehr Avatar asked Mar 23 '11 00:03

Mehr


1 Answers

It works for text fields^

$form['field_secured_title']['und']['0']['value']['#attributes']['disabled'] = TRUE;
like image 181
oleg Avatar answered Nov 02 '22 05:11

oleg