View source
<?php
namespace Drupal\civicrm_entity\Plugin\views\argument_default;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\views\Plugin\views\argument_default\ArgumentDefaultPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\civicrm_entity\CiviCrmApiInterface;
class ContactSubtype extends ArgumentDefaultPluginBase implements CacheableDependencyInterface {
protected $currentUser;
protected $civicrmApi;
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxy $currentUser, CiviCrmApiInterface $civicrmApi) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $currentUser;
$this->civicrmApi = $civicrmApi;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_user'), $container
->get('civicrm_entity.api'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['no_subtype'] = [
'default' => 'none',
];
$options['multiple_subtype'] = [
'default' => 'first',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['no_subtype'] = [
'#type' => 'radios',
'#title' => $this
->t('When logged in user has no contact subtype'),
'#default_value' => $this->options['no_subtype'],
'#options' => [
'none' => $this
->t('Show none'),
'all' => $this
->t('Show all'),
],
];
$form['multiple_subtype'] = [
'#type' => 'radios',
'#title' => $this
->t('When logged in user has multiple contact subtypes'),
'#description' => $this
->t('Multiple contact subtypes requires multiple values to be set for the contextual filter (see MORE below.)'),
'#default_value' => $this->options['multiple_subtype'],
'#options' => [
'first' => $this
->t('Match first'),
'any' => $this
->t('Match any'),
],
];
}
public function getArgument() {
$current_user_contact_subtype = $this->options['no_subtype'] == 'none' ? '<none>' : 'all';
$results = $this->civicrmApi
->get('UFMatch', [
'sequential' => 1,
'id' => $this->currentUser
->id(),
]);
if (!empty($results) && !empty($results[0]['contact_id'])) {
$cid = $results[0]['contact_id'];
$results = $this->civicrmApi
->get('contact', [
'sequential' => 1,
'return' => [
'contact_sub_type',
],
'id' => $cid,
]);
if (!empty($results) && !empty($results[0]['contact_sub_type'])) {
if ($this->options['multiple_subtype'] == 'first') {
$current_user_contact_subtype = reset($results[0]['contact_sub_type']);
}
else {
$current_user_contact_subtype = implode('+', $results[0]['contact_sub_type']);
}
}
}
return $current_user_contact_subtype;
}
public function getCacheMaxAge() {
return Cache::PERMANENT;
}
public function getCacheContexts() {
return [
'user',
];
}
}