Friday, September 18, 2009

Make a CCK field become hidden while creating a content type (node)

Make a CCK field become hidden while creating a content type (node)

Method 1: computed field

Method 2: use the content permissions module and don't give the view field permission to whatever roles you don't want to see it.

Method 3: CCK-specific hooks

Method 4:
<?php
/**
* Implementation of hook_form_alter().
*/
hook_form_alter() {
  $form['field_CCK_Field_Name']['#prefix'] = "<div style='display: none;'>
";
  $form['field_CCK_Field_Name']['#suffix'] = "</div>
";
}
?>

Method 5:
Following code is able to make a CCK field becoming a hidden type field.

<?php
/**
* Implementation of hook_form_alter().
*/
function YourModuleName_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node'])) {
    ### Make a CCK field becoming a hidden type field.
    // ### Use this check to match node edit form for a particular content type.
    if ($form_id === 'YourContentTypeName_node_form') {
      $form['field_NameToBeHidden'][0]['#default_value']['value'] = 2012;
      $form['#after_build'] = array('_test_set_cck_field_to_hidden');
    }
  }
}

/**
*
* @param
* @return
*/
function _test_set_cck_field_to_hidden($form, &$form_state) {
  $form['field_NameToBeHidden'][0]['value']['#type'] = 'hidden';
  $form['field_NameToBeHidden'][0]['#value']['value'] = 'testValue';

  return $form;
}
?>

Something Related:
You should be able to alter #default_value attribute for any element in the form directly from hook_form_alter().

<?php
function mymodule_form_alter(&$form, $form_state, $form_id) {
  // Is this the node edit form?
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
    if ( /* whatever else condition to find the form you're interested in */ ) {
      // The field is at the top level of the form?
      if (isset($form['field_myfield'])) {
        // Assign here whatever suits your needs.
        $form['field_myfield']['#default_value'] = 'myvalue';
      }
      // The field is inside a fieldgroup?
      if (isset($form['group_mygroup']['field_myfield'])) {
        // Assign here whatever suits your needs.
        $form['group_mygroup']['field_myfield']['#default_value'] = 'myvalue';
      }
    }
  }
}
?>

However, you should be sure that your module is loaded after the one that generates the form you intend to alter. You can do this by altering the weight of the module in the {system} table from the hook_install() of your module. See the fieldgroup module in CCK to see an example of this.

<?php
/**
* Something like this should be placed in your mymodule.install
*/
function mymodule_install() {
  db_query("UPDATE {system} SET weight = 10 WHERE name = 'mymodule'");
}
?>

Reference: http://drupal.org/node/357328

No comments: