You are here

class EmbedButtonForm in Embed 8

Form controller for embed button forms.

Hierarchy

Expanded class hierarchy of EmbedButtonForm

File

src/Form/EmbedButtonForm.php, line 20

Namespace

Drupal\embed\Form
View source
class EmbedButtonForm extends EntityForm {

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

  /**
   * The embed type plugin manager.
   *
   * @var \Drupal\embed\EmbedType\EmbedTypeManager
   */
  protected $embedTypeManager;

  /**
   * Constructs a new EmbedButtonForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\embed\EmbedType\EmbedTypeManager $embed_type_manager
   *   The embed type plugin manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EmbedTypeManager $embed_type_manager, ConfigFactoryInterface $config_factory) {
    $this->entityTypeManager = $entity_type_manager;
    $this->embedTypeManager = $embed_type_manager;
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.embed.type'), $container
      ->get('config.factory'));
  }

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

    /** @var \Drupal\embed\EmbedButtonInterface $button */
    $button = $this->entity;
    $form_state
      ->setTemporaryValue('embed_button', $button);
    $form['label'] = [
      '#title' => $this
        ->t('Label'),
      '#type' => 'textfield',
      '#default_value' => $button
        ->label(),
      '#description' => $this
        ->t('The human-readable name of this embed button. This text will be displayed when the user hovers over the CKEditor button. This name must be unique.'),
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $button
        ->id(),
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#disabled' => !$button
        ->isNew(),
      '#machine_name' => [
        'exists' => [
          EmbedButton::class,
          'load',
        ],
      ],
      '#description' => $this
        ->t('A unique machine-readable name for this embed button. It must only contain lowercase letters, numbers, and underscores.'),
    ];
    $form['type_id'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Embed type'),
      '#options' => $this->embedTypeManager
        ->getDefinitionOptions(),
      '#default_value' => $button
        ->getTypeId(),
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::updateTypeSettings',
        'effect' => 'fade',
      ],
      '#disabled' => !$button
        ->isNew(),
    ];
    if (empty($form['type_id']['#options'])) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('No embed types found.'));
    }

    // Add the embed type plugin settings.
    $form['type_settings'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#prefix' => '<div id="embed-type-settings-wrapper">',
      '#suffix' => '</div>',
    ];
    try {
      if ($plugin = $button
        ->getTypePlugin()) {
        $form['type_settings'] = $plugin
          ->buildConfigurationForm($form['type_settings'], $form_state);
      }
    } catch (PluginNotFoundException $exception) {
      $this
        ->messenger()
        ->addError($exception
        ->getMessage());
      watchdog_exception('embed', $exception);
      $form['type_id']['#disabled'] = FALSE;
    }
    $config = $this
      ->config('embed.settings');
    $upload_location = $config
      ->get('file_scheme') . '://' . $config
      ->get('upload_directory') . '/';
    $form['icon_file'] = [
      '#type' => 'managed_file',
      '#title' => $this
        ->t('Button icon'),
      '#upload_location' => $upload_location,
      '#upload_validators' => [
        'file_validate_extensions' => [
          'gif png jpg jpeg svg',
        ],
        'file_validate_image_resolution' => [
          '32x32',
          '16x16',
        ],
      ],
    ];
    if (!$button
      ->isNew()) {
      $form['icon_reset'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Reset to default icon'),
        '#access' => $button
          ->getIconUrl() !== $button
          ->getTypePlugin()
          ->getDefaultIconUrl(),
      ];
      $form['icon_preview'] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Current icon preview'),
      ];
      $form['icon_preview']['image'] = [
        '#theme' => 'image',
        '#uri' => $button
          ->getIconUrl(),
        '#alt' => $this
          ->t('Preview of @label button icon', [
          '@label' => $button
            ->label(),
        ]),
      ];

      // Show an even nicer preview with CKEditor being used.
      if ($this->moduleHandler
        ->moduleExists('ckeditor')) {
        $form['icon_preview']['image']['#prefix'] = '<div data-toolbar="active" role="form" class="ckeditor-toolbar ckeditor-toolbar-active clearfix"><ul class="ckeditor-active-toolbar-configuration" role="presentation" aria-label="CKEditor toolbar and button configuration."><li class="ckeditor-row" role="group" aria-labelledby="ckeditor-active-toolbar"><ul class="ckeditor-toolbar-groups clearfix js-sortable"><li class="ckeditor-toolbar-group" role="presentation" data-drupal-ckeditor-type="group" data-drupal-ckeditor-toolbar-group-name="Embed button icon preview" tabindex="0"><h3 class="ckeditor-toolbar-group-name" id="ckeditor-toolbar-group-aria-label-for-formatting">Embed button icon preview</h3><ul class="ckeditor-buttons ckeditor-toolbar-group-buttons js-sortable" role="toolbar" data-drupal-ckeditor-button-sorting="target" aria-labelledby="ckeditor-toolbar-group-aria-label-for-formatting"><li data-drupal-ckeditor-button-name="Bold" class="ckeditor-button"><a href="#" role="button" title="' . $button
          ->label() . '" aria-label="' . $button
          ->label() . '"><span class="cke_button_icon">';
        $form['icon_preview']['image']['#suffix'] = '</span></a></li></ul></li></ul></div>';
        $form['icon_preview']['#attached']['library'][] = 'ckeditor/drupal.ckeditor.admin';
      }
    }
    return $form;
  }

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

    /** @var \Drupal\embed\EmbedButtonInterface $button */
    $button = $this->entity;

    // Run embed type plugin validation.
    if ($plugin = $button
      ->getTypePlugin()) {
      $plugin_form_state = clone $form_state;
      $plugin_form_state
        ->setValues($button
        ->getTypeSettings());
      $plugin
        ->validateConfigurationForm($form['type_settings'], $plugin_form_state);
      if ($errors = $plugin_form_state
        ->getErrors()) {
        foreach ($errors as $name => $error) {
          $form_state
            ->setErrorByName($name, $error);
        }
      }
      $form_state
        ->setValue('type_settings', $plugin_form_state
        ->getValues());
    }
  }

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

    /** @var \Drupal\embed\EmbedButtonInterface $button */
    $button = $this->entity;

    // Run embed type plugin submission.
    $plugin = $button
      ->getTypePlugin();
    $plugin_form_state = clone $form_state;
    $plugin_form_state
      ->setValues($button
      ->getTypeSettings());
    $plugin
      ->submitConfigurationForm($form['type_settings'], $plugin_form_state);
    $form_state
      ->setValue('type_settings', $plugin
      ->getConfiguration());
    $button
      ->set('type_settings', $plugin
      ->getConfiguration());

    // If a file was uploaded to be used as the icon, get an encoded URL to be
    // stored in the config entity.
    $icon_fid = $form_state
      ->getValue([
      'icon_file',
      '0',
    ]);
    if (!empty($icon_fid) && ($file = $this->entityTypeManager
      ->getStorage('file')
      ->load($icon_fid))) {
      $file
        ->setPermanent();
      $file
        ->save();
      $button
        ->set('icon', EmbedButton::convertImageToEncodedData($file
        ->getFileUri()));
    }
    elseif ($form_state
      ->getValue('icon_reset')) {
      $button
        ->set('icon', NULL);
    }
    $status = $button
      ->save();
    $t_args = [
      '%label' => $button
        ->label(),
    ];
    if ($status === SAVED_UPDATED) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The embed button %label has been updated.', $t_args));
      $this
        ->logger('embed')
        ->info('Updated embed button %label.', $t_args);
    }
    elseif ($status === SAVED_NEW) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The embed button %label has been added.', $t_args));
      $this
        ->logger('embed')
        ->info('Added embed button %label.', $t_args);
    }
    $form_state
      ->setRedirectUrl($button
      ->toUrl());
  }

  /**
   * Ajax callback to update the form fields which depend on embed type.
   *
   * @param array $form
   *   The build form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   Ajax response with updated options for the embed type.
   */
  public function updateTypeSettings(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Update options for entity type bundles.
    $response
      ->addCommand(new ReplaceCommand('#embed-type-settings-wrapper', $form['type_settings']));
    return $response;
  }

}

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
EmbedButtonForm::$embedTypeManager protected property The embed type plugin manager.
EmbedButtonForm::$entityTypeManager protected property The entity type manager service. Overrides EntityForm::$entityTypeManager
EmbedButtonForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EmbedButtonForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
EmbedButtonForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
EmbedButtonForm::updateTypeSettings public function Ajax callback to update the form fields which depend on embed type.
EmbedButtonForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
EmbedButtonForm::__construct public function Constructs a new EmbedButtonForm.
EntityForm::$entity protected property The entity being used by this form. 7
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::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.