You are here

class MaestroTemplateBuilderEditTask in Maestro 8.2

Same name and namespace in other branches
  1. 3.x modules/maestro_template_builder/src/Form/MaestroTemplateBuilderEditTask.php \Drupal\maestro_template_builder\Form\MaestroTemplateBuilderEditTask

Maestro Template Editor Edit a Task Form.

Hierarchy

Expanded class hierarchy of MaestroTemplateBuilderEditTask

1 string reference to 'MaestroTemplateBuilderEditTask'
maestro_template_builder.routing.yml in modules/maestro_template_builder/maestro_template_builder.routing.yml
modules/maestro_template_builder/maestro_template_builder.routing.yml

File

modules/maestro_template_builder/src/Form/MaestroTemplateBuilderEditTask.php, line 17

Namespace

Drupal\maestro_template_builder\Form
View source
class MaestroTemplateBuilderEditTask extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'template_edit_task';
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // TODO:  we should be passing validation off to the tasks as well.
    $templateMachineName = $form_state
      ->getValue('template_machine_name');
    $taskID = $form_state
      ->getValue('task_id');
    $template = MaestroEngine::getTemplate($templateMachineName);
    $task = MaestroEngine::getTemplateTaskByID($templateMachineName, $taskID);
    $executableTask = MaestroEngine::getPluginTask($task['tasktype']);
    $executableTask
      ->validateTaskEditForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function cancelForm(array &$form, FormStateInterface $form_state) {

    // We cancel the modal dialog by first sending down the form's error state as the cancel is a submit.
    // we then close the modal.
    $response = new AjaxResponse();
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

    // Remove the session variable for the task being edited.
    $_SESSION['maestro_template_builder']['maestro_editing_task'] = '';
    $response
      ->addCommand(new HtmlCommand('#edit-task-form', $form));
    $response
      ->addCommand(new CloseModalDialogCommand());
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // If we have errors in the form, show those.
    if ($form_state
      ->getErrors()) {
      unset($form['#prefix'], $form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response = new AjaxResponse();

      // Replaces the form HTML with the validated HTML.
      $response
        ->addCommand(new HtmlCommand('#edit-task-form', $form));
      return $response;
    }
    else {

      // This should be managed by the engine.  in here for the time being.
      $templateMachineName = $form_state
        ->getValue('template_machine_name');
      $taskID = $form_state
        ->getValue('task_id');
      $template = MaestroEngine::getTemplate($templateMachineName);
      $task = MaestroEngine::getTemplateTaskByID($templateMachineName, $taskID);
      $executableTask = MaestroEngine::getPluginTask($task['tasktype']);

      // first, lets let the task do any specific or unique task preparations.
      // Prepares any specific pieces of the task for us.
      $executableTask
        ->prepareTaskForSave($form, $form_state, $task);

      // Now the core maestro requirements like the assignments and notifications.
      $result = $executableTask
        ->saveTask($form, $form_state, $task);

      // Oh Oh.  Some sort of error in saving the template.
      if ($result === FALSE) {
        \Drupal::messenger()
          ->addError(t('Error saving your task.'));
        $form['status_messages'] = [
          '#type' => 'status_messages',
          '#weight' => -10,
        ];
      }
    }

    // Rebuild the form to get an updated table of assignment information.
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * {@inheritdoc}
   */
  public function saveForm(array &$form, FormStateInterface $form_state) {

    // If we have errors in the form, show those.
    if ($form_state
      ->getErrors()) {
      unset($form['#prefix'], $form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response = new AjaxResponse();

      // Replaces the form HTML with the validated HTML.
      $response
        ->addCommand(new HtmlCommand('#edit-task-form', $form));
      return $response;
    }

    // Save of the task has already been done in the submit.  We now are only responsible for updating the UI and updating the form.
    $templateMachineName = $form_state
      ->getValue('template_machine_name');
    $taskID = $form_state
      ->getValue('task_id');
    $task = MaestroEngine::getTemplateTaskByID($templateMachineName, $taskID);
    $update = [
      'label' => $task['label'],
      'taskid' => $task['id'],
      'body' => 'placeholder',
      'participate_in_workflow_status_stage' => $task['participate_in_workflow_status_stage'],
      'workflow_status_stage_number' => $task['workflow_status_stage_number'],
      'workflow_status_stage_message' => $task['workflow_status_stage_message'],
    ];
    $response = new AjaxResponse();
    $response
      ->addCommand(new FireJavascriptCommand('maestroUpdateMetaData', $update));
    $response
      ->addCommand(new HtmlCommand('#edit-task-form', $form));
    $response
      ->addCommand(new FireJavascriptCommand('maestroShowSavedMessage', []));
    return $response;
  }

  /**
   * Ajax callback for add-new-form button click.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $templateMachineName = '') {
    $taskID = Xss::filter($_SESSION['maestro_template_builder']['maestro_editing_task']);
    $template = MaestroEngine::getTemplate($templateMachineName);
    $task = MaestroEngine::getTemplateTaskByID($templateMachineName, $taskID);
    $task['form_state'] = $form_state;

    // Need to validate this taskID and template to ensure that they exist.
    if ($taskID == '' || $template == NULL || $task == NULL) {
      $form = [
        '#title' => t('Error!'),
        '#markup' => t('The task or template you are attempting to edit does not exist'),
      ];
      return $form;
    }
    $form = [
      '#title' => $this
        ->t('Editing Task') . ': ' . $task['label'] . '(' . $taskID . ')',
      '#prefix' => '<div id="edit-task-form">',
      '#suffix' => '</div>',
    ];
    $form['save_task_notification'] = [
      '#markup' => $this
        ->t('Task Saved'),
      '#prefix' => '<div id="save-task-notificaiton" class="messages messages--status">',
      '#suffix' => '</div>',
    ];

    // Get a handle to the task plugin.
    $executableTask = MaestroEngine::getPluginTask($task['tasktype']);

    // Get the base edit form that all tasks adhere to.
    $form += $executableTask
      ->getBaseEditForm($task, $templateMachineName);

    // We now will pull back the edit form provided to us by the task itself.
    // this gives ultimate flexibility to developers.
    // even form alters work on this form by allowing the dev to detect what task_id is being edited
    // and get the task type and do any modifications on it from there.
    $form += $executableTask
      ->getTaskEditForm($task, $templateMachineName);

    // Now is this thing interactive or not?
    // if so, we show the assignment and notification tabs.  If not, leave it out.
    if ($executableTask
      ->isInteractive()) {
      $form += $executableTask
        ->getAssignmentsAndNotificationsForm($task, $templateMachineName);
    }

    // Save button in an actions bar:
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save Task'),
      '#required' => TRUE,
      '#ajax' => [
        // Use saveFrom rather than submitForm to alleviate the issue of calling a save handler twice.
        'callback' => [
          $this,
          'saveForm',
        ],
        'wrapper' => '',
      ],
    ];
    $form['actions']['close'] = [
      '#type' => 'button',
      '#value' => $this
        ->t('Close'),
      '#required' => TRUE,
      '#ajax' => [
        'callback' => [
          $this,
          'cancelForm',
        ],
        'wrapper' => '',
      ],
    ];
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MaestroTemplateBuilderEditTask::buildForm public function Ajax callback for add-new-form button click. Overrides FormInterface::buildForm
MaestroTemplateBuilderEditTask::cancelForm public function
MaestroTemplateBuilderEditTask::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MaestroTemplateBuilderEditTask::saveForm public function
MaestroTemplateBuilderEditTask::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MaestroTemplateBuilderEditTask::validateForm public function Form validation handler. Overrides FormBase::validateForm
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.