You are here

public function DbtngExampleRepository::insert in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/dbtng_example/src/DbtngExampleRepository.php \Drupal\dbtng_example\DbtngExampleRepository::insert()

Save an entry in the database.

Exception handling is shown in this example. It could be simplified without the try/catch blocks, but since an insert will throw an exception and terminate your application if the exception is not handled, it is best to employ try/catch.

Parameters

array $entry: An array containing all the fields of the database record.

Return value

int The number of updated rows.

Throws

\Exception When the database insert fails.

File

dbtng_example/src/DbtngExampleRepository.php, line 73

Class

DbtngExampleRepository
Repository for database-related helper methods for our example.

Namespace

Drupal\dbtng_example

Code

public function insert(array $entry) {
  try {
    $return_value = $this->connection
      ->insert('dbtng_example')
      ->fields($entry)
      ->execute();
  } catch (\Exception $e) {
    $this
      ->messenger()
      ->addMessage($this
      ->t('Insert failed. Message = %message', [
      '%message' => $e
        ->getMessage(),
    ]), 'error');
  }
  return $return_value ?? NULL;
}