EntityLegalDocumentAcceptanceForm.php in Entity Legal 4.0.x
File
src/Form/EntityLegalDocumentAcceptanceForm.php
View source
<?php
namespace Drupal\entity_legal\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\entity_legal\EntityLegalDocumentInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityLegalDocumentAcceptanceForm extends FormBase {
protected $document;
protected $tempStore;
public function __construct(PrivateTempStoreFactory $private_temp_store_factory) {
$this->tempStore = $private_temp_store_factory
->get('entity_legal');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('tempstore.private'));
}
public function setDocument(EntityLegalDocumentInterface $document) {
$this->document = $document;
}
public function getFormId() {
return 'entity_legal_document_acceptance_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$has_agreed = $this->document
->userHasAgreed();
$form['agree'] = [
'#title' => $this->document
->getAcceptanceLabel(),
'#type' => 'checkbox',
'#required' => TRUE,
'#default_value' => $has_agreed,
'#disabled' => $has_agreed,
];
$form['submit'] = [
'#value' => t('Submit'),
'#type' => 'submit',
'#access' => !$has_agreed,
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$published_version = $this->document
->getPublishedVersion();
\Drupal::entityTypeManager()
->getStorage(ENTITY_LEGAL_DOCUMENT_ACCEPTANCE_ENTITY_NAME)
->create([
'document_version_name' => $published_version
->id(),
])
->save();
if ($grouped_messages = $this->tempStore
->get('postponed_messages')) {
foreach ($grouped_messages as $type => $messages) {
foreach ($messages as $message) {
$this
->messenger()
->addMessage($message, $type);
}
}
$this->tempStore
->delete('postponed_messages');
}
}
}