You are here

class ChangeLayoutForm in Display Suite 8.4

Same name and namespace in other branches
  1. 8.2 src/Form/ChangeLayoutForm.php \Drupal\ds\Form\ChangeLayoutForm
  2. 8.3 src/Form/ChangeLayoutForm.php \Drupal\ds\Form\ChangeLayoutForm

Provides a configuration form for configurable actions.

Hierarchy

Expanded class hierarchy of ChangeLayoutForm

1 string reference to 'ChangeLayoutForm'
ds.routing.yml in ./ds.routing.yml
ds.routing.yml

File

src/Form/ChangeLayoutForm.php, line 15

Namespace

Drupal\ds\Form
View source
class ChangeLayoutForm extends FormBase {

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

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * ChangeLayoutForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
   *   The entity field manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, EntityFieldManagerInterface $entityFieldManager) {
    $this->entityTypeManager = $entityTypeManager;
    $this->entityFieldManager = $entityFieldManager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity_type = '', $bundle = '', $display_mode = '', $new_layout = '') {
    $old_layout = NULL;
    $all_layouts = Ds::getLayouts();
    if (!empty($entity_type) && !empty($bundle) && !empty($display_mode)) {

      /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
      $display = $this->entityTypeManager
        ->getStorage('entity_view_display')
        ->load($entity_type . '.' . $bundle . '.' . $display_mode);
      $old_layout = $display
        ->getThirdPartySettings('ds');
    }
    if ($old_layout && isset($all_layouts[$new_layout])) {
      $new_layout_key = $new_layout;
      $new_layout = $all_layouts[$new_layout];
      $old_layout_info = $all_layouts[$old_layout['layout']['id']];
      $form['#entity_type'] = $entity_type;
      $form['#entity_bundle'] = $bundle;
      $form['#mode'] = $display_mode;
      $form['#old_layout'] = $old_layout;
      $form['#old_layout_info'] = $old_layout_info;
      $form['#new_layout'] = $new_layout;
      $form['#new_layout_key'] = $new_layout_key;
      $form['info'] = [
        '#markup' => $this
          ->t('You are changing from @old to @new layout for @bundle in @view_mode view mode.', [
          '@old' => $old_layout_info
            ->getLabel(),
          '@new' => $new_layout
            ->getLabel(),
          '@bundle' => $bundle,
          '@view_mode' => $display_mode,
        ]),
        '#prefix' => "<div class='change-ds-layout-info'>",
        '#suffix' => "</div>",
      ];

      // Old region options.
      $regions = [];
      foreach ($old_layout_info
        ->getRegions() as $key => $info) {
        $regions[$key] = $info['label'];
      }

      // Let other modules alter the regions.
      // For old regions.
      $context = [
        'entity_type' => $entity_type,
        'bundle' => $bundle,
        'view_mode' => $display_mode,
      ];
      $region_info = [
        'region_options' => $regions,
      ];
      \Drupal::moduleHandler()
        ->alter('ds_layout_region', $context, $region_info);
      $regions = $region_info['region_options'];
      $save_regions = [];
      foreach ($regions as $key => $info) {
        $save_regions[$key] = [
          'label' => $info,
        ];
      }
      $form['#old_layout_info']
        ->setRegions($save_regions);

      // For new regions.
      $new_regions = [];
      foreach ($new_layout
        ->getRegions() as $key => $info) {
        $new_regions[$key] = $info['label'];
      }
      $region_info = [
        'region_options' => $new_regions,
      ];
      \Drupal::moduleHandler()
        ->alter('ds_layout_region', $context, $region_info);
      $new_layout
        ->setRegions($region_info['region_options']);

      // Display the region options.
      $selectable_regions = [
        '' => $this
          ->t('- None -'),
      ] + $new_layout
        ->getRegions();
      $form['regions_pre']['#markup'] = '<div class="ds-layout-regions">';
      foreach ($regions as $region => $region_title) {
        $form['region_' . $region] = [
          '#type' => 'container',
        ];
        $form['region_' . $region]['ds_label_' . $region] = [
          '#markup' => 'Fields in <span class="change-ds-layout-old-region"> ' . $region_title . '</span> go into',
        ];
        $form['region_' . $region]['ds_' . $region] = [
          '#type' => 'select',
          '#options' => $layout_options = $selectable_regions,
          '#default_value' => $region,
        ];
      }
      $form['regions_post']['#markup'] = '</div>';

      // Show previews from old and new layouts.
      $form['preview'] = [
        '#type' => 'container',
        '#prefix' => '<div class="ds-layout-preview">',
        '#suffix' => '</div>',
      ];
      $fallback_image = drupal_get_path('module', 'ds') . '/images/preview.png';
      $old_image = $old_layout_info
        ->getIconPath() ?: $fallback_image;
      $new_image = $new_layout
        ->getIconPath() ?: $fallback_image;
      $arrow = drupal_get_path('module', 'ds') . '/images/arrow.png';
      $form['preview']['old_layout'] = [
        '#markup' => '<div class="ds-layout-preview-image"><img src="' . base_path() . $old_image . '"/></div>',
      ];
      $form['preview']['arrow'] = [
        '#markup' => '<div class="ds-layout-preview-arrow"><img src="' . base_path() . $arrow . '"/></div>',
      ];
      $form['preview']['new_layout'] = [
        '#markup' => '<div class="ds-layout-preview-image"><img src="' . base_path() . $new_image . '"/></div>',
      ];
      $form['#attached']['library'][] = 'ds/admin';

      // Submit button.
      $form['actions'] = [
        '#type' => 'actions',
      ];
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Save'),
        '#prefix' => '<div class="ds-layout-change-save">',
        '#suffix' => '</div>',
      ];
    }
    else {
      $form['nothing'] = [
        '#markup' => $this
          ->t('No valid configuration found.'),
      ];
    }
    return $form;
  }

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

    // Prepare some variables.
    $old_layout = $form['#old_layout'];
    $new_layout = $form['#new_layout'];
    $old_layout_info = $form['#old_layout_info'];
    $new_layout_key = $form['#new_layout_key'];
    $entity_type = $form['#entity_type'];
    $bundle = $form['#entity_bundle'];
    $display_mode = $form['#mode'];

    // Create new third party settings.
    $third_party_settings = $old_layout;
    $third_party_settings['layout']['id'] = $new_layout_key;
    $third_party_settings['layout']['library'] = NULL;
    if ($library = $new_layout
      ->getLibrary()) {
      $third_party_settings['layout']['library'] = $library;
    }
    unset($third_party_settings['regions']);

    // Default wrappers.
    $third_party_settings['layout']['settings']['wrappers'] = [];
    foreach ($new_layout
      ->getRegions() as $region_name => $content) {
      $third_party_settings['layout']['settings']['wrappers'][$region_name] = 'div';
    }

    // Map old regions to new ones.
    $fields = [];
    foreach ($old_layout_info
      ->getRegions() as $region => $region_title) {
      $new_region = $form_state
        ->getValue('ds_' . $region);
      if ($new_region != '' && isset($old_layout['regions'][$region])) {
        foreach ($old_layout['regions'][$region] as $field) {
          if (!isset($third_party_settings['regions'][$new_region])) {
            $third_party_settings['regions'][$new_region] = [];
          }
          $third_party_settings['regions'][$new_region][] = $field;
          $fields[$field] = $new_region;
        }
      }
    }

    // Save configuration.

    /* @var $entity_display \Drupal\Core\Entity\Display\EntityDisplayInterface*/
    $entity_display = $this->entityTypeManager
      ->getStorage('entity_view_display')
      ->load($entity_type . '.' . $bundle . '.' . $display_mode);
    foreach (array_keys($third_party_settings) as $key) {
      $entity_display
        ->setThirdPartySetting('ds', $key, $third_party_settings[$key]);
    }

    // Map regions on fields.
    foreach ($entity_display
      ->getComponents() as $name => $options) {
      if (isset($options['region']) && isset($fields[$name])) {
        $options['region'] = $fields[$name];
        $entity_display
          ->setComponent($name, $options);
      }
    }

    // Map field groups, if available.
    $groups = $entity_display
      ->getThirdPartySettings('field_group');
    if (!empty($groups)) {
      foreach (array_keys($groups) as $group_name) {
        $region = 'hidden';
        if (isset($fields[$group_name])) {
          $region = $fields[$group_name];
        }
        $groups[$group_name]['region'] = $region;
        $entity_display
          ->setThirdPartySetting('field_group', $group_name, $groups[$group_name]);
      }
    }

    // Now save.
    $entity_display
      ->save();

    // Clear entity info cache.
    $this->entityFieldManager
      ->clearCachedFieldDefinitions();

    // Show message.
    $this
      ->messenger()
      ->addMessage($this
      ->t('The layout change has been saved.'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ChangeLayoutForm::$entityFieldManager protected property The entity field manager.
ChangeLayoutForm::$entityTypeManager protected property The entity type manager.
ChangeLayoutForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ChangeLayoutForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ChangeLayoutForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ChangeLayoutForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ChangeLayoutForm::__construct public function ChangeLayoutForm constructor.
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.
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.