commands-1.x-dev/src/Form/CommandForm.php

src/Form/CommandForm.php
<?php

namespace Drupal\commands\Form;

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

/**
 * Form controller for the command entity edit forms.
 */
class CommandForm extends ContentEntityForm {

  public function form(array $form, FormStateInterface $form_state)
  {
    $entity_type = $this->getBundleEntity();
    // This is just for display.
    $form['command_template'] = [
      '#title' => $this->t('Command'),
      '#type' => 'item',
      'command' => [
        '#type' => 'html_tag',
        '#tag' => 'pre',
        '#value' => implode(PHP_EOL, $entity_type->commandPlugin()->command()),
      ],
      '#description' => $this->t('The command that will be run.'),
      '#required' => TRUE,
      '#size' => 30,
    ];

    $form['working_directory'] = [
      '#title' => $this->t('Working Directory'),
      '#type' => 'textfield',
      '#default_value' => $this->entity->working_directory->value,
      '#description' => $this->t('The directory to run the command in.'),
      '#required' => TRUE,
      '#size' => 30,
    ];

    // Inject form elements from command plugins.
    $command_plugin = $this->getBundleEntity()->commandPlugin();
    $form = parent::form($form, $form_state);

    $form['parameters'] = [
      '#tree' => true,
    ];
    $form = $command_plugin->form($form, $form_state);
    return $form;

  }

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

    $entity = $this->getEntity();
    $result = parent::save($form, $form_state);
    $message_arguments = ['%label' => $entity->toLink()->toString()];
    $logger_arguments = [
      '%label' => $entity->label(),
      'link' => $entity->toLink($this->t('View'))->toString(),
    ];

    switch ($result) {
      case SAVED_NEW:
        $this->messenger()->addStatus($this->t('New command %label has been created.', $message_arguments));
        $this->logger('commands')->notice('Created new command %label', $logger_arguments);
        break;

      case SAVED_UPDATED:
        $this->messenger()->addStatus($this->t('The command %label has been updated.', $message_arguments));
        $this->logger('commands')->notice('Updated command %label.', $logger_arguments);
        break;
    }

    $form_state->setRedirect('entity.command.canonical', ['command' => $entity->id()]);

    return $result;
  }

}

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

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