You are here

function _serial_init_old_entities in Serial Field 7

Initializes the value of a new serial field in existing entities.

Parameters

string $entity_type: Type of entity (e.g. node)

string $bundle: Containing bundle (e.g. content type).

string $field_name: The field name.

Return value

int Number of existing entities that have been initialized.

1 call to _serial_init_old_entities()
serial_field_create_instance in ./serial.module
Implements hook_field_create_instance().

File

./serial.inc, line 199
Internal functions for the Serial module.

Code

function _serial_init_old_entities($entity_type, $bundle, $field_name) {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', $entity_type)
    ->fieldCondition($field_name);

  // The "comment" entity type does not support bundle conditions.
  // @see https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AentityCondition/7
  if ('comment' !== $entity_type) {
    $query
      ->entityCondition('bundle', $bundle);
  }
  $results = $query
    ->execute();
  if (!empty($results[$entity_type])) {
    foreach ($results[$entity_type] as $entity) {
      list($id, , $bundle) = entity_extract_ids($entity_type, $entity);
      $entity = entity_load_unchanged($entity_type, $id);
      $entity->{$field_name} = array(
        LANGUAGE_NONE => array(
          array(
            'value' => _serial_generate_value($entity_type, $bundle, $field_name, FALSE),
          ),
        ),
      );
      field_attach_insert($entity_type, $entity);
    }
    return count($results[$entity_type]);
  }
  return 0;
}