commands-1.x-dev/modules/tasks/src/Form/TaskForm.php

modules/tasks/src/Form/TaskForm.php
<?php

declare(strict_types=1);

namespace Drupal\tasks\Form;

use Drupal\commands\Entity\Command;
use Drupal\commands\Entity\CommandType;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for the tasks entity edit forms.
 */
final class TaskForm extends ContentEntityForm {

  public function form(array $form, FormStateInterface $form_state)
  {
    $form = parent::form($form, $form_state);

    $task_type = $this->getBundleEntity();
    $task_plugin = $task_type->getPlugin();

    if ($this->operation == 'add') {
      $form['#title'] = $this->t('%label', ['%label' => $task_type->label()]);
    }

    $form['working_directory'] = [
      '#type' => 'textfield',
      '#title' => t('Working directory'),
      '#default_value' => '',
      '#description' => t('The path to run the commands in.'),
      '#weight' => -100,

    ];
    $form['commands'] = [
      '#title' => t('Commands'),
      '#type' => 'fieldset',
      '#tree' => true,
      '#weight' => -90,
    ];
    $form['params'] = [
      '#title' => t('Parameters'),
      '#type' => 'fieldset',
      '#weight' => -80,
      '#tree' => true,
    ];

    $commands = $task_plugin->commands();
    foreach ($commands as $command_type => $params) {
      $command = CommandType::load($command_type);
      $form['commands'][$command_type] = [
        '#type' => 'checkbox',
        '#title' => $command->label(),
        '#default_value' => true,
        '#description' => $command->description(),
      ];

      // Load parameters.
      $form['params'][$command_type] = $command->commandPlugin()->form($form['plugins'][$command_type] ?? [], $form_state);

      // Log message
      unset($form['advanced']);
      unset($form['revision_information']['#attached']);
      $form['revision_information']['#title'] = t('Log message');
      $form['revision_log']['widget'][0]['value']['#title'] = t('Log message');
      $form['revision_log']['widget'][0]['value']['#description'] = t('Enter a message to save for this task.');

    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this->t('Run');
    return $actions;
  }

  /**
   * @TODO: Create constraint for "commands" field to create them on task validate.
   *
   * @param array $form
   * @param FormStateInterface $form_state
   * @return void
   */
  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    $command_values = [];
    $params = $form_state->getValue('params');
    foreach ($form_state->getValue('commands') as $command_type => $enabled) {
      if ($enabled) {
        $command_values[] = [
          'target_id' => 0,
          'command_type' => $command_type,
          'parameters' => $params[$command_type]['parameters'] ?? [],
          'working_directory' => $form_state->getValue('working_directory')
        ];
      }
    };
    $form_state->setValue('commands', $command_values);
    return parent::validateForm($form, $form_state);
  }
//    // Create Command entities.
//    $params = $form_state->getValue('params');
//    $command_ids = [];
//    foreach ($form_state->getValue('commands') as $command => $enabled) {
//      if ($enabled) {
//        try {
//          $data = [
//            'command_type' => $command,
//            'parameters' => $params[$command]['parameters'] ?? [],
//            'working_directory' => $form_state->getValue('working_directory')
//          ];
//          $commandEntity = Command::create($data);
//          $violations = $commandEntity->validate();
//          if ($violations) {
//            $this->flagViolations($violations, $form, $form_state);
//          }
//          else{
//            $commandEntity->save();
//            $command_ids[] = $commandEntity->id();
//          }
//        }
//        catch (\Exception $e) {
//          $form_state->setError($form, $e->getMessage());
//        }
//
//      }
//    }
//    $this->entity->set('commands', $command_ids);
//    return parent::validateForm($form, $form_state);
//  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state): int {
    $result = parent::save($form, $form_state);

    $message_args = ['%label' => $this->entity->toLink()->toString()];
    $logger_args = [
      '%label' => $this->entity->label(),
      'link' => $this->entity->toLink($this->t('View'))->toString(),
    ];

    switch ($result) {
      case SAVED_NEW:
        $this->messenger()->addStatus($this->t('New tasks %label has been created.', $message_args));
        $this->logger('tasks')->notice('New tasks %label has been created.', $logger_args);
        break;

      case SAVED_UPDATED:
        $this->messenger()->addStatus($this->t('The tasks %label has been updated.', $message_args));
        $this->logger('tasks')->notice('The tasks %label has been updated.', $logger_args);
        break;

      default:
        throw new \LogicException('Could not save the entity.');
    }

    $form_state->setRedirectUrl($this->entity->toUrl());

    return $result;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc