Wednesday, June 19, 2013

Creating a link field programmatically for a profile2 user entity and deleting it upon disable or uninstall

In this example I have a profile2 profile called "werkgever"

The field I'm creating is a field used for that profile to input a website link.

required modules are
link
profile2

My module name is more_werkgever_fields

Using hook_enable I create the field:
/**
 * Implementation of hook_enable().
 */
function more_werkgever_fields_enable() {
  // Check if our field is not already created and if not create the field.
  if (!field_info_field('field_website')) {
    $field = array(
        'field_name' => 'field_website',
        'type' => 'link_field', // text
    );
    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
      'field_name' => 'field_website',
      'entity_type' => 'profile2',
      'label' => 'Website',
      'bundle' => 'werkgever',
      'required' => FALSE, // default: FALSE
      'settings' => array(
         // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      // 'widget' => array(
      //   'type' => 'link',
      // ),
    );
    field_create_instance($instance);
  }
}

This needs to be put in your modulename.install file

Also in the .install file you can implement a hook_disable or hook_uninstall
hook_disable is called when you disable the module. So this is handy if you are in a developing stage.
Just disable de module and your field should be gone.
An implementation of hook_disable:
/**
 * Implements hook_disable
 */
function more_werkgever_fields_disable(){
  // removes field when module is disabled
  field_delete_field('field_website');
}
As said this goes into your module.install file as well
Finally there is the Implementation of hook_uninstall:
/**
 * Implements hook_uninstall
 */
function more_werkgever_fields_uninstall(){
  field_delete_field('field_website'); // removes field from the system
}
The uninstall hook is only called upon uninstalling the module. I recommend putting your delete field in here. Or don't delete your field. Depending if your your module can be reused by others and maybe causing problems if that field is to be deleted. In my case I don't want it to clutter my database so I put it in my uninstall hook.

No comments:

Post a Comment