You are here

class FormComponentAddForm in Flexiform 8

Provides a form for adding new form components.

Hierarchy

Expanded class hierarchy of FormComponentAddForm

File

src/Form/FormComponentAddForm.php, line 20

Namespace

Drupal\flexiform\Form
View source
class FormComponentAddForm extends FormBase {

  /**
   * The form display.
   *
   * @var \Drupal\flexiform\FlexiformEntityFormDisplay
   */
  protected $formDisplay;

  /**
   * The form component plugin manager.
   *
   * @var \Drupal\flexiform\FormComponentTypePluginManager
   */
  protected $pluginManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The router.
   *
   * @var \Symfony\Component\Routing\RouterInterface
   */
  protected $router;

  /**
   * Constructor.
   */
  public function __construct(FormComponentTypePluginManager $plugin_manager, EntityTypeManagerInterface $entity_type_manager, RouterInterface $router) {
    $this->pluginManager = $plugin_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->router = $router;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.flexiform.form_component_type'), $container
      ->get('entity_type.manager'), $container
      ->get('router'));
  }

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

  /**
   * Get the form entity manager.
   *
   * @return \Drupal\flexiform\FormEntity\FlexiformFormEntityManager
   *   The form entity manager.
   */
  protected function formEntityManager() {
    return $this->formDisplay
      ->getFormEntityManager();
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, FlexiformEntityFormDisplayInterface $form_display = NULL, $component_type = '') {
    $this->formDisplay = $form_display;
    $this->componentType = $this->pluginManager
      ->createInstance($component_type);
    $this->componentType
      ->setFormDisplay($form_display);
    $form['admin_label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Administration Label'),
      '#description' => $this
        ->t('A label for this component. This will only be used administrativly'),
    ];
    $form['name'] = [
      '#type' => 'machine_name',
      '#title' => $this
        ->t('Component Name'),
      '#description' => $this
        ->t('The name of this component. This must be unique in the form.'),
      '#machine_name' => [
        'source' => [
          'admin_label',
        ],
        'exists' => [
          $this,
          'nameExists',
        ],
      ],
    ];
    $form['region'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Region'),
      '#options' => $this->formDisplay
        ->getRegionOptions(),
    ];
    unset($form['region']['#options']['hidden']);
    $form['options'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#parents' => [
        'options',
      ],
    ];
    $form['options'] += $this->componentType
      ->addComponentForm($form['options'], $form_state);
    $form['actions'] = [
      '#type' => 'actions',
      'submit' => [
        '#type' => 'submit',
        '#value' => $this
          ->t('Add Component'),
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!empty($this->componentType)) {
      $this->componentType
        ->addComponentFormValidate($form['options'], $form_state);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $name = $form_state
      ->getValue('name');
    $options = [
      'component_type' => $this->componentType
        ->getPluginId(),
      'region' => $form_state
        ->getValue('region'),
      'admin_label' => $form_state
        ->getValue('admin_label'),
    ];
    $this->componentType
      ->addComponentFormSubmit($form['options'], $form_state);
    if ($plugin_options = $form_state
      ->getValue('options')) {
      $options += $plugin_options;
    }
    $this->formDisplay
      ->setComponent($name, $options);
    $this->formDisplay
      ->save();
    $params = [
      'form_mode_name' => $this->formDisplay
        ->get('mode'),
    ];
    $entity_type_id = $this->formDisplay
      ->get('targetEntityType');
    $entity_type = $this->entityTypeManager
      ->getDefinition($entity_type_id);
    if ($route_name = $entity_type
      ->get('field_ui_base_route')) {
      $route = $this->router
        ->getRouteCollection()
        ->get($route_name);
      $path = $route
        ->getPath();
      if (strpos($path, '{' . $entity_type
        ->getBundleEntityType() . '}') !== FALSE) {
        $params[$entity_type
          ->getBundleEntityType()] = $this->formDisplay
          ->get('bundle');
      }
      elseif (strpos($path, '{bundle}') !== FALSE) {
        $params['bundles'] = $this->formDisplay
          ->get('bundle');
      }
    }
    $form_state
      ->setRedirect("entity.entity_form_display.{$entity_type_id}.form_mode", $params);
  }

  /**
   * Ajax the plugin selection.
   */
  public function ajaxSubmit(array $form, FormStateInterface $form_state) {

    // Prepare redirect parameters.
    $params = [
      'form_mode_name' => $this->formDisplay
        ->get('mode'),
    ];
    $entity_type_id = $this->formDisplay
      ->get('targetEntityType');
    $entity_type = $this->entityTypeManager
      ->getDefinition($entity_type_id);
    if ($route_name = $entity_type
      ->get('field_ui_base_route')) {
      $route = $this->router
        ->getCollection()
        ->get($route_name);
      $path = $route
        ->getPath();
      if (strpos($path, '{' . $entity_type
        ->getBundleEntityType() . '}') !== FALSE) {
        $params[$entity_type
          ->getBundleEntityType()] = $this->formDisplay
          ->get('bundle');
      }
      elseif (strpos($path, '{bundle}') !== FALSE) {
        $params['bundles'] = $this->formDisplay
          ->get('bundle');
      }
    }
    $response = new AjaxResponse();
    $response
      ->addCommand(new CloseModalDialogCommand());
    $response
      ->addCommand(new RedirectCommand((new Url("entity.entity_form_display.{$entity_type_id}.form_mode", $params))
      ->toString()));
    return $response;
  }

  /**
   * Check whether the namespace already exists.
   */
  public function nameExists($name, $element, FormStateInterface $form_state) {
    return $this->formDisplay
      ->getComponent($name) !== NULL;
  }

}

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::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.
FormComponentAddForm::$entityTypeManager protected property The entity type manager.
FormComponentAddForm::$formDisplay protected property The form display.
FormComponentAddForm::$pluginManager protected property The form component plugin manager.
FormComponentAddForm::$router protected property The router.
FormComponentAddForm::ajaxSubmit public function Ajax the plugin selection.
FormComponentAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FormComponentAddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FormComponentAddForm::formEntityManager protected function Get the form entity manager.
FormComponentAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FormComponentAddForm::nameExists public function Check whether the namespace already exists.
FormComponentAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FormComponentAddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FormComponentAddForm::__construct public function Constructor.
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.
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.