0

I am trying to write my own module to add a content type with the help of node_example and this page. I made small tweaks and got it to work, yet I cannot find any example to create a select box as a field, and I failed in my each attempt. I have also checked the official documentation for field_create_field, still no clues.

Is there any documentation or sample you can guide me?

1 Answer 1

2

Something like this should work:

// Create field definition
$field = field_info_field('field_my_select_field');
if (empty($field)) {
  $field = array(
    'active' => '1',
    'cardinality' => '1',
    'deleted' => '0',
    'entity_types' => array(),
    'field_name' => 'field_my_select_field',
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values' => array(
        'Yes' => 'Yes',
        'No' => 'No',
      ),
      'allowed_values_function' => '',
    ),
    'translatable' => '0',
    'type' => 'list_text',
  );

  $field = field_create_field($field);
  drupal_set_message('Created field_my_select_field');
}

// Create field instance on entity bundle
if(!field_info_instance('node', 'field_my_select_field', 'my_node_type')){
  $instance = array(
    'bundle' => 'terms',
    'default_value' => array(
      0 => array(
        'value' => 'Yes',
      ),
    ),
    'deleted' => '0',
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'hidden',
        'module' => 'list',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => '4',
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_my_select_field',
    'label' => 'My field label',
    'required' => 0,
    'settings' => array(),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '3',
    ),
  );
  field_create_instance($instance);
  drupal_set_message("Added field_my_select_field field to node");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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