View source
<?php
namespace Drupal\workflows\Form;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\workflows\Entity\Workflow;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WorkflowAddForm extends EntityForm {
protected $workflowTypePluginManager;
public function __construct(PluginManagerInterface $workflow_type_plugin_manager) {
$this->workflowTypePluginManager = $workflow_type_plugin_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.workflows.type'));
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$workflow = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Label'),
'#maxlength' => 255,
'#default_value' => $workflow
->label(),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $workflow
->id(),
'#machine_name' => [
'exists' => [
Workflow::class,
'load',
],
],
];
$workflow_types = array_column($this->workflowTypePluginManager
->getDefinitions(), 'label', 'id');
$form['workflow_type'] = [
'#type' => 'select',
'#title' => $this
->t('Workflow type'),
'#required' => TRUE,
'#options' => $workflow_types,
];
return $form;
}
public function save(array $form, FormStateInterface $form_state) {
$workflow = $this->entity;
$return = $workflow
->save();
if (empty($workflow
->getTypePlugin()
->getStates())) {
$this
->messenger()
->addStatus($this
->t('Created the %label Workflow. In order for the workflow to be enabled there needs to be at least one state.', [
'%label' => $workflow
->label(),
]));
$form_state
->setRedirectUrl($workflow
->toUrl('add-state-form'));
}
else {
$this
->messenger()
->addStatus($this
->t('Created the %label Workflow.', [
'%label' => $workflow
->label(),
]));
$form_state
->setRedirectUrl($workflow
->toUrl('edit-form'));
}
return $return;
}
protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
$entity
->set('label', $values['label']);
$entity
->set('id', $values['id']);
$entity
->set('type', $values['workflow_type']);
}
}