How to hide a field in a Drupal form

13,569

Solution 1

You can use hook_form_alter. Which you can programmatically alter the contents of the form api build. This gives you the full $form array of which you can simply unset($form['the_field_you_dont_want']);.

But the easier way to get rid of the body field is in the edit content type there is a field labelled 'Body field label:' just leave this blank and the body field will be omitted.

Solution 2

unset seems to destroy the value as well, as does the #access property. I just use this to hide a field (in this case a reference if it was preset using the URL:

$form['field_reference']['#prefix'] = "<div class='hide'>";
$form['field_reference']['#suffix'] = "</div>";

Solution 3

The solution found here https://drupal.stackexchange.com/questions/11237/hide-field-in-node-add-page works great for me. Here I am repeating moon.watcher's solution:

function test_remove_filed_form_alter(&$form, &$form_state) {

    if (arg(0) == 'node' && arg(1) == 'add') {
    $form['field_test']['#access'] = 0;
    }

}

The disadvantage of using unset() is that it will entirely remove the field and you can't further on like, for example, on node presave. In my case, I just wanted to remove the field from the form on the first moment, but I wanted to populate it later on, prior to saving the node. The solution on the link above works perfect for me for this reason.

Solution 4

Did you implement the content type within a module (using hook_node_info)? If so, set the has_body attribute to false.

Share:
13,569

Related videos on Youtube

mimrock
Author by

mimrock

Updated on June 04, 2022

Comments

  • mimrock
    mimrock almost 2 years

    I have a specific content type in drupal6. I want to implement a hook, which hides the body field of that content type from the add form, but not from the edit form. How can I do that?

  • Eduard Luca
    Eduard Luca almost 12 years
    I did this too, but then, if the user knows CSS, he can see the fields, and if you do this on the edit user page, he can even edit the fields. It's a stupid implementation, cause #access=0 shouldn't destroy it. Maybe a feature request for Drupal 8? :)

Related