component_library-1.0.x-dev/src/Form/VariantDuplicateForm.php
src/Form/VariantDuplicateForm.php
<?php
declare(strict_types=1);
namespace Drupal\component_library\Form;
use Drupal\component_library\Entity\ComponentLibraryVariant;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\entity\Form\EntityDuplicateFormTrait;
/**
* Duplicate form.
*
* @property \Drupal\component_library\ComponentLibraryVariantInterface $entity
*/
final class VariantDuplicateForm extends EntityForm {
use EntityDuplicateFormTrait;
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state): array {
parent::form($form, $form_state);
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#required' => TRUE,
'#size' => 32,
'#maxlength' => 255,
'#default_value' => $this->t('Duplicate of @label', ['@label' => $this->entity->label()]),
];
$form['id'] = [
'#type' => 'machine_name',
'#maxlength' => 31,
'#machine_name' => [
'exists' => [self::class, 'exists'],
'source' => ['label'],
],
];
$form['pattern'] = [
'#type' => 'hidden',
'#value' => $this->entity->get('pattern'),
];
return $form;
}
public static function exists(string $value, array $element, FormStateInterface $form_state): bool {
return ComponentLibraryVariant::load(ComponentLibraryVariantForm::idFormat($value, $form_state->getValue('pattern'))) !== NULL;
}
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state): array {
$actions = [];
$actions['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Duplicate'),
];
return $actions;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->entity->set('label', $form_state->getValue('label'));
$this->entity->set('id', ComponentLibraryVariantForm::idFormat($form_state->getValue('id'), $form_state->getValue('pattern')));
$this->entity->save();
$form_state->setRedirectUrl($this->entity->toUrl('edit-form'));
}
}
