public function DataPolicyConsentManager::addCheckbox in Data Policy 8
Add checkbox to form which allow user give consent on data policy.
Parameters
array $form: An associative array containing the structure of the form.
Overrides DataPolicyConsentManagerInterface::addCheckbox
File
- src/
DataPolicyConsentManager.php, line 103
Class
- DataPolicyConsentManager
- Defines the Data Policy Consent Manager service.
Namespace
Drupal\data_policyCode
public function addCheckbox(array &$form) {
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';
$entity_ids = $this
->getEntityIdsFromConsentText();
$revisions = $this
->getRevisionsByEntityIds($entity_ids);
$links = [];
$query = $this->database
->select('user_consent', 'uc');
$query
->condition('status', TRUE);
$query
->condition('state', UserConsentInterface::STATE_AGREE);
$query
->condition('user_id', $this->currentUser
->id());
$query
->join('user_consent__data_policy_revision_id', 'ucr', 'uc.id = ucr.entity_id');
$query
->addField('ucr', 'data_policy_revision_id_value');
$user_agree_revision_ids = $query
->execute()
->fetchCol();
foreach ($revisions as $key => $revision) {
// Get translation for current revision if exists.
$revision = $this->entityRepository
->getTranslationFromContext($revision);
$links[$key] = Link::createFromRoute(strtolower($revision
->getName()), 'data_policy.data_policy', [
'id' => $revision
->id(),
], [
'attributes' => [
'class' => [
'use-ajax',
],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'title' => $revision
->getName(),
'width' => 700,
'height' => 700,
]),
'checked' => in_array($revision
->getRevisionId(), $user_agree_revision_ids),
],
]);
}
$enforce_consent_text = $this
->getConfig('consent_text');
$items = preg_split('/\\R/', $enforce_consent_text);
// Checkboxes always should be under all existing fields.
// See social_registration_fields module.
$form['account']['data_policy'] = [
'#type' => 'details',
'#tree' => TRUE,
'#weight' => 110,
'#open' => TRUE,
];
foreach ($links as $entity_id => $link) {
/** @var \Drupal\Core\Link $link */
$data = [];
foreach ($items as $item) {
if (strpos($item, "[id:{$entity_id}") !== FALSE) {
$data = [
'text' => $item,
'required' => strpos($item, "[id:{$entity_id}*]") ? TRUE : FALSE,
];
}
continue;
}
$enforce_consent_text = str_replace([
"[id:{$entity_id}*]",
"[id:{$entity_id}]",
], $link
->toString(), $data['text']);
$form['account']['data_policy']['data_policy_' . $entity_id] = [
'#type' => 'checkbox',
'#title' => $enforce_consent_text,
'#required' => $data['required'],
'#weight' => 110 + $entity_id,
'#default_value' => $link
->getUrl()
->getOption('attributes')['checked'],
];
}
}