annoying_popup-1.0.0/src/Form/AnnoyingPopupForm.php

src/Form/AnnoyingPopupForm.php
<?php

namespace Drupal\annoying_popup\Form;

use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form handler for the AnnoyingPopup add and edit forms.
 */
class AnnoyingPopupForm extends EntityForm {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Constructs an AnnoyingPopupForm object.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   *   The language maanger.
   */
  public function __construct(LanguageManagerInterface $languageManager) {
    $this->languageManager = $languageManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('language_manager')
    );
  }

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

    /** @var \Drupal\annoying_popup\Entity\AnnoyingPopup $annoyingPopup */
    $annoyingPopup = $this->entity;

    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $annoyingPopup->label(),
      '#description' => $this->t("Label for the popup."),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $annoyingPopup->id(),
      '#machine_name' => [
        'exists' => [$this, 'exist'],
      ],
      '#disabled' => !$annoyingPopup->isNew(),
    ];
    $form['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enabled'),
      '#default_value' => $annoyingPopup->get('enabled'),
      '#description' => $this->t("Enable or disable the popup. Disabled popups will remain completely inactive. For enabled popups the conditions you define below will be evaluated."),
      '#required' => FALSE,
    ];
    $form['content'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Content'),
      '#default_value' => $annoyingPopup->get('content')['value'] ?? '',
      '#description' => $this->t("Content for the popup."),
      '#required' => FALSE,
      '#format' => $annoyingPopup->get('content')['format'] ?? '',
    ];
    $form['action_button'] = [
      '#type' => 'details',
      '#title' => $this->t('Action button'),
      '#description' => $this->t('Define a main action button for this popup, e.g. to link to a details page or survey form.'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];
    $form['action_button']['url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Target URL'),
      '#default_value' => $annoyingPopup->get('action_button')['url'] ?? '',
      '#states' => [
        'required' => [
          ':input[name="action_button[title]"]' => [
            'filled' => TRUE,
          ],
        ],
      ],
    ];
    $form['action_button']['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Button title'),
      '#default_value' => $annoyingPopup->get('action_button')['title'] ?? '',
      '#states' => [
        'required' => [
          ':input[name="action_button[url]"]' => [
            'filled' => TRUE,
          ],
        ],
      ],
    ];
    $form['action_button']['open_in_new_window'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Open link in new window'),
      '#default_value' => $annoyingPopup->get('action_button')['open_in_new_window'] ?? 0,
    ];
    $form['dismiss_button'] = [
      '#type' => 'details',
      '#title' => $this->t('Dismiss button'),
      '#description' => $this->t('Define a button to permanently dismiss this popup.'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];
    $form['dismiss_button']['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Button title'),
      '#default_value' => $annoyingPopup->get('dismiss_button')['title'] ?? $this->t('Dismiss'),
      '#required' => TRUE,
    ];
    $form['visibility'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this->t('Visibility'),
      '#tree' => TRUE,
    ];

    $form['visibility']['request_path'] = [
      '#type' => 'fieldset',
      '#tree' => TRUE,
    ];
    $form['visibility']['request_path']['pages'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Pages'),
      '#description' => $this->t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. An example path is %user-wildcard for every user page. %front is the front page.", [
        '%user-wildcard' => '/user/*',
        '%front' => '<front>',
      ]),
      '#default_value' => $annoyingPopup->get('visibility')['request_path']['pages'] ?? '',
    ];
    $form['visibility']['request_path']['negate'] = [
      '#type' => 'radios',
      '#default_value' => isset($annoyingPopup->get('visibility')['request_path']['negate']) ? (int) $annoyingPopup->get('visibility')['request_path']['negate'] : 0,
      '#options' => [
        $this->t('Show for the listed pages'),
        $this->t('Hide for the listed pages'),
      ],
    ];

    $form['visibility']['languages'] = [
      '#type' => 'fieldset',
      '#tree' => TRUE,
    ];
    $langcodes = $this->languageManager->getLanguages();
    $form['visibility']['languages']['langcodes'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Languages'),
      '#description' => $this->t("Select languages this popup should be shown (or hidden) for."),
      '#options' => array_map(function ($langcode) {
        return $langcode->getName();
      }, $langcodes),
      '#default_value' => $annoyingPopup->get('visibility')['languages']['langcodes'] ?? [],
    ];
    $form['visibility']['languages']['negate'] = [
      '#type' => 'radios',
      '#default_value' => isset($annoyingPopup->get('visibility')['languages']['negate']) ? (int) $annoyingPopup->get('visibility')['languages']['negate'] : 0,
      '#options' => [
        $this->t('Show for the listed languages'),
        $this->t('Hide for the listed languages'),
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $actionButton = $form_state->getValue('action_button');
    if (!empty($actionButton['url'])) {
      $absoluteUrl = FALSE;
      if (preg_match('/^http(s)?\:\/\//', $actionButton['url'])) {
        $absoluteUrl = TRUE;
      }
      if (!UrlHelper::isValid($actionButton['url'], $absoluteUrl)) {
        $form_state->setError($form['action_button']['url'], $this->t('Make sure you enter a valid external URL (https://abc.xyz).'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\annoying_popup\Entity\AnnoyingPopup $annoyingPopup */
    $annoyingPopup = $this->entity;
    $status = $annoyingPopup->save();

    if ($status === SAVED_NEW) {
      $this->messenger()->addMessage($this->t('The %label popup created.', [
        '%label' => $annoyingPopup->label(),
      ]));
    }
    else {
      $this->messenger()->addMessage($this->t('The %label popup updated.', [
        '%label' => $annoyingPopup->label(),
      ]));
    }

    Cache::invalidateTags([$annoyingPopup->getCacheTag()]);
    return $status;
  }

  /**
   * Check whether an AnnoyingPopup configuration entity exists.
   */
  public function exist($id) {
    $entity = $this->entityTypeManager->getStorage('annoying_popup')->getQuery()
      ->condition('id', $id)
      ->accessCheck(TRUE)
      ->execute();
    return (bool) $entity;
  }

}

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

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