Setting default values for Drupal 7 fields

I spent about an hour this afternoon exploring the new Drupal Fields API, which sprung from the migration of CCK into Drupal core. The documentation is, shall we say, less than stellar. So for the Googling masses, here's a quick helper on setting default values to field instances.

<?php
$i
= array(
       
'field_name' => $field_name,
       
'bundle' => 'nodetype',
       
'entity_type' => 'node',
       
'label' => 'label',
       
'required' => TRUE,
       
'default_value' => array(0 => array('value' => 3)),
);

field_create_instance($i);
?>

I had tried the code on this page to no avail... it appears you need to explicitly set the 0 index, instead of just nesting the arrays. This example is for an integer field, obviously.

Comments

I couldn make it work :\

I couldn make it work :\

4 => t('Option four'),
5 => t('Option five'),

),

'#description' => t('Select at least two options'),
'#required' => True,
'#default_value' => array(0 => array('value' => 'Option five')),

I think that's how it works

'#default_value' => array(0,1);