How to disable a field or make it read-only in Drupal 7

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

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

then when I tried to disable a couple of fields, I found that this list can be disabled using 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 does not work:

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

I also found that I cannot use the same code to disable the text area field:

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

The above code does not disable the text area, but the same code may disable the selection list!

Then I tried hook_form_alter () to do the same, and I was able to disable the fields, and when I checked the render array from the $ 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. It seems like something else will override it, I thought hook_page_alter () is the last place to change the markup.

Any idea what is the best way to disable / read just any field inside hook_page_alter () in drupal 7?

thanks

+6
drupal-7 field form-api
source share
2 answers

It works for text fields ^

 $form['field_secured_title']['und']['0']['value']['#attributes']['disabled'] = TRUE; 
+13
source share

As the docs say

You can use attributes:

 $form['#attributes'] = array('disabled' => TRUE); 
+2
source share

All Articles