Hi, I'd like to programmatically add a read-only field, named zoho_comment_id to the Comment Fields of the already existing content type Support ticket (Machine name: support_ticket). I'd like the field to be added automatically when my module is enabled and deleted automatically when my module is disabled. What do I need to do? How to write code for it? Please help me. Thanks.

Comments

drupal_dev_2014’s picture

ok I found this tutorial http://www.monarchdigital.com/blog/2013-08-09/programmatically-creating-... which instructs me some basic steps to create a field. Based on its guideline, I created my field as below.

<?php
  $field_name
= 'zoho_comment_id';
 
 
// Make sure the field doesn't already exist.
 
if (!field_info_field($field_name)) {
     
// Create the field.
     
$field = array(
       
'field_name' => $field_name,
       
'type' => 'text',
       
'settings' => array(
         
'max_length' => 64,
        ),
      );
     
field_create_field($field);
 
     
// Create the instance.
     
$instance = array(
       
'field_name' => $field_name,
       
'entity_type' => 'node',
       
'bundle' => 'support_ticket',
       
'label' => 'Zoho Comment ID',
       
'description' => 'Zoho Comment ID',
       
'required' => TRUE,
      );
 
     
field_create_instance($instance);
     
watchdog('zoho', t('!field_name was added successfully.', array('!field_name' => $field_name)));
  }
  else {
   
watchdog('zoho', t('!field_name already exists.', array('!field_name' => $field_name)));
  }
?>

There are 2 problems that

- my zoho_comment_id field is visible, while I want it to be hidden.
- my zoho_comment_id field displays in the Manage Fields tab of Support Ticket content type, while I want it to display in the Comment Fields tab.

What do I need to do with this? What should I change in my code? Please help me.
Thanks

Jaypan’s picture

- my zoho_comment_id field is visible, while I want it to be hidden.

You will need to implement hook_form_alter() and set the type of the field to be either 'value' or 'hidden'. Unless you specifically need it to be rendered in the HTML as an <input type="hidden">, I'd suggest setting it as 'value', which means the value will be stored on the server where the user cannot change it.

- my zoho_comment_id field displays in the Manage Fields tab of Support Ticket content type, while I want it to display in the Comment Fields tab.

It sounds like you need to attach your field to the comment entity, not the node entity as you are doing now.

drupal_dev_2014’s picture

Thanks. I finally managed to add it. I use another module, named Field Hidden, to assist me in adding a hidden field. That works. And I finally managed to add it into the comment section too. Thanks for your help.