Last updated June 26, 2012. Created by chx on May 27, 2009.
Edited by Jupiter, Liam McDermott, TR, CrookedNumber. Log in to edit this page.
Let's begin with creating a last name field. We will add this to users and to the 'picture' node type so that it's possible to put names on them even if the author is not a user.
Our field type will be text. This will be stored in SQL (which is the default):
<?php
$field = array(
// It is strongly advised to prefix the field name with the name of the module
// that defines it, to avoid name clashes. Fields created through Field UI are
// prefixed with 'field_'
'field_name' => 'mymodule_lastname',
'type' => 'text',
'cardinality' => 1, // Not required, as it's the default
);
field_create_field($field);
?>Users will use common HTML text input fields to enter the data -- this is called a widget. We will format these as Plain text -- we do not need HTML tags in there.
<?php
$instance = array(
'field_name' => 'mymodule_lastname',
'entity_type' => 'user',
'bundle' => 'user',
'label' => t('Last name'),
'description' => t('You can enter your last name here.'),
'widget' => array(
'type' => 'text_textfield',
'weight' => 10,
),
);
field_create_instance($instance);
?>Now to attach the same field to another bundle (here, node type 'picture'), that's very easy:
<?php
$instance['entity_type'] = 'node';
$instance['bundle'] = 'picture';
field_create_instance($instance);
?>An example of a select field:
<?php
$field = array(
'field_name' => 'name_of_field',
'type' => 'list_text',
'settings' => array(
'allowed_values' => array(
'key_1' => t('Value 1'),
'key_2' => t('Value 2'),
'key_3' => t('Value 3'),
),
);
field_create_field($field);
$instance = array(
'field_name' => 'name_of_field',
'label' => t('The label'),
'bundle' => 'the_bundle',
'widget' => array(
'type' => 'options_select',
),
);
field_create_instance($instance);
?>
Comments
where to put this code?
Can you explain please where I will need to put this code to see the fields in action? I am learning drupal. I have learned about Form API and its related stuff, but now I want to know where to put and try this example.
This would typically be done in the hook_install() function...
...of the module providing the entity to which you are adding fields.