You are here

class AutocompletionConfigurationEditForm in Search Autocomplete 8

Same name and namespace in other branches
  1. 2.x src/Form/AutocompletionConfigurationEditForm.php \Drupal\search_autocomplete\Form\AutocompletionConfigurationEditForm

Class AutocompletionConfigurationEditForm

Provides the edit form for our AutocompletionConfiguration entity.

@package Drupal\search_autocomplete\Form

Hierarchy

Expanded class hierarchy of AutocompletionConfigurationEditForm

File

src/Form/AutocompletionConfigurationEditForm.php, line 22

Namespace

Drupal\search_autocomplete\Form
View source
class AutocompletionConfigurationEditForm extends AutocompletionConfigurationFormBase {

  /**
   * Returns the actions provided by this form.
   *
   * For the edit form, we only need to change the text of the submit button.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   An associative array containing the current state of the form.
   *
   * @return array
   *   An array of supported actions for the current entity form.
   */
  public function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->t('Update');
    return $actions;
  }

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::form() and
   * Drupal\search_autocomplete\Form\AutocompletionConfigurationFormBase::form()
   *
   * Builds the entity add form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   An associative array containing the current state of the form.
   *
   * @return array
   *   An associative array containing the autocompletion_configuration
   *   add/edit form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Get anything we need from the base class.
    $form = parent::buildForm($form, $form_state);

    // ------------------------------------------------------------------.
    // HOW - How to display Search Autocomplete suggestions.
    $form['search_autocomplete_how'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('HOW - How to display Search Autocomplete suggestions?'),
      '#collapsible' => TRUE,
      '#open' => FALSE,
    ];

    // Minimum characters to set autocompletion on.
    $form['search_autocomplete_how']['minChar'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Minimum keyword size that uncouple autocomplete search'),
      '#description' => $this
        ->t('Please enter the minimum number of character a user must input before autocompletion starts.'),
      '#default_value' => $this->entity
        ->getMinChar(),
      '#maxlength' => 2,
      '#required' => TRUE,
    ];

    // Number of suggestions to display.
    $form['search_autocomplete_how']['maxSuggestions'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Limit of the autocomplete search result'),
      '#description' => $this
        ->t('Please enter the maximum number of suggestion to display.'),
      '#default_value' => $this->entity
        ->getMaxSuggestions(),
      '#maxlength' => 2,
      '#required' => TRUE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['autoSubmit'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Auto Submit'),
      '#description' => $this
        ->t('If enabled, the form will be submitted automatically as soon as your user choose a suggestion in the popup list.'),
      '#default_value' => $this->entity
        ->getAutoSubmit(),
    ];

    // Check if form should be auto redirected.
    $form['search_autocomplete_how']['autoRedirect'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Auto Redirect'),
      '#description' => $this
        ->t('If enabled, the user will be directly routed to the suggestion he chooses instead of performing form validation process. Only works if "link" attribute is existing and if "Auto Submit" is enabled.'),
      '#default_value' => $this->entity
        ->getAutoRedirect(),
    ];

    // ###
    // "View all results" custom configurations.
    $form['search_autocomplete_how']['moreResultsSuggestion'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Custom behaviour when some suggestions are available'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['moreResultsSuggestion']['moreResultsLabel'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom "view all results" message label'),
      '#description' => $this
        ->t('This message is going to be displayed at the end of suggestion list when suggestions are found.') . $this
        ->t('Leave empty to disable this functionality.') . '<br/>' . $this
        ->t('You can use HTML tags as well as the token [search-phrase] to replace user input or [search-count] to replace the number of matching results.'),
      '#default_value' => $this
        ->t($this->entity
        ->getMoreResultsLabel()),
      '#maxlength' => 255,
      '#required' => FALSE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['moreResultsSuggestion']['moreResultsValue'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom "view all results" message value'),
      '#description' => $this
        ->t('If a label is filled above, this is the value that will be picked when the message is selected.') . $this
        ->t('Leave empty if you don\'t want the message to be selectable.') . '<br/>' . $this
        ->t('You can use the token [search-phrase] to replace user input.'),
      '#default_value' => $this
        ->t($this->entity
        ->getMoreResultsValue()),
      '#maxlength' => 255,
      '#required' => FALSE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['moreResultsSuggestion']['moreResultsLink'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom "view all results" URL redirection'),
      '#description' => $this
        ->t('If "Auto redirect" is checked and an URL is given for this configuration, the user will be redirected to this URL when the message is clicked. Leave empty if you rather like a standard Drupal behavior.'),
      '#default_value' => $this
        ->t($this->entity
        ->getMoreResultsLink()),
      '#maxlength' => 255,
      '#required' => FALSE,
    ];

    // ###
    // "No resuls" custom configurations.
    $form['search_autocomplete_how']['noResultSuggestion'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Custom behaviour when no suggestions are found'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['noResultSuggestion']['noResultLabel'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom "no result" message label'),
      '#description' => $this
        ->t('This message is going to be displayed when no suggestions can be found.') . $this
        ->t('Leave empty to disable this functionality.') . '<br/>' . $this
        ->t('You can use HTML tags as well as the token [search-phrase] to replace user input.'),
      '#default_value' => $this
        ->t($this->entity
        ->getNoResultLabel()),
      '#maxlength' => 255,
      '#required' => FALSE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['noResultSuggestion']['noResultValue'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom "no result" message value'),
      '#description' => $this
        ->t('If a label is filled above, this is the value that will be picked when the message is selected.') . $this
        ->t('Leave empty if you don\'t want the message to be selectable.') . '<br/>' . $this
        ->t('You can use the token [search-phrase] to replace user input.'),
      '#default_value' => $this
        ->t($this->entity
        ->getNoResultValue()),
      '#maxlength' => 255,
      '#required' => FALSE,
    ];

    // Check if form should be auto submitted.
    $form['search_autocomplete_how']['noResultSuggestion']['noResultLink'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom "no result" URL redirection'),
      '#description' => $this
        ->t('If "Auto redirect" is checked and an URL is given for this configuration, the user will be redirected to this URL when the message is clicked. Leave empty if you rather like a standard Drupal behavior.'),
      '#default_value' => $this
        ->t($this->entity
        ->getNoResultLink()),
      '#maxlength' => 255,
      '#required' => FALSE,
    ];

    // ------------------------------------------------------------------.
    // WHAT - What to display in Search Autocomplete suggestions.
    $form['search_autocomplete_what'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('WHAT - What to display in Search Autocomplete suggestions?'),
      '#description' => $this
        ->t('Choose which data should be added to autocompletion suggestions.'),
      '#collapsible' => TRUE,
      '#open' => TRUE,
    ];
    $source = $this->entity
      ->getSource();
    $form['search_autocomplete_what']['source'] = [
      '#type' => 'textfield',
      '#autocomplete_route_name' => 'search_autocomplete.view_autocomplete',
      '#description' => $this
        ->t('Enter the URL of your callback for suggestions.') . '<br/>' . $this
        ->t('You can enter an internal path such as %node-xx or an external URL such as %url. You can also use autocompletion to target a specific View display.', [
        '%node-xx' => '/node/xx',
        '%url' => 'http://example.com',
      ]),
      '#element_validate' => [
        [
          $this,
          'validateUriElement',
        ],
      ],
      '#default_value' => $this->entity
        ->getSource(),
      '#size' => 80,
      '#attributes' => [
        'data-autocomplete-first-character-blacklist' => '/#?',
      ],
    ];

    // Template to use.
    $themes = [];
    $files = file_scan_directory(drupal_get_path('module', 'search_autocomplete') . '/css/themes', '/.*\\.css\\z/', [
      'recurse' => FALSE,
    ]);
    foreach ($files as $file) {
      $themes[$file->filename] = $file->name;
    }
    $form['search_autocomplete_what']['theme'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Select a theme for your suggestions'),
      '#options' => $themes,
      '#default_value' => $this->entity
        ->getTheme(),
      '#description' => $this
        ->t('Choose the theme to use for autocompletion dropdown popup. Read <a href="http://drupal-addict.com/nos-projets/search-autocomplete">documentation</a> to learn how to make your own.'),
    ];

    // ------------------------------------------------------------------.
    // ADVANCED - Advanced options.
    $form['search_autocomplete_advanced'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('ADVANCED - Advanced options'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $form['search_autocomplete_advanced']['selector'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('ID selector for this form'),
      '#description' => $this
        ->t('Please change only if you know what you do, read <a href="http://drupal-addict.com/nos-projets/search-autocomplete">documentation</a> first.'),
      '#default_value' => $this->entity
        ->getSelector(),
      '#maxlength' => 255,
      '#size' => 35,
    ];

    // Return the form.
    return $form;
  }

  /**
   * Validation callback for URI form.
   *
   * @param array $element
   *   The element itself
   * @param FormStateInterface $form_state
   *   The submitted form data.
   */
  public function validateUriElement($element, FormStateInterface $form_state) {
    $source = $form_state
      ->getValue('source');
    $entity_ids = NULL;

    // Check if source input is a valid View display.
    $input_source = explode('::', $source);
    if (count($input_source) == 2) {
      $entity_ids = Drupal::service('entity.query')
        ->get('view')
        ->condition('status', TRUE)
        ->condition('id', $input_source[0])
        ->condition("display.*.id", $input_source[1])
        ->execute();
    }

    // If Views are found: it's OK.
    if (!empty($entity_ids)) {
      return;
    }
    elseif (UrlHelper::isExternal($source)) {
      return;
    }
    else {
      if (!Drupal::service('path.validator')
        ->isValid($source)) {
        $form_state
          ->setErrorByName('source', $this
          ->t('The input source is not valid. Please enter a Drupal valid path, a View display (using completion) or a valid external URL.'));
      }
    }
  }

  /**
   * Autocomplete the label of a view.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object that contains the typed tags.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The matched entity labels as a JSON response.
   */
  public function viewAutocomplete(Request $request) {
    $matches = [];

    // Retrieve elligible views.
    $displays = Views::getApplicableViews('autocompletion_callback_display');

    // Add the view as a suggestion if meeting user_input
    $options = [];
    foreach ($displays as $data) {
      list($view_id, $display_id) = $data;
      $view = Views::getView($view_id);
      $display = $view
        ->getDisplay();
      $suggestion_value = $view->storage
        ->get('id') . '::' . $display_id;
      $suggestion_label = $view->storage
        ->get('label') . '::' . $display->display['display_title'];
      if (stristr($suggestion_label, $request->query
        ->get('q')) !== FALSE) {
        $matches[] = [
          'value' => $suggestion_value,
          'label' => $suggestion_label,
        ];
      }
    }
    return new JsonResponse($matches);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AutocompletionConfigurationEditForm::actions public function Returns the actions provided by this form. Overrides AutocompletionConfigurationFormBase::actions
AutocompletionConfigurationEditForm::buildForm public function Overrides Drupal\Core\Entity\EntityFormController::form() and Drupal\search_autocomplete\Form\AutocompletionConfigurationFormBase::form() Overrides AutocompletionConfigurationFormBase::buildForm
AutocompletionConfigurationEditForm::validateUriElement public function Validation callback for URI form.
AutocompletionConfigurationEditForm::viewAutocomplete public function Autocomplete the label of a view.
AutocompletionConfigurationFormBase::$entityStorage protected property
AutocompletionConfigurationFormBase::create public static function Factory method for AutocompletionConfigurationFormBase. Overrides FormBase::create
AutocompletionConfigurationFormBase::save public function Overrides Drupal\Core\Entity\EntityFormController::save(). Overrides EntityForm::save 1
AutocompletionConfigurationFormBase::validateForm public function Overrides Drupal\Core\Entity\EntityFormController::validate(). Overrides FormBase::validateForm
AutocompletionConfigurationFormBase::__construct public function Construct the AutocompletionConfigurationFormBase.
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::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::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::form public function Gets the actual form array to be built. 30
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::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::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 FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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.