You are here

class InsertComponentForm in Layout Paragraphs 2.0.x

Class InsertComponentForm.

Builds the form for inserting a new component.

Hierarchy

Expanded class hierarchy of InsertComponentForm

File

src/Form/InsertComponentForm.php, line 21

Namespace

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

  /**
   * DOM element selector.
   *
   * @var string
   */
  protected $domSelector;

  /**
   * The jQuery insertion method to use for adding the new component.
   *
   * Must be "before", "after", "prepend", or "append.".
   *
   * @var string
   */
  protected $method = 'prepend';

  /**
   * The uuid of the parent component / paragraph.
   *
   * @var string
   */
  protected $parentUuid;

  /**
   * The region this component will be inserted into.
   *
   * @var string
   */
  protected $region;

  /**
   * Where to place the new component in relation to sibling.
   *
   * @var string
   *   "before" or "after"
   */
  protected $placement;

  /**
   * The sibling component's uuid.
   *
   * @var string
   *   The sibling component's uuid.
   */
  protected $siblingUuid;

  /**
   * {@inheritDoc}
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   * @param \Drupal\layout_paragraphs\LayoutParagraphsLayout $layout_paragraphs_layout
   *   The layout paragraphs layout object.
   * @param \Drupal\paragraphs\Entity\ParagraphsType $paragraph_type
   *   The paragraph type.
   * @param string $parent_uuid
   *   The parent component's uuid.
   * @param string $region
   *   The region to insert the new component into.
   * @param string $sibling_uuid
   *   The uuid of the sibling component.
   * @param string $placement
   *   Where to place the new component - either "before" or "after".
   */
  public function buildForm(array $form, FormStateInterface $form_state, LayoutParagraphsLayout $layout_paragraphs_layout = NULL, ParagraphsType $paragraph_type = NULL, string $parent_uuid = NULL, string $region = NULL, string $sibling_uuid = NULL, string $placement = NULL) {
    $this
      ->setLayoutParagraphsLayout($layout_paragraphs_layout);
    $this->paragraph = $this
      ->newParagraph($paragraph_type);
    $this->parentUuid = $parent_uuid;
    $this->region = $region;
    $this->siblingUuid = $sibling_uuid;
    $this->placement = $placement;
    if ($this->siblingUuid && $this->placement) {
      $this->domSelector = '[data-uuid="' . $sibling_uuid . '"]';
      $this->method = $placement;
    }
    elseif ($this->parentUuid && $this->region) {
      $this->domSelector = '[data-region-uuid="' . $parent_uuid . '-' . $region . '"]';
    }
    else {
      $this->domSelector = '[data-lpb-id="' . $this->layoutParagraphsLayout
        ->id() . '"]';
    }
    return $this
      ->buildComponentForm($form, $form_state);
  }

  /**
   * Create the form title.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   *   The form title.
   */
  protected function formTitle() {
    return $this
      ->t('Create new @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);
    switch ($this->method) {
      case 'before':
        $response
          ->addCommand(new BeforeCommand($this->domSelector, $rendered_item));
        break;
      case 'after':
        $response
          ->addCommand(new AfterCommand($this->domSelector, $rendered_item));
        break;
      case 'append':
        $response
          ->addCommand(new AppendCommand($this->domSelector, $rendered_item));
        break;
      case 'prepend':
        $response
          ->addCommand(new PrependCommand($this->domSelector, $rendered_item));
        break;
    }
    $response
      ->addCommand(new LayoutParagraphsEventCommand($this->layoutParagraphsLayout, $uuid, 'component:insert'));
    return $response;
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $this
      ->insertComponent();
    $this->tempstore
      ->set($this->layoutParagraphsLayout);
  }

  /**
   * Inserts the new component into the layout.
   *
   * Determines the correct method based on provided values.
   *
   * - If parent uuid and region are provided, new component
   *   is added to the specified region within the specified parent.
   * - If sibling uuid and placement are provided, the new component
   *   is added before or after the existing sibling.
   * - If no parameters are added, the new component is simply added
   *   to the layout at the root level.
   *
   * @return $this
   */
  protected function insertComponent() {
    if ($this->parentUuid && $this->region) {
      $this->layoutParagraphsLayout
        ->insertIntoRegion($this->parentUuid, $this->region, $this->paragraph);
    }
    elseif ($this->siblingUuid && $this->placement) {
      switch ($this->placement) {
        case 'before':
          $this->layoutParagraphsLayout
            ->insertBeforeComponent($this->siblingUuid, $this->paragraph);
          break;
        case 'after':
          $this->layoutParagraphsLayout
            ->insertAfterComponent($this->siblingUuid, $this->paragraph);
          break;
      }
    }
    else {
      $this->layoutParagraphsLayout
        ->appendComponent($this->paragraph);
    }
    return $this;
  }

  /**
   * Creates a new, empty paragraph empty of the provided type.
   *
   * @param \Drupal\paragraphs\ParagraphsTypeInterface $paragraph_type
   *   The paragraph type.
   *
   * @return \Drupal\paragraphs\ParagraphInterface
   *   The new paragraph.
   */
  protected function newParagraph(ParagraphsTypeInterface $paragraph_type) {
    $entity_type = $this->entityTypeManager
      ->getDefinition('paragraph');
    $bundle_key = $entity_type
      ->getKey('bundle');

    /** @var \Drupal\paragraphs\ParagraphInterface $paragraph_entity */
    $paragraph = $this->entityTypeManager
      ->getStorage('paragraph')
      ->create([
      $bundle_key => $paragraph_type
        ->id(),
    ]);
    return $paragraph;
  }

}

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.
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.
InsertComponentForm::$domSelector protected property DOM element selector.
InsertComponentForm::$method protected property The jQuery insertion method to use for adding the new component.
InsertComponentForm::$parentUuid protected property The uuid of the parent component / paragraph.
InsertComponentForm::$placement protected property Where to place the new component in relation to sibling.
InsertComponentForm::$region protected property The region this component will be inserted into.
InsertComponentForm::$siblingUuid protected property The sibling component's uuid.
InsertComponentForm::buildForm public function Overrides FormInterface::buildForm
InsertComponentForm::formTitle protected function Create the form title. Overrides ComponentFormBase::formTitle
InsertComponentForm::insertComponent protected function Inserts the new component into the layout.
InsertComponentForm::newParagraph protected function Creates a new, empty paragraph empty of the provided type.
InsertComponentForm::submitForm public function Saves the paragraph component. Overrides ComponentFormBase::submitForm
InsertComponentForm::successfulAjaxSubmit public function Allows the form to respond to a successful AJAX submission. Overrides AjaxFormHelperTrait::successfulAjaxSubmit
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.