Adding and reusing a field
Last modified: November 25, 2009 - 22:44
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. We will store this in SQL, which is the default anyways:
<?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' => 'lastname',
'object_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['object_type'] = 'node';
$instance['bundle'] = 'picture';
field_create_instance($instance);
?>
object_type is required
The instance array needs an
object_typeelement:<?php$instance = array(
'field_name' => 'lastname',
'bundle' => 'user',
'object_type' => 'node',
'label' => t('Last name'),
'description' => t('You can enter your last name here.'),
'weight' => 10,
'widget' => array(
'type' => 'text_textfield',
'label' => t('Last name'),
),
);
field_create_instance($instance);
?>
Martin Tomes
Fixed in the article. Thanks
Fixed in the article. Thanks !