8

Say I have this field, "map_description". I know I would this function to define the field:

$field = array(
  'field_name' => 'map_description',
  'cardinality' => 1,
  'type' => 'text',
);
field_create_field($field);

And I have this code which I'm not sure what it does but I'm told that I'll need it:

 $instance = array(
    'field_name' => 'map_description',
    'label' => 'The map description.',
    'bundle' => 'my_content_type',
    'entity_type' => 'node',
    'widget' => array(
    'type' => 'text_textfield',
 );
 field_create_instance($instance)

Those two code bits are both in my install hook and run when I install the module. But while the fields are in fact created, I have to manually assign them to the content type via "manage fields", is there a way to have the fields automatically assigned to the content type?

10

You're almost there.

From your code:

'bundle' => 'my_content_type',

Replace my_content_type with the name of the content type you want it attached to.

Here's a full example of adding a Alias text field to the Article content type. (from monarchdigital.com)

/**
 * Update hook to add a field to a node.
 */
function my_module_update_7000() {
  $field_name = 'field_alias';
  // 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' => 'article',
      'label' => 'Alias',
      'description' => 'The article alias.',
      'required' => TRUE,
    );
    field_create_instance($instance);

    watchdog('my_module', t('!field_name was added successfully.', array('!field_name' => $field_name)));
  }
  else {
    watchdog('my_module', t('!field_name already exists.', array('!field_name' => $field_name)));
  }
}
0

Make small changes in your code .In Fields

$t = get_t();
$field = array(
   'field_name' => 'map_description',
    'label' => $t('My Description'),
    'type' => 'text',

);
field_create_field($field);

& Write this in Instance

$t = get_t();
return array(
  'map_description' => array(
    'field_name' => 'map_description',
    'type' => 'text',
    'label' => $t('Map Description'),
    'bundle' => 'your_custom_content_type',
    'entity_type' => 'node',
    'widget' => array(
      'type' => 'text_textfield'
    ),
    'display' => array(
      'example_node_list' => array(
        'label' => $t('Map Description'),
        'type' => 'text'
      )
    )
  ),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.