View source
<?php
namespace Drupal\private_message\Form;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Component\Utility\Html;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\private_message\Ajax\PrivateMessageInboxTriggerUpdateCommand;
use Drupal\private_message\Ajax\PrivateMessageLoadNewMessagesCommand;
use Drupal\private_message\Entity\PrivateMessageThread;
use Drupal\private_message\Entity\PrivateMessageThreadInterface;
use Drupal\private_message\Service\PrivateMessageServiceInterface;
use Drupal\private_message\Service\PrivateMessageThreadManagerInterface;
use Drupal\user\UserDataInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PrivateMessageForm extends ContentEntityForm {
protected $formId;
protected $currentUser;
protected $entityTypeManager;
protected $typedDataManager;
protected $userData;
protected $configFactory;
protected $privateMessageService;
protected $privateMessageThreadManager;
protected $userManager;
public function __construct(EntityRepositoryInterface $entityRepository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, EntityTypeManagerInterface $entityTypeManager, AccountProxyInterface $currentUser, TypedDataManagerInterface $typedDataManager, UserDataInterface $userData, ConfigFactoryInterface $configFactory, PrivateMessageServiceInterface $privateMessageService, PrivateMessageThreadManagerInterface $privateMessageThreadManager) {
parent::__construct($entityRepository, $entity_type_bundle_info, $time);
$this->entityTypeManager = $entityTypeManager;
$this->currentUser = $currentUser;
$this->typedDataManager = $typedDataManager;
$this->userData = $userData;
$this->configFactory = $configFactory;
$this->privateMessageService = $privateMessageService;
$this->privateMessageThreadManager = $privateMessageThreadManager;
$this->userManager = $entityTypeManager
->getStorage('user');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.repository'), $container
->get('entity_type.bundle.info'), $container
->get('datetime.time'), $container
->get('entity_type.manager'), $container
->get('current_user'), $container
->get('typed_data_manager'), $container
->get('user.data'), $container
->get('config.factory'), $container
->get('private_message.service'), $container
->get('private_message.thread_manager'));
}
public function setFormId($id) {
$this->formId = Html::escape($id);
}
public function getFormId() {
$form_id = parent::getFormId();
if ($this->formId) {
$form_id .= '-' . $this->formId;
}
return $form_id;
}
public function buildForm(array $form, FormStateInterface $form_state, PrivateMessageThreadInterface $privateMessageThread = NULL) {
$form = parent::buildForm($form, $form_state);
if ($privateMessageThread) {
$form_state
->set('thread', $privateMessageThread);
$form['actions']['submit']['#ajax'] = [
'callback' => '::ajaxCallback',
];
$form['#attached']['library'][] = 'private_message/message_form';
$form['#attached']['drupalSettings']['privateMessageSendKey'] = $this->configFactory
->get('private_message.settings')
->get('keys_send');
$autofocus_enabled = $this->configFactory
->get('private_message.settings')
->get('autofocus_enable');
if ($autofocus_enabled) {
$form['message']['widget'][0]['#attributes']['autofocus'] = 'autofocus';
}
}
else {
$private_message_thread = PrivateMessageThread::create();
$form_copy = $form;
$form_state_copy = clone $form_state;
$form_display = EntityFormDisplay::collectRenderDisplay($private_message_thread, 'default');
$form_display
->buildForm($private_message_thread, $form_copy, $form_state_copy);
if (empty($storage['field_storage']['#parents']['#fields']['members'])) {
$storage = $form_state_copy
->getStorage();
$copy_storage = $form_state_copy
->getStorage();
$storage['field_storage']['#parents']['#fields']['members'] = $copy_storage['field_storage']['#parents']['#fields']['members'];
$form_state
->setStorage($storage);
}
$form_state
->set('pmt_form_display', $form_display);
$form_state
->set('pmt_entity', $private_message_thread);
$form['members'] = $form_copy['members'];
$form['#validate'][] = '::validateMembers';
}
if ($this->configFactory
->get('private_message.settings')
->get('hide_form_filter_tips')) {
$form['#after_build'][] = '::afterBuild';
}
if ($save_label = $this->configFactory
->get('private_message.settings')
->get('save_message_label')) {
$form['actions']['submit']['#value'] = $save_label;
}
return $form;
}
public function validateMembers(array &$form, FormStateInterface $formState) {
$entity_type = $this->entityTypeManager
->getDefinition('private_message_thread');
$field_definitions = PrivateMessageThread::baseFieldDefinitions($entity_type);
$entity = $formState
->get('pmt_entity');
$form_display = $formState
->get('pmt_form_display');
$form_display
->extractFormValues($entity, $form, $formState);
$members_field = $field_definitions['members'];
$members = [];
$selectedMembers = [];
foreach ($entity
->get('members') as $user) {
if ($user instanceof EntityReferenceItem) {
$user = $user->entity;
}
$selectedMembers[] = $user;
if ($user
->isActive()) {
$members[] = $user;
}
}
if (count($members) != count($selectedMembers)) {
$formState
->setError($form['members'], $this
->t('You can not send a message because there are inactive users selected for this thread.'));
}
$typed_data = $this->typedDataManager
->create($members_field, $members);
$violations = $typed_data
->validate();
if ($violations
->count() > 0) {
foreach ($violations as $violation) {
$formState
->setError($form['members'], $violation
->getMessage());
}
}
}
public function ajaxCallback(array $form, FormStateInterface $formState) {
$response = new AjaxResponse();
$form['message']['widget'][0]['value']['#value'] = '';
$response
->addCommand(new ReplaceCommand('.private-message-add-form', $form));
$response
->addCommand(new PrivateMessageLoadNewMessagesCommand());
$response
->addCommand(new PrivateMessageInboxTriggerUpdateCommand());
return $response;
}
public function afterBuild(array $form, FormStateInterface $formState) {
$form['message']['widget'][0]['format']['#attributes']['class'][] = 'hidden';
return $form;
}
public function save(array $form, FormStateInterface $formState) {
$status = parent::save($form, $formState);
$private_message_thread = $formState
->get('thread');
if (!$private_message_thread) {
$current_user = $this->userManager
->load($this->currentUser
->id());
$members = [
$current_user,
];
$entity = $formState
->get('pmt_entity');
foreach ($entity
->get('members') as $user) {
if ($user instanceof EntityReferenceItem) {
$user = $user->entity;
}
$members[] = $user;
}
$private_message_thread = $this->privateMessageService
->getThreadForMembers($members);
}
$this->privateMessageThreadManager
->saveThread($this->entity, $private_message_thread
->getMembers(), [], $private_message_thread);
$formState
->set('private_message_thread', $private_message_thread);
$formState
->setRedirect('entity.private_message_thread.canonical', [
'private_message_thread' => $private_message_thread
->id(),
]);
return $status;
}
}