Add allowed values list programmatically in drupal 7 CCK field "list_text"

thandem picture thandem · Nov 20, 2012 · Viewed 7.3k times · Source

I was wondering if i can create programmatically a CCK field instance and insert the "allowed_values" in a single stage. So i tried this:

 field_create_instance(array(
  'field_name' => 'card number',
  'entity_type' => 'payment_method',
  'bundle' => 'debit_card',
  'label' => t('Debit/Credit card'),
  'description' => t('Add card\'s number '),
  'widget' => array(
      'type' => 'options_select',
      'weight' => 0,
      'settings' => array('size' => 50),
   ),
  'required' => TRUE,
 ));

I've tried some case i.e to set in 'setting' => array( 'allowed_values' => array( 1, 2, 3 ) ) but nothing happened. Any suggestions?

Answer

thandem picture thandem · Jan 13, 2013

Solution:

function MY_MODULE_install() {
  field_create_field(array(
    'field_name' => 'months',
    'type' => 'list_text',
    'cardinality' => 1,
    'settings' => array('allowed_values_function' => 'get_months'),
  'entity_types' => array('user', 'node'),
));
}

function get_months() {
  $months = array( '01', '02', '03',...'12');
  return $months;
}

Warning: Callback function must always be in *.module file of your custom module.