ConfigEntityCloneFormBase.php in Entity Clone 8
File
src/EntityClone/Config/ConfigEntityCloneFormBase.php
View source
<?php
namespace Drupal\entity_clone\EntityClone\Config;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslationManager;
use Drupal\entity_clone\EntityClone\EntityCloneFormInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ConfigEntityCloneFormBase implements EntityHandlerInterface, EntityCloneFormInterface {
protected $translationManager;
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationManager $translation_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->translationManager = $translation_manager;
}
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($container
->get('entity_type.manager'), $container
->get('string_translation'));
}
public function formElement(EntityInterface $entity, $parent = TRUE) {
$form = [];
if ($this->entityTypeManager
->getDefinition($entity
->getEntityTypeId())
->getKey('label')) {
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->translationManager
->translate('New Label'),
'#maxlength' => 255,
'#required' => TRUE,
];
}
$max_length = 64;
if ($entity
->getEntityType()
->getBundleOf()) {
$max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH;
}
$form['id'] = [
'#type' => 'machine_name',
'#title' => $this->translationManager
->translate('New Id'),
'#maxlength' => $max_length,
'#required' => TRUE,
];
if (method_exists($entity, 'getTargetType')) {
$form['id']['#field_prefix'] = $entity
->getTargetType() . '.';
}
if (method_exists($entity, 'load')) {
$form['id']['#machine_name'] = [
'exists' => get_class($entity) . '::load',
];
}
return $form;
}
public function getValues(FormStateInterface $form_state) {
$field_prefix = '';
if (isset($form_state
->getCompleteForm()['id']['#field_prefix'])) {
$field_prefix = $form_state
->getCompleteForm()['id']['#field_prefix'];
}
return [
'id' => $field_prefix . $form_state
->getValue('id'),
'label' => $form_state
->getValue('label'),
];
}
}