You are here

class FacetSettingsForm in Facets 8

Provides a form for creating and editing facets.

Hierarchy

Expanded class hierarchy of FacetSettingsForm

File

src/Form/FacetSettingsForm.php, line 20

Namespace

Drupal\facets\Form
View source
class FacetSettingsForm extends EntityForm {

  /**
   * The facet storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $facetStorage;

  /**
   * The plugin manager for facet sources.
   *
   * @var \Drupal\facets\FacetSource\FacetSourcePluginManager
   */
  protected $facetSourcePluginManager;

  /**
   * The plugin manager for processors.
   *
   * @var \Drupal\facets\Processor\ProcessorPluginManager
   */
  protected $processorPluginManager;

  /**
   * Constructs a FacetForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\facets\FacetSource\FacetSourcePluginManager $facet_source_plugin_manager
   *   The plugin manager for facet sources.
   * @param \Drupal\facets\Processor\ProcessorPluginManager $processor_plugin_manager
   *   The plugin manager for processors.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The url generator.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, FacetSourcePluginManager $facet_source_plugin_manager, ProcessorPluginManager $processor_plugin_manager, ModuleHandlerInterface $module_handler, UrlGeneratorInterface $url_generator) {
    $this->facetStorage = $entity_type_manager
      ->getStorage('facets_facet');
    $this->facetSourcePluginManager = $facet_source_plugin_manager;
    $this->processorPluginManager = $processor_plugin_manager;
    $this->moduleHandler = $module_handler;
    $this->urlGenerator = $url_generator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.facets.facet_source'), $container
      ->get('plugin.manager.facets.processor'), $container
      ->get('module_handler'), $container
      ->get('url_generator'));
  }

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

    // If the form is being rebuilt, rebuild the entity with the current form
    // values.
    if ($form_state
      ->isRebuilding()) {
      $this->entity = $this
        ->buildEntity($form, $form_state);
    }
    $form = parent::form($form, $form_state);

    // Set the page title according to whether we are creating or editing the
    // facet.
    if ($this
      ->getEntity()
      ->isNew()) {
      $form['#title'] = $this
        ->t('Add facet');
    }
    else {
      $form['#title'] = $this
        ->t('Facet settings for %label facet', [
        '%label' => $this
          ->getEntity()
          ->label(),
      ]);
    }
    $this
      ->buildEntityForm($form, $form_state, $this
      ->getEntity());
    $form['#attached']['library'][] = 'facets/drupal.facets.edit-facet';
    return $form;
  }

  /**
   * Builds the form for editing and creating a facet.
   *
   * @param array $form
   *   The form array for the complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param \Drupal\facets\FacetInterface $facet
   *   The facets facet entity that is being created or edited.
   */
  public function buildEntityForm(array &$form, FormStateInterface $form_state, FacetInterface $facet) {
    $facet_sources = [];
    foreach ($this->facetSourcePluginManager
      ->getDefinitions() as $facet_source_id => $definition) {
      $facet_sources[$definition['id']] = !empty($definition['label']) ? $definition['label'] : $facet_source_id;
    }
    if (count($facet_sources) == 0) {
      $form['#markup'] = $this
        ->t('You currently have no facet sources defined. You should start by adding a facet source before creating facets.');
      return;
    }
    $form['facet_source_id'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Facet source'),
      '#description' => $this
        ->t('The source where this facet can find its fields.'),
      '#options' => $facet_sources,
      '#default_value' => $facet
        ->getFacetSourceId(),
      '#required' => TRUE,
      '#ajax' => [
        'trigger_as' => [
          'name' => 'facet_source_configure',
        ],
        'callback' => '::buildAjaxFacetSourceConfigForm',
        'wrapper' => 'facets-facet-sources-config-form',
        'method' => 'replace',
        'effect' => 'fade',
      ],
    ];
    $form['facet_source_configs'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'facets-facet-sources-config-form',
      ],
      '#tree' => TRUE,
    ];
    $form['facet_source_configure_button'] = [
      '#type' => 'submit',
      '#name' => 'facet_source_configure',
      '#value' => $this
        ->t('Configure facet source'),
      '#limit_validation_errors' => [
        [
          'facet_source_id',
        ],
      ],
      '#submit' => [
        '::submitAjaxFacetSourceConfigForm',
      ],
      '#ajax' => [
        'callback' => '::buildAjaxFacetSourceConfigForm',
        'wrapper' => 'facets-facet-sources-config-form',
      ],
      '#attributes' => [
        'class' => [
          'js-hide',
        ],
      ],
    ];
    $this
      ->buildFacetSourceConfigForm($form, $form_state);
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#description' => $this
        ->t('The administrative name used for this facet.'),
      '#default_value' => $facet
        ->label(),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $facet
        ->id(),
      '#maxlength' => 50,
      '#required' => TRUE,
      '#machine_name' => [
        'exists' => [
          $this->facetStorage,
          'load',
        ],
        'source' => [
          'name',
        ],
      ],
      '#disabled' => !$facet
        ->isNew(),
    ];
  }

  /**
   * Handles form submissions for the facet source subform.
   */
  public function submitAjaxFacetSourceConfigForm($form, FormStateInterface $form_state) {
    $form_state
      ->setValue('id', NULL);
    $form_state
      ->setRebuild();
  }

  /**
   * Handles changes to the selected facet sources.
   */
  public function buildAjaxFacetSourceConfigForm(array $form, FormStateInterface $form_state) {
    return $form['facet_source_configs'];
  }

  /**
   * Builds the configuration forms for all possible facet sources.
   *
   * @param array $form
   *   An associative array containing the initial structure of the plugin form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the complete form.
   */
  public function buildFacetSourceConfigForm(array &$form, FormStateInterface $form_state) {
    $facet_source_id = $this
      ->getEntity()
      ->getFacetSourceId();
    if (!is_null($facet_source_id) && $facet_source_id !== '') {

      /** @var \Drupal\facets\FacetSource\FacetSourcePluginInterface $facet_source */
      $facet_source = $this->facetSourcePluginManager
        ->createInstance($facet_source_id, [
        'facet' => $this
          ->getEntity(),
      ]);
      if ($config_form = $facet_source
        ->buildConfigurationForm([], $form_state)) {
        $form['facet_source_configs'][$facet_source_id]['#type'] = 'container';
        $form['facet_source_configs'][$facet_source_id]['#attributes'] = [
          'class' => [
            'facet-source-field-wrapper',
          ],
        ];
        $form['facet_source_configs'][$facet_source_id]['#title'] = $this
          ->t('%plugin settings', [
          '%plugin' => $facet_source
            ->getPluginDefinition()['label'],
        ]);
        $form['facet_source_configs'][$facet_source_id] += $config_form;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $facet_source_id = $form_state
      ->getValue('facet_source_id');
    if (!is_null($facet_source_id) && $facet_source_id !== '') {

      /** @var \Drupal\facets\FacetSource\FacetSourcePluginInterface $facet_source */
      $facet_source = $this->facetSourcePluginManager
        ->createInstance($facet_source_id, [
        'facet' => $this
          ->getEntity(),
      ]);
      $facet_source
        ->validateConfigurationForm($form, $form_state);
    }
  }

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

    /** @var \Drupal\facets\FacetInterface $facet */
    $facet = $this
      ->getEntity();
    $is_new = $facet
      ->isNew();
    if ($is_new) {

      // On facet creation, enable all locked processors by default, using their
      // default settings.
      $stages = $this->processorPluginManager
        ->getProcessingStages();
      $processors_definitions = $this->processorPluginManager
        ->getDefinitions();
      foreach ($processors_definitions as $processor_id => $processor) {
        $is_locked = isset($processor['locked']) && $processor['locked'] == TRUE;
        $is_default_enabled = isset($processor['default_enabled']) && $processor['default_enabled'] == TRUE;
        if ($is_locked || $is_default_enabled) {
          $weights = [];
          foreach ($stages as $stage_id => $stage) {
            if (isset($processor['stages'][$stage_id])) {
              $weights[$stage_id] = $processor['stages'][$stage_id];
            }
          }
          $facet
            ->addProcessor([
            'processor_id' => $processor_id,
            'weights' => $weights,
            'settings' => [],
          ]);
        }
      }

      // Set a default widget for new facets.
      $facet
        ->setWidget('links');
      $facet
        ->setUrlAlias($form_state
        ->getValue('id'));
      $facet
        ->setWeight(0);

      // Set default empty behaviour.
      $facet
        ->setEmptyBehavior([
        'behavior' => 'none',
      ]);
      $facet
        ->setOnlyVisibleWhenFacetSourceIsVisible(TRUE);
    }
    $facet_source_id = $form_state
      ->getValue('facet_source_id');
    if (!is_null($facet_source_id) && $facet_source_id !== '') {

      /** @var \Drupal\facets\FacetSource\FacetSourcePluginInterface $facet_source */
      $facet_source = $this->facetSourcePluginManager
        ->createInstance($facet_source_id, [
        'facet' => $this
          ->getEntity(),
      ]);
      $facet_source
        ->submitConfigurationForm($form, $form_state);
    }
    $facet
      ->save();
    if ($is_new) {
      if ($this->moduleHandler
        ->moduleExists('block')) {
        $message = $this
          ->t('Facet %name has been created. Go to the <a href=":block_overview">Block overview page</a> to place the new block in the desired region.', [
          '%name' => $facet
            ->getName(),
          ':block_overview' => $this->urlGenerator
            ->generateFromRoute('block.admin_display'),
        ]);
        $this
          ->messenger()
          ->addMessage($message);
        $form_state
          ->setRedirect('entity.facets_facet.edit_form', [
          'facets_facet' => $facet
            ->id(),
        ]);
      }
    }
    else {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Facet %name has been updated.', [
        '%name' => $facet
          ->getName(),
      ]));
    }
    list($type, ) = explode(':', $facet_source_id);
    if ($type !== 'search_api') {
      return $facet;
    }

    // Ensure that the caching of the view display is disabled, so the search
    // correctly returns the facets.
    if (isset($facet_source) && $facet_source instanceof SearchApiFacetSourceInterface) {
      $view = $facet_source
        ->getViewsDisplay();
      if ($view !== NULL) {
        if ($view->display_handler instanceof Block) {
          $facet
            ->setOnlyVisibleWhenFacetSourceIsVisible(FALSE);
        }
        $view->display_handler
          ->overrideOption('cache', [
          'type' => 'none',
        ]);
        $view
          ->save();
        $this
          ->messenger()
          ->addMessage($this
          ->t('Caching of view %view has been disabled.', [
          '%view' => $view->storage
            ->label(),
        ]));
      }
    }
    return $facet;
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 41
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
FacetSettingsForm::$facetSourcePluginManager protected property The plugin manager for facet sources.
FacetSettingsForm::$facetStorage protected property The facet storage.
FacetSettingsForm::$processorPluginManager protected property The plugin manager for processors.
FacetSettingsForm::buildAjaxFacetSourceConfigForm public function Handles changes to the selected facet sources.
FacetSettingsForm::buildEntityForm public function Builds the form for editing and creating a facet.
FacetSettingsForm::buildFacetSourceConfigForm public function Builds the configuration forms for all possible facet sources.
FacetSettingsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FacetSettingsForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
FacetSettingsForm::submitAjaxFacetSourceConfigForm public function Handles form submissions for the facet source subform.
FacetSettingsForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
FacetSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FacetSettingsForm::__construct public function Constructs a FacetForm object.
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.
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.