Skip to content

Commit

Permalink
Merge pull request #24 from OS2Forms/develop
Browse files Browse the repository at this point in the history
Prearing new release 3.2.1
  • Loading branch information
andriyun authored Jan 19, 2022
2 parents 3255630 + 5128a01 commit 7211050
Show file tree
Hide file tree
Showing 16 changed files with 405 additions and 8 deletions.
5 changes: 2 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@
"drupal/entity_print": "^2.1",
"drupal/webform_migrate": "^1.1",
"drupal/maillog": "1.x-dev",
"drupal/webform_permissions_by_term": "^1.2",
"drupal/permissions_by_term": "^3.1",
"phpoffice/phpword": "^0.17.0",
"drupal/permissions_by_term": "^3.1 || ^2.25",
"phpoffice/phpword": "^0.18.2",
"tecnickcom/tcpdf": "~6",
"vaimo/composer-patches": "^4.20",
"os2web/os2web_datalookup": "^1.0",
Expand Down
15 changes: 15 additions & 0 deletions modules/os2forms_autocomplete/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# OS2Forms Autocomplete Drupal module

# Module purpose

The aim of this module is to provide a genetic OS2Forms Autocomplete element which can return options from an external webservice.

# How does it work

Module exposes OS2Forms Autocomplete component that are available in the webform build process.

Build page:

```
admin/structure/webform/manage/[webform]
```
9 changes: 9 additions & 0 deletions modules/os2forms_autocomplete/os2forms_autocomplete.info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
name: 'OS2forms Autocomplete'
type: module
description: 'Provides autocomplete field'
package: OS2Forms
core: 8.x
core_version_requirement: ^8 || ^9

dependencies:
- os2forms
2 changes: 2 additions & 0 deletions modules/os2forms_autocomplete/os2forms_autocomplete.module
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?php

10 changes: 10 additions & 0 deletions modules/os2forms_autocomplete/os2forms_autocomplete.routing.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
os2forms_autocomplete.element.autocomplete:
path: '/os2forms/{webform}/autocomplete/{key}'
defaults:
_controller: '\Drupal\os2forms_autocomplete\Controller\AutocompleteElementController::autocomplete'
options:
parameters:
webform:
type: 'entity:webform'
requirements:
_entity_access: 'webform.submission_page'
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
services:
os2forms_autocomplete.service:
class: Drupal\os2forms_autocomplete\Service\AutocompleteService
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace Drupal\os2forms_autocomplete\Controller;

use Drupal\webform\Controller\WebformElementController;
use Drupal\webform\Entity\WebformOptions;
use Drupal\webform\WebformInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
* Provides route responses for Webform elements.
*/
class AutocompleteElementController extends WebformElementController {

/**
* Returns response for 'os2forms_autocomplete' element autocomplete route.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object containing the search string.
* @param \Drupal\webform\WebformInterface $webform
* A webform.
* @param string $key
* Webform element key.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A JSON response containing the autocomplete suggestions.
*/
public function autocomplete(Request $request, WebformInterface $webform, $key) {
// Get autocomplete query.
$q = $request->query->get('q') ?: '';
if ($q === '') {
return new JsonResponse([]);
}

// Get the initialized webform element.
$element = $webform->getElement($key);
if (!$element) {
return new JsonResponse([]);
}

// Loading #autocomplete_items.
/** @var \Drupal\os2forms_autocomplete\Service\AutocompleteService $acService */
$acService = \Drupal::service('os2forms_autocomplete.service');
$element['#autocomplete_items'] = $acService->getAutocompleteItemsFromApi($element['#autocomplete_api_url']);

// Set default autocomplete properties.
$element += [
'#autocomplete_items' => [],
'#autocomplete_match' => 3,
'#autocomplete_limit' => 10,
'#autocomplete_match_operator' => 'CONTAINS',
];

// Check minimum number of characters.
if (mb_strlen($q) < (int) $element['#autocomplete_match']) {
return new JsonResponse([]);
}

$matches = [];

// Get items (aka options) matches.
if (!empty($element['#autocomplete_items'])) {
$element['#options'] = $element['#autocomplete_items'];
$options = WebformOptions::getElementOptions($element);
$matches += $this->getMatchesFromOptions($q, $options, $element['#autocomplete_match_operator'], $element['#autocomplete_limit']);
}

// Sort matches by label and enforce the limit.
if ($matches) {
uasort($matches, function (array $a, array $b) {
return $a['label'] > $b['label'];
});
$matches = array_values($matches);
$matches = array_slice($matches, 0, $element['#autocomplete_limit']);
}

return new JsonResponse($matches);
}

}
22 changes: 22 additions & 0 deletions modules/os2forms_autocomplete/src/Element/AutocompleteElement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Drupal\os2forms_autocomplete\Element;

use Drupal\webform\Element\WebformAutocomplete;

/**
* Provides a DAWA Address Autocomplete element.
*
* @FormElement("os2forms_autocomplete")
*/
class AutocompleteElement extends WebformAutocomplete {

/**
* @inheritDoc
*/
public static function preRenderWebformAutocomplete($element) {
static::setAttributes($element, ['os2forms-autocomplete']);
return $element;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace Drupal\os2forms_autocomplete\Plugin\WebformElement;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformElement\WebformAutocomplete;
use Drupal\webform\WebformSubmissionInterface;

/**
* Provides a 'os2forms_autocomplete' element.
*
* @WebformElement(
* id = "os2forms_autocomplete",
* label = @Translation("OS2Forms Autocomplete"),
* description = @Translation("Provides a customer OS2Forms Autocomplete element."),
* category = @Translation("OS2Forms"),
* )
*/
class AutocompleteElement extends WebformAutocomplete {

/**
* {@inheritdoc}
*/
protected function defineDefaultProperties() {
$properties = parent::defineDefaultProperties();

// Adding OS2Forms autocomplete properties.
$properties['autocomplete_api_url'] = '';

// Remove properties which is not applicable to
// OS2Forms autocomplete element.
unset($properties['autocomplete_existing']);
unset($properties['autocomplete_items']);

return $properties;
}

/**
* {@inheritdoc}
*/
public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
parent::prepare($element, $webform_submission);

if (isset($element['#webform_key'])) {
$element['#autocomplete_route_name'] = 'os2forms_autocomplete.element.autocomplete';
$element['#autocomplete_route_parameters'] = [
'webform' => $webform_submission->getWebform()->id(),
'key' => $element['#webform_key'],
];

if ($webform_submission->isNew() && isset($element['#default_value'])) {
/** @var \Drupal\os2forms_autocomplete\Service\AutocompleteService $acService */
$acService = \Drupal::service('os2forms_autocomplete.service');
$autocompleteDefaultValue = $acService->getFirstMatchingValue($element['#autocomplete_api_url'], $element['#default_value']);

if ($autocompleteDefaultValue) {
$element['#default_value'] = $autocompleteDefaultValue;
}
}
}
}

/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);

// Unsetting the parametes that we are not using.
unset($form['autocomplete']['autocomplete_items']);
unset($form['autocomplete']['autocomplete_existing']);

$form['autocomplete']['autocomplete_api_url'] = [
'#type' => 'textfield',
'#title' => $this->t('API Url where the autocomplete values are coming from'),
'#description' => $this->t('The returned result must be in JSON format. Values from multiple keys will be combined'),
];

return $form;
}

}
69 changes: 69 additions & 0 deletions modules/os2forms_autocomplete/src/Service/AutocompleteService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace Drupal\os2forms_autocomplete\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
* Class AutocompleteService.
*/
class AutocompleteService {

/**
* Returns a full list of items for autocomplete options.
*
* @param string $requestUrl
* URL for getting the results from.
*
* @return array
* List of options.
*/
public function getAutocompleteItemsFromApi($requestUrl) {
$options = [];

$httpClient = new Client();
try {
$res = $httpClient->get($requestUrl);
if ($res->getStatusCode() == 200) {
$body = $res->getBody();
$jsonDecoded = json_decode($body, TRUE);
if (!empty($jsonDecoded) && is_array($jsonDecoded)) {
foreach ($jsonDecoded as $key => $values) {
$options = array_merge($options, $values);
}
}
}
} catch (RequestException $e) {
\Drupal::logger('OS2Forms Autocomplete')->notice('Autocomplete request failed: %e', ['%e' => $e->getMessage()]);
}

return $options;
}

/**
* Gets a first option from a fetched options list matching the criteria.
*
* @param string $requestUrl
* URL for getting the results from.
* @param $needle
* Search criteria.
*
* @return mixed
* First available option or FALSE.
*/
public function getFirstMatchingValue($requestUrl, $needle) {
$options = $this->getAutocompleteItemsFromApi($requestUrl);

if (!empty($options)) {
foreach ($options as $option) {
if (stripos($option, $needle) !== FALSE) {
return $option;
}
}
}

return FALSE;
}

}
23 changes: 23 additions & 0 deletions modules/os2forms_nemid/os2forms_nemid.module
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,26 @@ function os2forms_nemid_migrate_prepare_row(\Drupal\migrate\Row $row, \Drupal\mi
$row->setDestinationProperty('dependencies', $dependencies);
}
}

/**
* Add a flag that this webform submission has a protected address field.
*
* @param array $form
* Form object.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
function os2forms_nemid_submission_set_address_protected(array $form, \Drupal\Core\Form\FormStateInterface &$form_state){
/** @var \Drupal\webform\WebformSubmissionForm $webformSubmissionForm */
$webformSubmissionForm = $form_state->getFormObject();

/** @var \Drupal\webform\WebformSubmissionInterface $webformSubmission */
$webformSubmission = $webformSubmissionForm->getEntity();

$data = $webformSubmission->getData();
$data['os2forms_nemid_elements_nemid_address_protected'] = TRUE;
$webformSubmission->setData($data);
$webformSubmission->save();
}
Loading

0 comments on commit 7211050

Please sign in to comment.