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

Whitewall
  • 597
  • 1
  • 7
  • 18
Mehr
  • 61
  • 1
  • 2
  • 3

2 Answers2

21

It works for text fields^

$form['field_secured_title']['und']['0']['value']['#attributes']['disabled'] = TRUE;
Samsquanch
  • 8,866
  • 12
  • 50
  • 89
oleg
  • 219
  • 1
  • 3
  • 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. – Mehr Mar 25 '11 at 04:04
  • 4
    if you want to change fields from a form, the way Drupal like it is to do it with `hook_form_alter` – Marius Ilie Nov 17 '11 at 10:13
  • API doc is wrong and misguiding http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/6#disabled – Sivaji Oct 08 '12 at 07:36
  • Sivaji - you are linking the D6 API doc, not D7. – Ted Jan 15 '14 at 15:30
  • 1
    There is a #disabled parameter in Form API https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#disabled – Capi Etheriel May 09 '14 at 18:16
2

Like it said in the docs

You can use attributes :

$form['#attributes'] = array('disabled' => TRUE);
Reign.85
  • 2,420
  • 1
  • 28
  • 28