How to add user-fields programmatically in Drupal 7
I'm trying to create a .install for a module that I'm migrating from Drupal 6. It requires two 'profile fields', which, in drupal 6, it checked for and created automatically.
To upgrade it to drupal 7 I'm trying to do this with fields! Easy enough right?
So far I have
if(!field_info_field('user_fullname')) {
$field = array(
'field_name' => 'user_fullname',
'type' => 'text',
'settings' => array(
'required' => TRUE,
),
);
field_create_field($field);
$instance = array(
'field_name' => 'user_fullname',
'entity_type' => 'user',
'label' => 'The user\'s full name',
'bundle' => 'additional_info',
'required' => true,
'开发者_开发知识库widget' => array(
'type'=>'options_select',
)
);
field_create_instance($instance);
}
Which, sure enough, creates the field, but it's not visible in the user's profile?
Do I need something additional for that? If so, What?Many Thanks.
SOLVED: It was due to the bundle (not entirely sure what a bundle is really), I changed the bundle to 'user' and it appeared!
bundle is pretty much the same as content type. But since in D7 users are entities too, but they are not content, using the term 'content type' didn't make sense. Reference: Barry Jaspan's DrupalCon Paris 2009 Session: Intro to the Field API for Module Developers.
Intro to the Field API for Module Developers
It was due to the bundle (not entirely sure what a bundle is really), I changed the bundle to 'user' and it appeared!
As I know in D7 the bundles are something like a model for an entity and it can have fields. The default drupal bundles are node, user and taxonomy but the new API provides the developer to create custom bundles too. Every field needs to belong to a bundle.
A bundle in Drupal is a subset of the entity. In this case the entity type is User and there is only one type of User so the bundle is User.
In Taxonomy: the Taxonomy is the Entity and the Vocabularies are the bundles.
In Nodes: Nodes are the Entity and Content Types are the bundles.
No field can be attached to an entity, properties are attached to the entity (published, sticky, etc). Fields are attached to the Bundles.
I don't have enough rep to comment, so here is my answer for those you find this via google. As I did.
精彩评论