You are here

class ParagraphsBrowserForm in Paragraphs Browser 8

Class CleanupUrlAliases.

@package Drupal\paragraphs_browser\Form

Hierarchy

Expanded class hierarchy of ParagraphsBrowserForm

File

src/Form/ParagraphsBrowserForm.php, line 28
Contains \Drupal\paragraphs_browser\Form\ParagraphsBrowserForm.

Namespace

Drupal\paragraphs_browser\Form
View source
class ParagraphsBrowserForm extends FormBase {

  /**
   * The index for which the fields are configured.
   *
   * @var \Drupal\search_api\IndexInterface
   */
  protected $entity;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Constructs a new ParagraphsTypeDeleteConfirm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('module_handler'), $container
      ->get('current_user'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, FieldConfig $field_config = null, $paragraphs_browser_type = null, $uuid = null) {
    $form_state
      ->addBuildInfo('uuid', $uuid);
    $form['#attached']['library'][] = 'paragraphs_browser/modal';
    $field_name = $field_config
      ->getName();
    $handler_settings = $field_config
      ->getSetting('handler_settings');
    $target_bundles = is_array($handler_settings['target_bundles']) ? array_keys($handler_settings['target_bundles']) : [];
    $paragraph_type_storage = $this->entityTypeManager
      ->getStorage('paragraphs_type');
    $all_paragraph_types = array_keys($this->entityTypeBundleInfo
      ->getBundleInfo('paragraph'));
    if (empty($target_bundles)) {

      /**
       * if there are no target bundles defined in the field config, then we
       * default to target them all
       */
      $target_bundles = $all_paragraph_types;
    }
    else {
      if ($handler_settings['negate']) {

        /**
         * if "Exclude the selected types" is set, then we only target bundles
         * other than the ones defined in the field config
         */
        $target_bundles = array_diff($all_paragraph_types, $target_bundles);
      }
    }
    $paragraphs_types = $paragraph_type_storage
      ->loadMultiple($target_bundles);

    // Check for permission.
    if ($this->moduleHandler
      ->moduleExists('paragraphs_type_permissions')) {
      foreach ($target_bundles as $key => $bundle) {
        if (!$this->currentUser
          ->hasPermission('create paragraph content ' . $bundle) && !$this->currentUser
          ->hasPermission('bypass paragraphs type content access')) {
          unset($target_bundles[$key]);
        }
      }
    }
    $groups = $paragraphs_browser_type
      ->groupManager()
      ->getDisplayGroups();
    $mapped_items = [];
    foreach ($groups as $group) {
      $mapped_items[$group
        ->getId()] = [];
    }
    foreach ($target_bundles as $bundle) {
      $group_machine_name = $paragraphs_browser_type
        ->getGroupMap($bundle);
      if (isset($mapped_items[$group_machine_name], $groups[$group_machine_name])) {
        $mapped_items[$group_machine_name][] = $paragraphs_types[$bundle];
      }
      else {
        $mapped_items['_na'][] = $paragraphs_types[$bundle];
      }
    }
    $mapped_items = array_filter($mapped_items);
    $form['#attached']['library'][] = 'core/drupal.states';
    $form['paragraph_types'] = [
      '#type' => 'container',
      '#theme_wrappers' => [
        'paragraphs_browser_wrapper',
      ],
    ];

    //@todo: Make filter display optional

    //@todo: Make categories optional.
    $options = [
      'all' => 'All',
    ];
    foreach (array_intersect_key($groups, $mapped_items) as $group_machine_name => $group) {
      $options[$group_machine_name] = $group
        ->getLabel();
    }
    $form['paragraph_types']['filters'] = [
      '#title' => 'Filter',
      '#type' => 'select',
      '#options' => $options,
    ];
    $form['paragraph_types']['pb_modal_text'] = [
      '#title' => $this
        ->t('Search'),
      '#type' => 'textfield',
      '#size' => 20,
      '#placeholder' => $this
        ->t('simple paragraph ... '),
    ];
    foreach ($mapped_items as $group_machine_name => $items) {
      $form['paragraph_types'][$group_machine_name] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            $group_machine_name,
          ],
        ],
      ];
      $form['paragraph_types'][$group_machine_name]['label'] = [
        '#type' => 'markup',
        '#markup' => '<h2>' . $groups[$group_machine_name]
          ->getLabel() . '</h2>',
      ];
      foreach ($items as $paragraph_type) {

        /** @var \Drupal\paragraphs\ParagraphsTypeInterface $paragraph_type */
        $element = [
          '#theme' => 'paragraphs_browser_paragraph_type',
        ];
        $element['label'] = [
          '#markup' => $paragraph_type
            ->label(),
        ];
        if ($description = $paragraph_type
          ->getDescription()) {
          $element['description'] = [
            '#markup' => $description,
          ];
        }
        if ($image_path = $paragraph_type
          ->getThirdPartySetting('paragraphs_browser', 'image_path', $default = NULL)) {

          // If there is a paragraphs browser image, use it
          $src = file_create_url($image_path);
        }
        else {

          // Otherwise, default to paragraphs icon
          $src = $paragraph_type
            ->getIconUrl();
        }
        if (!empty($src)) {
          $element['icon'] = [
            '#type' => 'html_tag',
            '#tag' => 'img',
            '#attributes' => [
              'src' => $src,
              'title' => $paragraph_type
                ->label(),
              'alt' => $paragraph_type
                ->label(),
            ],
          ];
        }
        $form['#parents'] = isset($form['#parents']) ? $form['#parents'] : [];
        $id_prefix = implode('-', array_merge($form['#parents'], [
          $field_name,
        ]));
        $wrapper_id = Html::getUniqueId($id_prefix . '-add-more-wrapper');
        $element['add_more']['add_more_button_' . $paragraph_type
          ->id()] = [
          '#type' => 'submit',
          '#name' => strtr($id_prefix, '-', '_') . '_' . $paragraph_type
            ->id() . '_add_more',
          '#value' => $this
            ->t('Add'),
          '#attributes' => [
            'class' => [
              'field-add-more-submit',
            ],
          ],
          '#limit_validation_errors' => [],
          '#submit' => [
            [
              get_class($this),
              'addMoreSubmit',
            ],
          ],
          '#ajax' => [
            'callback' => [
              get_class($this),
              'addMoreAjax',
            ],
            'wrapper' => $wrapper_id,
            'effect' => 'fade',
          ],
          '#bundle_machine_name' => $paragraph_type
            ->id(),
        ];
        $form['paragraph_types'][$group_machine_name][$paragraph_type
          ->id()] = $element;
      }
    }
    return $form;
  }

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

  /**
   * {@inheritdoc}
   */
  public static function addMoreAjax(array $form, FormStateInterface $form_state) {
    $build_info = $form_state
      ->getBuildInfo();
    $uuid = $build_info['uuid'];
    $response = new AjaxResponse();
    $command = new AddParagraphTypeCommand($uuid, $form_state
      ->getTriggeringElement()['#bundle_machine_name']);
    $response
      ->addCommand($command);

    //    return $element;
    $command = new CloseModalDialogCommand();
    $response
      ->addCommand($command);
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public static function addMoreSubmit(array $form, FormStateInterface $form_state) {
    $form_state
      ->setRebuild();
  }

}

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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
ParagraphsBrowserForm::$currentUser protected property The current user.
ParagraphsBrowserForm::$entity protected property The index for which the fields are configured.
ParagraphsBrowserForm::$entityTypeBundleInfo protected property
ParagraphsBrowserForm::$entityTypeManager protected property
ParagraphsBrowserForm::$moduleHandler protected property The module handler service.
ParagraphsBrowserForm::addMoreAjax public static function
ParagraphsBrowserForm::addMoreSubmit public static function
ParagraphsBrowserForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ParagraphsBrowserForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ParagraphsBrowserForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ParagraphsBrowserForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ParagraphsBrowserForm::__construct public function Constructs a new ParagraphsTypeDeleteConfirm object.
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.