Programmatically add checkbox field to a node type in Drupal 7

Recently I wanted to programmatically add a checkbox field to a node type, depending on a certain set of circumstances. 

To do this I needed to use the field_create_field() function to create the field, and then field_create_instance() to add that field to a content type. I created the following field array:

$field = array( 
  'field_name' => 'field_premium_content',
  'cardinality' => 1,
  'entity_type' => 'node',
  'type' => 'list_boolean',
  'description' => 'Is this content premium content requiring subscription?',
  'label' => 'Premium Content',  
  'widget' => array(
    'type' => 'options_onoff',
  ),
);

After I'd ran this array through the two functions the field displayed correctly in a node edit form for any node of that particular node type, however upon saving the node and going back to edit it - no value had been saved. After some time I finally figured out what the problem was, and it is that for a list_boolean field type, there are no default values set, and you have define what the allowed values will be at the creation stage. So I changed my field array to the following:

$field = array( 
  'field_name' => 'field_premium_content',
  'cardinality' => 1,
  'entity_type' => 'node', 
  'entity_type' => 'node', 
  'type' => 'list_boolean',
  'description' => 'Is this content premium content requiring subscription?',
  'label' => 'Premium Content',  
  'widget' => array(
    'type' => 'options_onoff',
  ),
  'settings' => array(
    'allowed_values' => array(
      '0' => 'No',
      '1' => 'Yes',
    ),
  ),
);

Once I'd done this and re-ran the code to add the field to that content type - the field now displays the 'Yes' value next to the tick box and saving the node now records the value for that field.

Comments