View source
<?php
namespace Drupal\tour_builder\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class TourBuilderCloneForm extends EntityForm {
use StringTranslationTrait;
protected $entityTypeManager;
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'));
}
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Tour name'),
'#required' => TRUE,
'#default_value' => $this->entity
->label(),
];
$form['old_name'] = [
'#type' => 'value',
'#value' => $this->entity
->getOriginalId(),
];
$form['new_name'] = [
'#title' => 'File name for new tour item.',
'#type' => 'textfield',
'#description' => $this
->t('This value should start with <strong>tour.tour.</strong> and may not exists.'),
'#field_prefix' => 'tour.tour.',
'#default_value' => $this->entity
->getOriginalId(),
];
$form['module'] = [
'#title' => 'Module for this tour.',
'#type' => 'textfield',
'#default_value' => $this->entity
->getModule(),
];
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) {
$this->entity = $this->entity
->createDuplicate();
$this->entity
->set('id', $form_state
->getValue('new_name'));
$this->entity
->save();
if ($redirect) {
$form_state
->setRedirect('entity.tour.edit_form', [
'tour' => $this->entity
->id(),
]);
}
}
}