You are here

public function Table::addField in Data 8

Add a field.

@todo: Check wether field name is available, otherwise change.

Throws

DataException

File

src/Table.php, line 261

Class

Table
Manages data access and manipulation for a single data table. Use data_create_table() or data_get_table() to instantiate an object from this class.

Namespace

Drupal\data

Code

public function addField($field, $spec) {
  try {
    \Drupal::database()
      ->schema()
      ->addField($this->name, $field, $spec);
    $schema = $this->table_schema;
    $schema['fields'][$field] = $spec;
    $this
      ->update(array(
      'table_schema' => $schema,
    ));

    // @todo: use clearCaches().
    drupal_get_schema($this->name, TRUE);

    // Invalidate views caches to use new field immediately.
    if (function_exists('views_invalidate_cache')) {
      views_invalidate_cache();
    }
    return $field;
  } catch (DatabaseSchemaObjectExistsException $e) {
    throw new DataException(t('Error adding field.'));
  }
  throw new DataException(t('Error adding field.'));
}