I'm trying to create a field after a node has been created, but it does not look possible:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1305 SAVEPOINT savepoint_1 does not exist in field_read_instances() (line 703 of /var/www/drupal-7.2/modules/field/field.crud.inc).

Just creating a simple field and field instance for a node type in hook_insert():

/**
 * Implements hook_insert().
 */
function item_insert($node) {
  // Create a field named 'Last name'
  $field = array(
    'field_name' => 'page_name',
    'type' => 'text',
  );
  field_create_field($field);
  
  // Enable the field for node type 'Client profile'
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'page',
    'label' => t('Name'),
    'description' => '',
    'widget' => array(
      'type' => 'text_textfield',
      'settings' => array(
        'size' => 24,
      ),
      'weight' => 0,
    ),
  );
  field_create_instance($instance);
}

It passed through field_create_field(), and created a new field, but a field instance could not be added. It works if I place it inside hook_view().

Why inserting a field instance during node insert will cause PDOException error?

Comments

nevets’s picture

The error suggests a transaction error. I wonder if it's caused by operating on an entity (node) while it's in use. It does seem like an odd place to try and add a field or an instance.

realguess’s picture

Operating on an entity (node) while it's in use.

Why not? I'm not operating on the same bundle. And field was created, just not the instance being attached. And yes, it's a bit odd, but every time a new node is inserted, a new field instance is created for tracking the node (so need node ID), that was my thought.

Thinking about other ways around it, if can't solve the error. Thanks!

nevets’s picture

Not sure what your goal is but in general if I was tracking nodes I would make a table with a field for 'nid' and other fields as needed.

Note in your code you are trying to create the same instance on each call.

realguess’s picture

Thanks! I think I am taking an approach similar to your suggestion. It looks like when you're operating on an entity, it's locked, other entity operation cannot be performed at the same time. I tried to create an taxonomy vocabulary, which is a different entity, but still showing similar error. However, the vocabulary was created.

Entity is still new to me in D7.