Skip to main content

Posts

Showing posts from May, 2018

Add JOIN tables in views query alter in Drupal 8

How to add join condition in views programmatically in Drupal 8? use $query->queueTable to implement joins. function hook_views_query_alterViewExecutable $views, QueryPluginBase $query) { $query->queueTable('node__field_accounts', "node_field_data", NULL, 'node__field_accounts'); $query->addWhere($where_last_key, 'node__field_accounts.field_accounts_target_id', $account_values['target_id'], 'IN'); } Method definition Sql::queueTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL) To use INNER JOIN $configuration = [ 'type' => 'INNER', 'table' => 'user__field_region', 'field' => 'entity_id', 'left_table' => 'users_field_data', 'left_field' => 'uid', 'operator' => '=', ]; $join = Views::pluginManager('join') ->...

How to inject database connection in Drupal 8

Database connection can be injected in class object using dependency injection. We can also use service method \Drupal::database() This way of using database is suitable for XXX.module file but in class we can use dependency injection. Using dependency injection :- Drupal\Core\Database\Connection class for database connection. use Drupal\Core\Database\Connection; use Symfony\Component\DependencyInjection\ContainerInterface; class CustomClass { /** * The database connection to be used. * * @var \Drupal\Core\Database\Connection */ protected $database; /** * @param \Drupal\Core\Database\Connection $database * The database connection to be used. */ public function __construct(Connection $database) { $this->database = $database; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { $container->get('database') } } $container->get('database') here database is the ...