Community Documentation

Adding and reusing a field

Last updated July 15, 2011. Created by chx on May 27, 2009.
Edited by Liam McDermott, TR, CrookedNumber, Magnity. 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);
?>