TourBuilderExportForm.php in Tour Builder 8
File
src/Form/TourBuilderExportForm.php
View source
<?php
namespace Drupal\tour_builder\Form;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class TourBuilderExportForm extends EntityForm {
use StringTranslationTrait;
protected $entityTypeManager;
protected $configStorage;
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('config.storage'));
}
public function __construct(EntityTypeManagerInterface $entity_type_manager, StorageInterface $config_storage) {
$this->entityTypeManager = $entity_type_manager;
$this->configStorage = $config_storage;
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$definition = $this->entityTypeManager
->getDefinition('tour');
$name = $definition
->getConfigPrefix() . '.' . $this->entity
->getOriginalId();
$config = $this->configStorage
->read($name);
$unset_keys = [
'uuid',
'_core',
];
foreach ($unset_keys as $key) {
unset($config[$key]);
}
$content = Yaml::encode($config);
$form['export'] = [
'#type' => 'textarea',
'#title' => $this
->t('YAML Content'),
'#description' => $this
->t('Filename: %name', [
'%name' => $name . '.yml',
]),
'#rows' => 15,
'#default_value' => $content,
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state, $redirect = TRUE) {
$old_name = $form_state
->getValue('old_name');
$new_name = $form_state
->getValue('new_name');
if ($form_state
->isValueEmpty('new_name')) {
$form_state
->setError($form['new_name'], $this
->t('The tour file name cannot be empty.'));
}
if ($old_name == $new_name) {
$form_state
->setError($form['new_name'], $this
->t('You must change the new tour file name', [
'%tip' => 'XXX',
]));
}
}
public function submitForm(array &$form, FormStateInterface $form_state, $redirect = TRUE) {
if ($redirect) {
$form_state
->setRedirect('entity.tour.edit_form', [
'tour' => $this->entity
->id(),
]);
}
}
}