support-2.0.x-dev/modules/support_ticket/src/SupportTicketTypeForm.php
modules/support_ticket/src/SupportTicketTypeForm.php
<?php
namespace Drupal\support_ticket;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\language\Entity\ContentLanguageSettings;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\support_ticket\Util\SupportTicketUtility;
/**
* Form controller for support ticket type forms.
*/
class SupportTicketTypeForm extends EntityForm {
use MessengerTrait;
use StringTranslationTrait;
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityManager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Constructs the SupportTicketTypeForm object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity manager.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, EntityFieldManagerInterface $entity_field_manager) {
$this->entityManager = $entity_manager;
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('entity_field.manager')
);
}
/**
* {@inheritdoc}
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
*/
public function form(array $form, FormStateInterface $form_state): array {
$form = parent::form($form, $form_state);
if ($this->operation == 'add') {
$form['#title'] = $this->t('Add support ticket type');
$fields = $this->entityFieldManager
->getBaseFieldDefinitions('support_ticket');
// Create a support ticket with a fake bundle using the type's
// UUID so that we can get the default values for workflow settings.
$support_ticket_type = $this->entityManager
->getStorage('support_ticket')
->create(['support_ticket_type' => $this->entity->uuid()]);
}
else {
$form['#title'] = $this->t('Edit %label support ticket type', ['%label' => $this->entity->label()]);
$fields = $this->entityFieldManager
->getFieldDefinitions('support_ticket', $this->entity->id());
// Create a support_ticket to get the current values
// for workflow settings fields.
$support_ticket_type = $this->entityManager
->getStorage('support_ticket')
->create(['support_ticket_type' => $this->entity->id()]);
}
$form['name'] = [
'#title' => $this->t('Name'),
'#type' => 'textfield',
'#default_value' => $this->entity->label(),
'#description' => $this->t('The human-readable name of this support ticket type. This text will be displayed as part of the list on the <em>Add support ticket</em> page. This name must be unique.'),
'#required' => TRUE,
'#size' => 30,
];
$form['type'] = [
'#type' => 'machine_name',
'#default_value' => $this->entity->id(),
'#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
'#disabled' => $this->entity->isLocked(),
'#machine_name' => [
'exists' => ['Drupal\support_ticket\Entity\SupportTicketType', 'load'],
'source' => ['name'],
],
'#description' => $this->t('A unique machine-readable name for this support ticket type. It must only contain lowercase letters, numbers, and underscores. This name will be used for constructing the URL of the %support-ticket-add page, in which underscores will be converted into hyphens.',
['%support-ticket-add' => $this->t('Add support ticket')]),
];
// @todo description input box is not working?
$form['description'] = [
'#title' => $this->t('Description'),
'#type' => 'textarea',
'#default_value' => $this->entityTypeManager
->getDefinition($this->entity->getEntityTypeId())
->getBundleLabel(),
'#description' => $this->t('Describe this support ticket type. The text will be displayed on the <em>Add support ticket</em> page.'),
];
$form['additional_settings'] = [
'#type' => 'vertical_tabs',
'#attached' => [
'library' => ['support_ticket/drupal.support_ticket_types'],
],
];
$form['submission'] = [
'#type' => 'details',
'#title' => $this->t('Submission form settings'),
'#group' => 'additional_settings',
'#open' => TRUE,
];
$form['submission']['title_label'] = [
'#title' => $this->t('Title field label'),
'#type' => 'textfield',
'#default_value' => $fields['title']->getLabel(),
'#required' => TRUE,
];
$form['submission']['preview_mode'] = [
'#type' => 'radios',
'#title' => $this->t('Preview before submitting'),
'#default_value' => $this->entity->getPreviewMode(),
'#options' => [
DRUPAL_DISABLED => $this->t('Disabled'),
DRUPAL_OPTIONAL => $this->t('Optional'),
DRUPAL_REQUIRED => $this->t('Required'),
],
];
$form['submission']['help'] = [
'#type' => 'textarea',
'#title' => $this->t('Explanation or submission guidelines'),
'#default_value' => $this->entity->getHelp(),
'#description' => $this->t('This text will be displayed at the top of the page when creating or editing support tickets of this type.'),
];
$form['workflow'] = [
'#type' => 'details',
'#title' => $this->t('Publishing options'),
'#group' => 'additional_settings',
];
$workflow_options = [
'status' => $support_ticket_type->isPublished(),
'locked' => $support_ticket_type->isLocked(),
'revision' => $this->entity->isNewRevision(),
];
// Prepare workflow options to be used for 'checkboxes' form element.
$keys = array_keys(array_filter($workflow_options));
$workflow_options = array_combine($keys, $keys);
$form['workflow']['options'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Default options'),
'#default_value' => $workflow_options,
'#options' => [
'status' => $this->t('Published'),
'locked' => $this->t('Locked'),
'revision' => $this->t('Create new revision'),
],
'#description' => $this->t('Users with the <em>Administer support tickets</em> permission will be able to override these options.'),
];
if ($this->moduleHandler->moduleExists('language')) {
$form['language'] = [
'#type' => 'details',
'#title' => $this->t('Language settings'),
'#group' => 'additional_settings',
];
$language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('support_ticket', $this->entity->id());
$form['language']['language_configuration'] = [
'#type' => 'language_configuration',
'#entity_information' => [
'entity_type' => 'support_ticket',
'bundle' => $this->entity->id(),
],
'#default_value' => $language_configuration,
];
}
$form['display'] = [
'#type' => 'details',
'#title' => $this->t('Display settings'),
'#group' => 'additional_settings',
];
$form['display']['display_submitted'] = [
'#type' => 'checkbox',
'#title' => $this->t('Display author and date information'),
'#default_value' => $this->entity->displaySubmitted(),
'#description' => $this->t('Author username and publish date will be displayed.'),
];
return $form;
}
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions = parent::actions($form, $form_state);
$actions['submit']['#value'] = $this->t('Save support ticket type');
$actions['delete']['#value'] = $this->t('Delete support ticket type');
return $actions;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$id = trim($form_state->getValue('type'));
// '0' is invalid, since elsewhere we check it using empty().
if ($id == '0') {
$form_state->setErrorByName('type',
$this->t("Invalid machine-readable name. Enter a name other than %invalid.",
['%invalid' => $id])
);
}
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$this->entity->setNewRevision($form_state->getValue(['options', 'revision']));
$this->entity->set('type', trim($this->entity->id()));
$this->entity->set('name', trim($this->entity->label()));
$status = $this->entity->save();
$t_args = ['%name' => $this->entity->label()];
if ($status == SAVED_UPDATED) {
$this->messenger()
->addStatus($this->t('The support ticket type %name has been updated.', $t_args));
}
elseif ($status == SAVED_NEW) {
// @todo research why this needed.
SupportTicketUtility::supportTicketAddBodyField($this->entity);
$this->messenger()
->addStatus($this->t('The support ticket type %name has been added.', $t_args));
$context = array_merge($t_args,
['link' => $this->entity->toUrl('collection')->toString()]
);
$this->logger('support_ticket')
->notice('Added support ticket type %name.', $context);
}
$fields = $this->entityFieldManager
->getFieldDefinitions('support_ticket', $this->entity->id());
// Update title field definition.
$title_field = $fields['title'];
$title_label = $form_state->getValue('title_label');
if ($title_field->getLabel() != $title_label) {
$title_field->getConfig($this->entity->id())
->setLabel($title_label)
->save();
}
// Update workflow options.
$support_ticket = $this->entityManager
->getStorage('support_ticket')
->create(['support_ticket_type' => $this->entity->id()]);
foreach (['status', 'locked'] as $field_name) {
$value = (bool) $form_state->getValue(['options', $field_name]);
if ($support_ticket->$field_name->value != $value) {
$fields[$field_name]
->getConfig($this->entity->id())
->setDefaultValue($value)
->save();
}
}
$this->entityFieldManager->clearCachedFieldDefinitions();
$form_state->setRedirectUrl($this->entity->toUrl('collection'));
}
}
