Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 0 additions & 55 deletions includes/civipostcode_component.inc

This file was deleted.

76 changes: 76 additions & 0 deletions js/civipostcode_autocomplete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
(function (Drupal, $, once) {
Drupal.behaviors.civipostcodeAutocomplete = {
attach: function (context, settings) {
const $postcodeFields = $(once('civipostcodeAutocomplete', '.civipostcode-autocomplete', context));

$postcodeFields.each((index, element) => {
const $input = $(element);
const elementId = $input.attr('id');
const { civicrmSeq, contactSeq } = extractSequences(elementId);

if (!civicrmSeq || !contactSeq) return;

$input.on('autocompleteselect', (event, ui) => {
if (!ui.item.id) return;
$.ajax({
dataType: 'json',
data: {id: ui.item.id},
url: drupalSettings.civipostcode.apiUrl,
success: function (data) {
populateAddress(data.address, civicrmSeq, contactSeq);
}
});

return false;
});
});

/**
* Extract CiviCRM and Contact sequences from the element ID.
* Returns an object: { civicrmSeq, contactSeq }
*/
function extractSequences(id) {
const parts = id.split('-');
let civicrmSeq = null;
let contactSeq = null;

parts.forEach((part, index) => {
if (parts[index - 1] === 'civicrm') civicrmSeq = part;
if (parts[index - 1] === 'contact') contactSeq = part;
});

return { civicrmSeq, contactSeq };
}

/**
* Populate address fields based on CiviCRM and Contact sequence.
*/
function populateAddress(address, civicrmSeq, contactSeq) {
const fieldMap = {
street_address: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-street-address`,
supplemental_address_1: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-supplemental-address-1`,
supplemental_address_2: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-supplemental-address-2`,
supplemental_address_3: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-supplemental-address-3`,
city: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-city`,
postcode: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-postal-code`,
county: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-state-province-id`,
country_id: `civicrm-${civicrmSeq}-contact-${contactSeq}-address-country-id`,
};

Object.entries(fieldMap).forEach(([key, selector]) => {
const $field = $(`[id*="${selector}"]`);
// Always set a value — either the returned value or an empty string.
$field.val(address[key] ?? '');
});

// Handle special cases if CiviCRM uses different keys
if (address.town) {
$(`[id*="civicrm-${civicrmSeq}-contact-${contactSeq}-address-city"]`).val(address.town);
}
if (address.state_province_abbreviation) {
$(`[id*="civicrm-${civicrmSeq}-contact-${contactSeq}-address-state-province-id"]`).val(address.state_province_abbreviation);
}
}
}
};
})(Drupal, jQuery, once);
75 changes: 0 additions & 75 deletions js/civipostcode_component.js

This file was deleted.

76 changes: 76 additions & 0 deletions src/Controller/PostcodeAutocompleteController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

namespace Drupal\webform_civicrm_postcode\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PostcodeAutocompleteController extends ControllerBase {

/**
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;

/**
* @var \Drupal\webform_civicrm_postcode\Utils
*/
protected $utils;

/**
* Construct a Postcode Autocomplete Controller.
*/
public function __construct(ClientInterface $http_client, $utils) {
$this->httpClient = $http_client;
$this->utils = $utils;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('http_client'),
$container->get('webform_civicrm_postcode.utils')
);
}

/**
* Handle autocomplete request.
*/
public function handleAutocomplete(Request $request) {
$search = trim($request->query->get('q', ''));

if (strlen($search) < 2) {
return new JsonResponse([]);
}

$lookupProvider = $this->utils->getPostCodeLookupSettings()['provider'];
$lookupUrl = sprintf(
'%s/civicrm/%s/ajax/search?json=1&term=%s',
$request->getSchemeAndHttpHost(), $lookupProvider, urlencode($search)
);

try {
$response = $this->httpClient->get($lookupUrl, ['timeout' => 10]);

if ($response->getStatusCode() !== 200) {
return new JsonResponse([]);
}

$data = json_decode($response->getBody()->getContents(), TRUE);
if (!is_array($data)) {
return new JsonResponse([]);
}

return new JsonResponse($data);
}
catch (\Exception $e) {
return new JsonResponse([]);
}
}

}
79 changes: 79 additions & 0 deletions src/Plugin/WebformElement/Civipostcode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace Drupal\webform_civicrm_postcode\Plugin\WebformElement;

use Drupal\webform\Plugin\WebformElementBase;
use Drupal\webform\WebformSubmissionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Provides a 'Civipostcode' element.
*
* @WebformElement(
* id = "civipostcode",
* label = @Translation("Civi Postcode"),
* description = @Translation("A custom postcode lookup element."),
* category = @Translation("Custom"),
* )
*/
class Civipostcode extends WebformElementBase {

/**
* The postcode utility service.
*
* @var \Drupal\webform_civicrm_postcode\Utils\PostcodeUtils
*/
protected $utils;

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->utils = $container->get('webform_civicrm_postcode.utils');
return $instance;
}

/**
* {@inheritdoc}
*/
public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
// Always a textfield + input.
$element['#type'] = 'textfield';
$element['#input'] = TRUE;

// Only enable autocomplete if the extension is enabled.
if ($this->utils->isPostcodeLookupExtensionEnabled()) {
$provider = $this->utils->getPostCodeLookupSettings()['provider'] ?? NULL;
if ($provider) {
$host = \Drupal::request()->getSchemeAndHttpHost();

// Attach autocomplete processing handlers.
$element['#process'] = [
['Drupal\Core\Render\Element\Textfield', 'processAutocomplete'],
['Drupal\Core\Render\Element\Textfield', 'processAjaxForm'],
['Drupal\Core\Render\Element\Textfield', 'processPattern'],
];

// Autocomplete route → your controller.
$element['#autocomplete_route_name'] = 'webform_civicrm_postcode.autocomplete';
$element['#autocomplete_route_parameters'] = [];

// Attach JS libraries.
$element['#attached']['library'][] = 'core/drupal.autocomplete';
$element['#attached']['library'][] = 'webform_civicrm_postcode/civipostcode_autocomplete';

// Add class for JS behavior.
$element['#attributes']['class'][] = 'civipostcode-autocomplete';

// Provide JS settings (for the "get details" call).
$element['#attached']['drupalSettings']['civipostcode'] = [
'apiUrl' => "{$host}/civicrm/{$provider}/ajax/get?json=1",
];
}
}

parent::prepare($element, $webform_submission);
}

}
31 changes: 31 additions & 0 deletions src/Utils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Drupal\webform_civicrm_postcode;

class Utils {

public function __construct() {
\Drupal::service('civicrm')->initialize();
}

/**
* Check if the postcode extension is enabled.
*
* @return bool
*/
public function isPostcodeLookupExtensionEnabled(): bool {
return \CRM_Extension_System::singleton()->getMapper()->isActiveModule(
'civicrmpostcodelookup'
);
}

/**
* Get postal code lookup settings.
*
* @return array
*/
public function getPostCodeLookupSettings() {
return unserialize(\Civi::settings()->get('api_details'));
}

}
Loading