How do I programatically add a field to a node? I'm trying to create custom Drupal 7 module. In the form setting for the module I have checkboxes where the admin can select multiple content types:



After installing the module I need to automatically create two fields (Price of type decimal (4,2), and currency of type text) only in the 'content types' the admin has selected from the list above. 

And this is how I set the content type to the checkboxes list in the mymodule_payment_admin_settings_form hook in mymodule.module:

 $form['test_content_types'] = array(
      '#type' =&gt; 'checkboxes',
      '#options' =&gt; drupal_map_assoc(node_type_get_names()),
      '#default_value' =&gt; variable_get('test_content_types'),
      '#required' =&gt; TRUE
    );
You need your own form ideally, right now you have a system_settings_form. That's typically for only setting variables and really simple stuff like that. see the documentation on system_settings_forms.

Instead you probably want to create and use a custom menu callback (you've already done that) which has a callback to a custom form you've defined. See the general drupal FAPI guide.

With your own form you create a submit callback. In that callback you take the selected node types and just create and assign instances of drupal fields to them. So you have to do 2 things: 1) create the fields, 2) assign them to the content types (entity bundles).

The form submit callback could look like this (not 100% tested code, fill in the blanks, add validation, etc):

function mymodule_form_submit($form, &amp;$form_state) {
  if (!field_info_field('field_price')) {
    # Create field singleton
    $field = array('field_name' =&gt; 'field_price', 'type' =&gt; 'number_decimal',);
    $field = field_create_field($field);
  }
  if (!field_info_field('field_price')) {
    # Create field singleton
    $field2 = array('field_name' =&gt; 'field_type_of_currency', 'type' =&gt; 'option',);
    $field2 = field_create_field($field2);
  }

  foreach ($form_state['values']['content_type'] as $machine_id =&gt; $machine_name) {
    # Create instance on bundle.
    $instance['field_price'] = array(
      'field_name' =&gt; $field['field_name'],
      'entity_type' =&gt; 'node',
      'bundle' =&gt; $machine_id,
      'label' =&gt; 'Price',
      'description' =&gt; 'The price of an item.',
      'required' =&gt; FALSE,
      'settings' =&gt; array(),
      'widget' =&gt; array(
        'type' =&gt; 'textfield',
      ),
      'display' =&gt; array(
        'default' =&gt; array('label' =&gt; 'hidden'),
      ),
    );
    // ... same instance code for currancy type field instance.
    // $instance['field_currency_type'] = ...;

    foreach ($instance as $instance_field){
      field_create_instance($instance_field);
    }
  }
}