You are here

class EditComponentForm in Layout Paragraphs 2.0.x

Class LayoutParagraphsComponentEditForm.

Builds the edit form for an existing layout paragraphs paragraph entity.

Hierarchy

Expanded class hierarchy of EditComponentForm

1 string reference to 'EditComponentForm'
layout_paragraphs.routing.yml in ./layout_paragraphs.routing.yml
layout_paragraphs.routing.yml

File

src/Form/EditComponentForm.php, line 16

Namespace

Drupal\layout_paragraphs\Form
View source
class EditComponentForm extends ComponentFormBase {

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, LayoutParagraphsLayout $layout_paragraphs_layout = NULL, string $component_uuid = NULL) {
    $this
      ->setLayoutParagraphsLayout($layout_paragraphs_layout);
    $this->paragraph = $this->layoutParagraphsLayout
      ->getComponentByUuid($component_uuid)
      ->getEntity();
    $form = $this
      ->buildComponentForm($form, $form_state);
    if ($selected_layout = $form_state
      ->getValue([
      'layout_paragraphs',
      'layout',
    ])) {
      $section = $this->layoutParagraphsLayout
        ->getLayoutSection($this->paragraph);
      if ($section && $selected_layout != $section
        ->getLayoutId()) {
        $form['layout_paragraphs']['move_items'] = [
          '#old_layout' => $section
            ->getLayoutId(),
          '#new_layout' => $selected_layout,
          '#weight' => 5,
          '#process' => [
            [
              $this,
              'orphanedItemsElement',
            ],
          ],
        ];
      }
    }
    return $form;
  }

  /**
   * Create the form title.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   *   The form title.
   */
  protected function formTitle() {
    return $this
      ->t('Edit @type', [
      '@type' => $this->paragraph
        ->getParagraphType()
        ->label(),
    ]);
  }

  /**
   * {@inheritDoc}
   */
  public function successfulAjaxSubmit(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $this
      ->ajaxCloseForm($response);
    if ($this
      ->needsRefresh()) {
      return $this
        ->refreshLayout($response);
    }
    $uuid = $this->paragraph
      ->uuid();
    $rendered_item = $this
      ->renderParagraph($uuid);
    $response
      ->addCommand(new ReplaceCommand("[data-uuid={$uuid}]", $rendered_item));
    $response
      ->addCommand(new LayoutParagraphsEventCommand($this->layoutParagraphsLayout, $uuid, 'component:update'));
    return $response;
  }

  /**
   * Form #process callback.
   *
   * Builds the orphaned items form element for when a new layout's
   * regions do not match the previous one's.
   *
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   * @param array $form
   *   The complete form.
   *
   * @return array
   *   The form element.
   */
  public function orphanedItemsElement(array $element, FormStateInterface $form_state, array &$form) {
    $old_regions = $this
      ->getLayoutRegionNames($element['#old_layout']);
    $new_regions = $this
      ->getLayoutRegionNames($element['#new_layout']);
    $section = $this->layoutParagraphsLayout
      ->getLayoutSection($this->paragraph);
    $has_orphans = FALSE;
    foreach ($old_regions as $region_name => $region) {
      if ($section
        ->getComponentsForRegion($region_name) && empty($new_regions[$region_name])) {
        $has_orphans = TRUE;
        $element[$region_name] = [
          '#type' => 'select',
          '#options' => $new_regions,
          '#wrapper_attributes' => [
            'class' => [
              'container-inline',
            ],
          ],
          '#title' => $this
            ->t('Move items from "@region" to', [
            '@region' => $region,
          ]),
        ];
      }
    }
    if ($has_orphans) {
      $element += [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Move Orphaned Items'),
        '#description' => $this
          ->t('Choose where to move items for missing regions.'),
      ];
    }
    return $element;
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $this->layoutParagraphsLayout
      ->setComponent($this->paragraph);
    if ($form_state
      ->getValue([
      'layout_paragraphs',
      'move_items',
    ])) {
      $this
        ->moveItemsSubmit($form, $form_state);
    }
    $this->tempstore
      ->set($this->layoutParagraphsLayout);
  }

  /**
   * Moves items from removed regions into designated new ones.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   */
  public function moveItemsSubmit(array &$form, FormStateInterface $form_state) {
    if ($move_items = $form_state
      ->getValue([
      'layout_paragraphs',
      'move_items',
    ])) {
      $section = $this->layoutParagraphsLayout
        ->getLayoutSection($this->paragraph);
      foreach ($move_items as $source => $destination) {
        $components = $section
          ->getComponentsForRegion($source);
        foreach ($components as $component) {
          $component
            ->setSettings([
            'region' => $destination,
          ]);
          $this->layoutParagraphsLayout
            ->setComponent($component
            ->getEntity());
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxFormHelperTrait::ajaxSubmit public function Submit form dialog #ajax callback.
AjaxHelperTrait::getRequestWrapperFormat protected function Gets the wrapper format of the current request.
AjaxHelperTrait::isAjax protected function Determines if the current request is via AJAX.
ComponentFormBase::$entityRepository protected property The entity repository service.
ComponentFormBase::$entityTypeManager protected property The entity type manager service.
ComponentFormBase::$layoutPluginManager protected property The layout plugin manager service.
ComponentFormBase::$moduleHandler protected property The module handler service.
ComponentFormBase::$paragraph protected property The paragraph.
ComponentFormBase::$paragraphType protected property The paragraph type.
ComponentFormBase::$tempstore protected property The tempstore service.
ComponentFormBase::access public function Access check.
ComponentFormBase::afterBuild public function After build callback fixes issues with data-drupal-selector.
ComponentFormBase::ajaxCallback public function Ajax form callback.
ComponentFormBase::ajaxCloseForm protected function Closes the form with ajax.
ComponentFormBase::behaviorPluginsForm public function Form #process callback.
ComponentFormBase::buildComponentForm protected function Builds a component (paragraph) edit form.
ComponentFormBase::buildParagraphComponent protected function Builds the paragraph component using submitted form values.
ComponentFormBase::cancel public function Form #ajax callback.
ComponentFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ComponentFormBase::getEnabledBehaviorPlugins protected function Returns an array of enabled behavior plugins excluding Layout Paragraphs.
ComponentFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ComponentFormBase::getLayoutRegionNames protected function Returns an array of region names for a given layout.
ComponentFormBase::getLayoutRegions protected function Returns an array of regions for a given layout.
ComponentFormBase::initFormLangcodes protected function Initializes form language code values.
ComponentFormBase::layoutParagraphsBehaviorForm public function Form #process callback.
ComponentFormBase::renderParagraph protected function Renders a single Layout Paragraphs Layout paragraph entity.
ComponentFormBase::validateForm public function Validate the component form. Overrides FormBase::validateForm
ComponentFormBase::__construct public function
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
DialogHelperTrait::closeDialogCommand protected function Returns a CloseDialogComand with the correct selector.
DialogHelperTrait::dialogId protected function Generates a dialog id for a given layout.
DialogHelperTrait::dialogSelector protected function Generates a dialog selector for a given layout.
DialogHelperTrait::dialogSettings protected function Returns an array of dialog settings for modal edit forms.
EditComponentForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
EditComponentForm::formTitle protected function Create the form title. Overrides ComponentFormBase::formTitle
EditComponentForm::moveItemsSubmit public function Moves items from removed regions into designated new ones.
EditComponentForm::orphanedItemsElement public function Form #process callback.
EditComponentForm::submitForm public function Saves the paragraph component. Overrides ComponentFormBase::submitForm
EditComponentForm::successfulAjaxSubmit public function Allows the form to respond to a successful AJAX submission. Overrides AjaxFormHelperTrait::successfulAjaxSubmit
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
LayoutParagraphsLayoutRefreshTrait::$eventDispatcher protected property The event dispatcher service. 1
LayoutParagraphsLayoutRefreshTrait::$layoutParagraphsLayout protected property The layout paragraphs layout object.
LayoutParagraphsLayoutRefreshTrait::$originalLayoutParagraphsLayout protected property The original paragraphs layout object.
LayoutParagraphsLayoutRefreshTrait::eventDispatcher protected function Returns the event dispatcher service. 1
LayoutParagraphsLayoutRefreshTrait::needsRefresh protected function Returns TRUE if the layout needs to be refreshed.
LayoutParagraphsLayoutRefreshTrait::refreshLayout protected function Decorates an ajax response with a command to refresh an entire layout.
LayoutParagraphsLayoutRefreshTrait::renderLayout protected function Renders the layout builder UI render array.
LayoutParagraphsLayoutRefreshTrait::setLayoutParagraphsLayout protected function Setter for layoutParagraphsLayout property.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.