Repository URL to install this package:
|
Version:
2.0.2 ▾
|
novicell/custom_forms
/
custom_forms.module
|
|---|
<?php
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\EventSubscriber\AjaxResponseSubscriber;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\custom_forms\CustomFormInterface;
use Drupal\custom_forms\Entity\CustomFormSubmission;
/**
* Implements hook_theme().
*/
function custom_forms_theme() {
return [
'custom_field_list__field_name' => [
'variables' => [
'label' => NULL,
'label_attributes' => NULL,
'machine_name' => NULL,
],
],
'custom_field_list__field_visibility' => [
'variables' => [
'visibility' => TRUE,
],
],
'custom_form_form' => [
'render element' => 'form',
],
'submission_receipt' => [
'variables' => [
'submission' => NULL,
],
],
'field_info' => [
'variables' => [
'attributes' => NULL,
'icon_attributes' => NULL,
'message_attributes' => NULL,
'icon' => NULL,
'message' => NULL,
],
],
];
}
/**
* Implements hook_help().
*/
function custom_forms_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.custom_forms':
return 'Allows creation and management of custom forms.';
}
}
/**
* Implements hook_locale_translation_projects_alter().
*/
function custom_forms_locale_translation_projects_alter(&$projects) {
$module_handler = \Drupal::service('module_handler');
$path = $module_handler->getModule('custom_forms')->getPath();
$projects['custom_forms']['info']['interface translation server pattern'] = $path.'/translations/%language.po';
}
/**
* Implements hook_page_attachments_alter().
*
* Attach the custom forms admin toolbar styling for icon support.
*/
function custom_forms_page_attachments_alter(array &$attachments) {
$attachments['#attached']['library'][] = 'custom_forms/admin-toolbar';
}
/**
* Implements hook_preprocess_HOOK().
*
* Adds a simple class to the wrapper of any entity reference rendering of a
* custom form.
*/
function custom_forms_preprocess_field__entity_reference(&$variables) {
if (!empty($variables['element']['#items'])) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $entityReferenceItems */
$entityReferenceItems = $variables['element']['#items'];
$settings = $entityReferenceItems->getSettings();
// If the entity reference field is for a custom form, add the wrapper class
// to it, so that the root entity reference field can be targeted.
if (!empty($settings['target_type']) && $settings['target_type'] === 'custom_form') {
$variables['attributes']['class'][] = 'custom_form__wrapper';
}
}
}
/**
* Implements hook_preprocess_HOOK().
*
* Preprocess the visibility field to add some attributes for styling purposes.
*/
function custom_forms_preprocess_custom_field_list__field_visibility(&$variables) {
$attributes = new \Drupal\Core\Template\Attribute();
$attributes->addClass('custom-field-visibility');
$attributes->addClass('visibility-icon');
if ((boolean) $variables['visibility']) {
$attributes->addClass('visibility-icon--visible');
$attributes->setAttribute('title', t('Field is visible'));
}
else {
$attributes->addClass('visibility-icon--hidden');
$attributes->setAttribute('title', t('Field is hidden'));
}
$variables['attributes'] = $attributes;
}
/**
* Implements hook_preprocess_custom_forms__form_item().
*
* Add some extra classes to the form items so that they can be targeted without
* hitting forms that are not a custom form.
*/
function custom_forms_preprocess_custom_forms__form_item(&$element, \Drupal\custom_forms\CustomFormItem $item) {
$type = $item->getType();
$key = '#attributes';
// We need a different attribute key for those where we want it added to their wrapper.
$wrapper_elements = ['dawa_address', 'text_plain', 'email', 'number'];
if ($type === 'field' || in_array($item->getPluginDefinition()['id'], $wrapper_elements)) {
$key = '#wrapper_attributes';
}
if (!empty($element[$key])) {
if (is_array($element[$key])) {
$element[$key]['class'][] = 'custom-forms-item__'.$type;
$element[$key]['class'][] = 'js-custom-forms-item__'.$type;
} else if ($element[$key] instanceof \Drupal\Core\Template\Attribute) {
$element[$key]->addClass('custom-forms-item__'.$type);
$element[$key]->addClass('js-custom-forms-item__'.$type);
}
} else {
$element[$key] = [
'class' => [
'custom-forms-item__'.$type,
'js-custom-forms-item__'.$type,
],
];
}
}
/**
* Implements hook_entity_operation_alter().
*
* Add the field list and revision history operations to the custom form entity.
*/
function custom_forms_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity) {
$bundle = $entity->bundle();
if ($entity instanceof CustomFormInterface && !empty($bundle)) {
$account = \Drupal::currentUser();
// Rename "Edit" to "Settings"
if (!empty($operations['edit'])) {
$operations['edit']['title'] = t('Settings');
}
// Add operation for field list if the user has permission
if ($account->hasPermission('bypass custom form access') ||
$account->hasPermission("edit any $bundle custom form") ||
(
$account->hasPermission("edit own $bundle custom form") &&
$entity->getOwnerId() === $account->id()
)
) {
$operations['fields'] = [
'title' => t('Field list'),
'weight' => 11,
'url' => Url::fromRoute(
'entity.custom_form.fields_form',
['custom_form' => $entity->id()],
['language' => $entity->language()]),
];
$operations['handlers'] = [
'title' => t('Handlers'),
'weight' => 12,
'url' => Url::fromRoute(
'entity.custom_form_submission_handler.collection',
['custom_form' => $entity->id()],
['language' => $entity->language()]),
];
}
// Add operation for version history if the user has permission
if ($account->hasPermission('bypass custom form access') ||
$account->hasPermission('view all custom form revisions') ||
(
$account->hasPermission('view published custom forms') &&
$account->hasPermission("view $bundle revisions")
)
) {
$operations['version_history'] = [
'title' => t('Revisions'),
'weight' => 13,
'url' => Url::fromRoute(
'entity.custom_form.version_history',
['custom_form' => $entity->id()],
['language' => $entity->language()]),
];
}
}
}
/**
* Implements hook_mail().
*
* Force the mail sent via the custom forms module to use text/html format.
*/
function custom_forms_mail($key, &$message, $params) {
$system_site_config = \Drupal::config('system.site');
$message['headers']['content-type'] = 'text/html';
switch ($key) {
case 'sendgrid_test':
$message['headers']['from'] = $system_site_config->get('name') . ' <'.$system_site_config->get('mail').'>';
break;
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* This is just a form alter to change the description text to be more fitting
* for the custom forms.
*/
function custom_forms_form_entity_clone_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$request = \Drupal::request();
/** @var \Drupal\custom_forms\Entity\CustomForm $custom_form */
$custom_form = $request->attributes->get('custom_form');
if (empty($custom_form)) {
return;
}
// Change description to one that fits custom forms better.
$form['description']['#markup'] = '<p>' . t('Pressing the clone button takes a copy of %current-form, including all the fields.',
['%current-form' => $custom_form->label()]
) . '</p>';
}
/**
* Implements hook_preprocess().
*/
function custom_forms_preprocess(&$variables, $hook) {
$config = \Drupal::config('custom_forms.settings');
$query = \Drupal::request()->query;
$original_hook = $hook;
$config_hook = $hook;
// If the hook is for paragraph widget, mask it as a paragraph since it needs
// to affect both hooks identically.
switch ($original_hook) {
case 'paragraph_widget':
$hook = 'paragraph';
$config_hook = 'paragraph';
break;
case 'block_content':
$hook = 'block';
$config_hook = 'block_content';
break;
}
if (
$query->has('S') &&
!empty($query->get('S')) &&
$bundle_type_config = $config->get('receipt_bundle_types')
) {
// To save time, we remove all bundles that are not selected to have the receipt field added.
foreach ($bundle_type_config as $entity_type_id => $entities) {
$remove_entry = TRUE;
foreach ($entities as $key => $value) {
if ($value === $key) {
$remove_entry = FALSE;
} else {
unset($bundle_type_config[$entity_type_id][$key]);
}
}
if ($remove_entry) {
unset($bundle_type_config[$entity_type_id]);
}
}
if (!empty($bundle_type_config[$config_hook])) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
// First see if we have access to the entity as a root element.
if (!empty($variables[$hook])) {
$entity = $variables[$hook];
}
// Next check the content array for the entity.
if (empty($entity) && !empty($variables['content']['#entity'])) {
$entity = $variables['content']['#entity'];
}
// Lastly, check for the config hook.
if (empty($entity) && !empty($variables[$config_hook])) {
$entity = $variables[$config_hook];
}
// If the entity wasn't found, just return.
if (empty($entity)) {
return;
}
/** @var \Drupal\custom_forms\Entity\CustomFormSubmissionInterface $submission */
$submission = CustomFormSubmission::loadByUniqueId($query->get('S'));
if (
$submission !== NULL &&
!empty($bundle_type_config[$config_hook][$entity->bundle()])
) {
try {
$data = $submission->getData();
if (!empty($data['_submission_token'])) {
/** @var \Drupal\dds\Service\SessionService $sessionService */
$sessionService = \Drupal::service('dds.session');
$tempstore = $sessionService->getTempStore('private', 'custom_form_submission_'.$submission->id());
$token = $tempstore->get('submission_token');
if ($token === $data['_submission_token']) {
// Disable caching of receipt data.
$variables['#cache']['max-age'] = 0;
$variables['#cache']['contexts'][] = 'url.query_args:S';
$variables['receipt'] = [
'#theme' => 'submission_receipt',
'#submission' => $submission,
];
if (isset($variables['content'])) {
$variables['content']['receipt'] = $variables['receipt'];
}
if (isset($variables['rendered_fields'])) {
$variables['rendered_fields']['receipt'] = $variables['receipt'];
}
}
}
unset($data);
} catch (Throwable $e) {
$error_message = t('Failed preparing submission data for receipt template. Message = %message', [
'%message' => $e->getMessage()
]);
\Drupal::logger('Custom Forms')->error($error_message);
}
}
}
}
}
/**
* Implements hook_preprocess_HOOK().
*
* Handle layout builders inline blocks.
*/
function custom_forms_preprocess_block__inline_block(&$variables) {
custom_forms_preprocess($variables, 'block_content');
}
/**
* Implements hook_preprocess_HOOK().
*/
function custom_forms_preprocess_submission_receipt(&$variables) {
/** @var \Drupal\custom_forms\Entity\CustomFormSubmissionInterface $submission */
$submission = $variables['submission'];
$variables['data'] = $submission->generateReceiptData();
}
/**
* Implements hook_preprocess_HOOK().
*/
function custom_forms_preprocess_block__custom_form_receipt_block(&$variables) {
if (isset($variables['attributes'])) {
/** @var \Drupal\Core\Template\Attribute $attributes */
$attributes = $variables['attributes'];
if (!($attributes instanceof Attribute)) {
$attributes = new Attribute($attributes);
}
}
else {
$attributes = new Attribute();
}
$attributes->addClass('custom-forms__receipt-block');
$variables['attributes'] = $attributes->toArray();
}
/**
* Implements hook_preprocess_HOOK().
*/
function custom_forms_preprocess_block__custom_form_block(&$variables) {
if (isset($variables['attributes'])) {
/** @var \Drupal\Core\Template\Attribute $attributes */
$attributes = $variables['attributes'];
if (!($attributes instanceof Attribute)) {
$attributes = new Attribute($attributes);
}
}
else {
$attributes = new Attribute();
}
$attributes->addClass('custom-forms__form-block');
$variables['attributes'] = $attributes->toArray();
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function custom_forms_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
if (!empty($variables['element']['#suggestions'])) {
foreach ($variables['element']['#suggestions'] as $suggestion) {
$suggestions[] = 'form_element__'.$suggestion;
}
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function custom_forms_preprocess_form_element(&$variables) {
if (!empty($variables['element']['#field_info'])) {
$variables['field_info'] = $variables['element']['#field_info'];
}
}