简体   繁体   中英

How to hide a field in a Drupal form

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?

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.

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>";

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM