0

I'm helping to convert a Drupal 7 module across to Drupal 8 and getting an error on the install.

Fatal error: Call to undefined function field_create_instance()

I've seen in the Drupal 7 database that a table is created for field_first_name as field_data_field_first_name. Does this still happen in Drupal 8?

I resolved the fact that field_info_field() and field_info_instance() are now deprecated in Drupal 8 and have updated accordingly with \Drupal::entityManager()->getFieldMap() and FieldConfig::loadByName() respectively, but I can't find anything to suggest what to use instead of field_create_instance(); can someone suggest how I get around this?

My code is this.

/**
 * Implements hook_install().
 *
 * Adds custom fields used by module.
 */
function indicia_api_install() {
  $fields = array(
    'field_indicia_user_id' => (object) array(
      'type' => 'number_integer',
      'title' => 'User ID for this key on the warehouse',
      'name' => 'field_indicia_user_id',
    ),
  );

  foreach ($fields as $fielddef) {
    if (!\Drupal::entityManager()->getFieldMap($fielddef->name)) {
      \Drupal::logger('ima', 'Adding field: ' . $fielddef->name);
      $field = array(
        'field_name' => $fielddef->name,
        'type' => $fielddef->type,
      );
      if (isset($fielddef->required)) {
        $field['settings'] = array('required' => TRUE);
      }
      field_create_field($field);
    }
    else {
      \Drupal::logger('ima', 'Field already exists: ' . $fielddef->name);
    }
    if (!FieldConfig::loadByName('user', $fielddef->name, 'user')) {
      \Drupal::logger('ima', 'Adding instance: ' . $fielddef->name);
      $instance = array(
        'field_name' => $fielddef->name,
        'entity_type' => 'user',
        'label' => $fielddef->title,
        'bundle' => 'user',
        'required' => isset($fielddef->required) && $fielddef->required,
      );
      field_create_instance($instance);
    }
    else {
      \Drupal::logger('ima', 'Instance already exists: ' . $fielddef->name);
    }
  }
}
0

Just to update this question, if anyone else comes across this - I worked out the solution in the end. Rather than implementing the hook_install() function I added the field information to the config/install/ folder which adds the necessary user fields instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.