6

I am trying to add a checkbox field to user entities using the FIELD API (in function MYMODULE_install() )

I can create the field, but I can't pre-load it with the desired default values.

Where my code is wrong ?

$default_notification_field_name = "field_notification_defaults";
if(!field_info_field($default_notification_field_name))   { // check if the field already exists.

    field_create_field(
        array(
            'field_name' => $default_notification_field_name,
            'cardinality' => FIELD_CARDINALITY_UNLIMITED,
            'type' => 'list_text',
            'settings' => array(
                'allowed_values' => array(
                    'group' => t('Groups to which you subscribe'),
                    'content' => t('Authored content'),
                    'comment' => t('Replies to your comments')
                )
            ),
        )
    );

    field_create_instance(
        array(
            'field_name' => $default_notification_field_name,
            'entity_type' => 'user',
            'bundle' => 'user',
            'label' => t('Default settings for notifications'), 
            'description' => t('Select the ​​default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
            'required' => FALSE,
            'widget' => array(
                'type' => 'options_buttons',
            ),
            'default_value' => array('content','comment')
        )
    );
}
6

Try this for your instance creation:

field_create_instance(
  array(
    'field_name' => $default_notification_field_name,
    'entity_type' => 'user',
    'bundle' => 'user',
    'label' => t('Default settings for notifications'), 
    'description' => t('Select the ​​default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
    'required' => FALSE,
    'widget' => array(
      'type' => 'options_buttons',
    ),
    'default_value' => array(
      0 => array(
        'value' => 'comment',
      ),
      1 => array(
        'value' => 'content',
      ),
    ),
  ));

To assist you in knowing the array structure, try this:

  1. Install the devel module
  2. Go to the page /devel/php on your site
  3. Run this code to see all field information on your site:
// Show all fields.
dpm(field_info_fields());
// Show all field instances.
dpm(field_info_instances());
| improve this answer | |

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.