Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/4.0.x' into 4.0.x-pathauto
Browse files Browse the repository at this point in the history
* origin/4.0.x:
  4.0.x field mappings (eileenmcnaughton#430)
  Adding a raw value function to return value from values array (eileenmcnaughton#465)
  Add filter for state province. (eileenmcnaughton#453)
  Update default timezone handling for dates in CiviEntityStorage.php (eileenmcnaughton#461)
  fix testLoadContact birthdate assertion (eileenmcnaughton#472)
  port to 4.0.x from 436: Include dblocale table names in list of civicrm entity info (eileenmcnaughton#438)
  Ignore convert to UTC if custom field is date only (eileenmcnaughton#469)
  update contact entity referece field on contact merge (eileenmcnaughton#456)
  update test versions of Drupal 10.2 and CiviCRM 5.69 (eileenmcnaughton#468)
  Clean value on custom field for Float (Number) and Money field type (eileenmcnaughton#463)
  From eileenmcnaughton#378 for 4.0.x (eileenmcnaughton#466)
  Add reset to the file URLs generated. (eileenmcnaughton#458)
  fix Views field custom date field output for year only (eileenmcnaughton#439)
  • Loading branch information
puresyntax71 committed Apr 19, 2024
2 parents 574cdbc + 8a5b3de commit 28b8471
Show file tree
Hide file tree
Showing 15 changed files with 344 additions and 14 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ jobs:
fail-fast: false
matrix:
include:
- drupal: '10.0.*'
- drupal: '10.2.*'
civicrm: '5.69.*'
- drupal: '10.2.*'
civicrm: 'dev-master'
name: Drupal ${{ matrix.drupal }} | CiviCRM ${{ matrix.civicrm }}
services:
Expand Down
9 changes: 9 additions & 0 deletions civicrm_entity.libraries.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,12 @@ form:
css:
theme:
css/civicrm_entity.form.css: {}

states:
version: VERSION
js:
js/civicrm_entity.states.js: {}
dependencies:
- core/drupal
- core/jquery
- core/once
53 changes: 53 additions & 0 deletions civicrm_entity.module
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,59 @@ function civicrm_entity_search_api_datasource_info_alter(array &$infos) {
}
}

/**
* Implements hook_civicrm_merge().
*/
function civicrm_entity_civicrm_merge($mode, &$sqls, $mainId = NULL, $otherId = NULL, $tables = NULL) {
if ($mode == 'sqls' && !empty($mainId) && !empty($otherId)) {
// Get List if civicrm contact entity reference field.
$entityRefFields = \Drupal::entityTypeManager()->getStorage('field_storage_config')
->loadByProperties([
'type' => 'entity_reference',
'settings' => ['target_type' => 'civicrm_contact'],
]);

// Iterate fields and prepare the array.
foreach ($entityRefFields as $entityRefField) {
// Get Field name.
$fieldName = $entityRefField->getName();
// Get Type, Node etc..
$entityRefType = $entityRefField->getTargetEntityTypeId();
$options[$entityRefType][] = $fieldName;
}

foreach ($options as $type => $fields) {
foreach ($fields as $field) {
try {
// $otherId is duplicate contact ID
$ids = \Drupal::entityQuery($type)
->condition($field, $otherId, '=')
->accessCheck(FALSE)
->execute();
if (!empty($ids)) {
$entityRecords = Drupal::entityTypeManager()->getStorage($type)
->loadMultiple($ids);
foreach ($entityRecords as $entityRecord) {
// Update new contact.
// Target Contact.
try {
$entityRecord->set($field, $mainId);
$entityRecord->save();
}
catch (\Exception $e) {
\Drupal::logger('civicrm_entity')->error($e->getMessage());
}
}
}
}
catch (\Exception $e) {
\Drupal::logger('civicrm_entity')->error($e->getMessage());
}
}
}
}
}

/**
* Implements hook_query_TAG_alter().
*/
Expand Down
1 change: 1 addition & 0 deletions civicrm_entity.views.inc
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ function civicrm_entity_views_data_alter(&$data) {
$data['civicrm_contact']['current_employer']['real field'] = 'organization_name';
$data['civicrm_contact']['employer_id']['field']['id'] = 'standard';
$data['civicrm_contribution']['contribution_source']['real field'] = 'source';
$data['civicrm_address']['state_province_id']['filter']['id'] = 'civicrm_entity_civicrm_address_state_province';
}

/**
Expand Down
3 changes: 3 additions & 0 deletions config/schema/civicrm_entity.views.schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ views.filter_value.civicrm_entity_civicrm_address_proximity:
type: string
label: 'Distance unit'

views.filter.civicrm_entity_civicrm_address_state_province:
type: views.filter.many_to_one

views.argument_validator.entity:civicrm_contact:
type: views.argument_validator_entity
label: 'Civicrm contact'
Expand Down
33 changes: 33 additions & 0 deletions js/civicrm_entity.states.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @file
* civicrm_entity.states.js
*/

(function ($, Drupal) {

/**
* Sets states depending on the chosen country.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
*/
Drupal.behaviors.civicrmEntityStates = {
attach(context, settings) {
$(once('loadStates', '.views-exposed-form [data-drupal-selector="edit-' + settings.civicrm_entity.country_identifier + '"]', context)).on('change', function() {
var countries = $(this).val();

var $stateElement = $('[data-drupal-selector="edit-' + settings.civicrm_entity.states_identifier + '"]', $(this).parents('form'));
$stateElement.find('option').not(':first').remove();

if (countries != Drupal.t('All')) {
countries = Array.isArray(countries) ? countries : [countries];
countries.forEach((v) => {
$stateElement.append(settings.civicrm_entity.states[v]);
});
}
}).trigger('change');
},
};

})(jQuery, Drupal, drupalSettings);
33 changes: 25 additions & 8 deletions src/CiviEntityStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,17 +158,13 @@ protected function doLoadMultiple(array $ids = NULL) {

// Get all the fields.
$fields = $this->getCiviCrmApi()->getFields($this->entityType->get('civicrm_entity'));
$field_names = [];
foreach ($fields as $field) {
$field_names[] = $field['name'];
}

$ids = $this->cleanIds($ids);

if (!empty($ids)) {
$options = [
'id' => ['IN' => $ids],
'return' => $field_names,
'return' => array_keys($fields),
'options' => ['limit' => 0],
];

Expand All @@ -195,7 +191,14 @@ protected function doLoadMultiple(array $ids = NULL) {
$civicrm_entity = $temporary;
}

$entity = $this->prepareLoadedEntity($civicrm_entity);
$massaged_civicrm_entity = [];
foreach ($fields as $name => $field) {
if (isset($civicrm_entity[$name])) {
$massaged_civicrm_entity[$field['name']] = $civicrm_entity[$name];
}
}

$entity = $this->prepareLoadedEntity($civicrm_entity + $massaged_civicrm_entity);
$entities[$entity->id()] = $entity;
}
}
Expand Down Expand Up @@ -418,7 +421,7 @@ protected function initFieldValues(ContentEntityInterface $entity, array $values
}
else {
$datetime_format = $definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
$default_timezone = \Drupal::config('system.date')->get('timezone.default') ?? date_default_timezone_get();
$default_timezone = $definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::STORAGE_TIMEZONE : \Drupal::config('system.date')->get('timezone.default') ?? date_default_timezone_get();
$datetime_value = (new \DateTime($item[$main_property_name], new \DateTimeZone($default_timezone)))->setTimezone(new \DateTimeZone('UTC'))->format($datetime_format);
$item_values[$delta][$main_property_name] = $datetime_value;
}
Expand All @@ -429,7 +432,21 @@ protected function initFieldValues(ContentEntityInterface $entity, array $values

// Handle special cases for field definitions.
foreach ($field_definitions as $definition) {
if (($field_metadata = $definition->getSetting('civicrm_entity_field_metadata')) && isset($field_metadata['custom_group_id']) && $field_metadata['data_type'] === 'File') {
if (($field_metadata = $definition->getSetting('civicrm_entity_field_metadata')) && isset($field_metadata['custom_group_id']) && in_array($field_metadata['data_type'],['Float', 'Money'])) {
$items = $entity->get($definition->getName());
$item_values = $items->getValue();
if (!empty($item_values)) {
$ret = [];
foreach ($item_values as $value) {
$v = \CRM_Utils_Rule::cleanMoney($value['value']);
$ret[] = ['value' => $v];
}
if (!empty($ret)) {
$items->setValue($ret);
}
}
}
elseif (($field_metadata = $definition->getSetting('civicrm_entity_field_metadata')) && isset($field_metadata['custom_group_id']) && $field_metadata['data_type'] === 'File') {
$items = $entity->get($definition->getName());
$item_values = $items->getValue();

Expand Down
4 changes: 4 additions & 0 deletions src/Entity/CivicrmEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,8 @@ public function civicrmApiNormalize() {
return $params;
}

public function getRawValue($field) {
return $this->values[$field] ?? '';
}

}
35 changes: 35 additions & 0 deletions src/Plugin/Field/FieldFormatter/ContactReferenceFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Drupal\civicrm_entity\Plugin\Field\FieldFormatter;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter;
use Drupal\user\Entity\User;

/**
* Plugin implementation of the 'civicrm_entity_contact_reference' formatter.
*
* @FieldFormatter(
* id = "civicrm_entity_contact_reference",
* label = @Translation("CiviCRM custom contact reference field"),
* field_types = {
* "entity_reference",
* }
* )
*/
class ContactReferenceFormatter extends EntityReferenceLabelFormatter {

/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity) {
$permissions = [
'view all contacts',
'access all custom data'
];
$account = User::load(\Drupal::currentUser()->id());
return AccessResult::allowedIfHasPermissions($account, $permissions, 'OR');
}

}
42 changes: 40 additions & 2 deletions src/Plugin/views/field/CustomEntityField.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ protected function defineOptions() {
if (in_array($this->fieldMetadata['html_type'], ['Multi-Select', 'CheckBox'])) {
$options['type']['default'] = 'civicrm_entity_custom_multi_value';
}
if ($this->fieldMetadata['data_type'] == 'ContactReference') {
$options['type']['default'] = 'civicrm_entity_contact_reference';
}

return $options;
}
Expand Down Expand Up @@ -301,8 +304,7 @@ protected function getItemValue($value, FieldDefinitionInterface $definition) {
switch ($definition->getType()) {
case 'datetime':
if (!empty($value)) {
$datetime_format = $definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
return (new \DateTime($value, new \DateTimeZone(date_default_timezone_get())))->setTimezone(new \DateTimeZone('UTC'))->format($datetime_format);
return $this->convertToUtc($definition, $value);
}
break;

Expand Down Expand Up @@ -335,4 +337,40 @@ protected function getDelta($id) {
return 0;
}

/**
* Check if date field should be converted to UTC or not.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $definition
* The field definition.
* @param string $date_value
* The date value.
*
* @return string
* The converted value.
*/
public function convertToUtc(FieldDefinitionInterface $definition, $date_value) {
$datetime_format = $definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
$default_timezone = date_default_timezone_get();

$utc = TRUE;
// If the field is custom and meant to store only year value,
// Avoid converting to any timezone and display it as stored in database.
if (strpos($definition->getName(), "custom_") === 0) {
[, $custom_field_id] = explode('_', $definition->getName());
$params = [
'sequential' => 1,
'id' => $custom_field_id,
];
$date_field = $this->civicrmApi->get('CustomField', $params);
if (empty($date_field[0]['time_format'])) {
$utc = FALSE;
}
}

if ($utc) {
return (new \DateTime($date_value, new \DateTimeZone($default_timezone)))->setTimezone(new \DateTimeZone('UTC'))->format($datetime_format);
}
return (new \DateTime($date_value, new \DateTimeZone($default_timezone)))->format($datetime_format);
}

}
2 changes: 1 addition & 1 deletion src/Plugin/views/field/CustomFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function render(ResultRow $values) {
$entity_id = $this->getValue($values, 'entity_id');
$file_hash = \CRM_Core_BAO_File::generateFileHash($entity_id, $value);

$query = ['id' => $value, 'eid' => $entity_id, 'fcs' => $file_hash];
$query = ['id' => $value, 'eid' => $entity_id, 'fcs' => $file_hash, 'reset' => 1];
return \CRM_Utils_System::url($path, UrlHelper::buildQuery($query), TRUE, FALSE, FALSE, TRUE);
}

Expand Down
Loading

0 comments on commit 28b8471

Please sign in to comment.