You are here

class AjaxController in Paragraphs table 8

Returns responses for paragraphs item routes.

Hierarchy

Expanded class hierarchy of AjaxController

File

src/Controller/AjaxController.php, line 14

Namespace

Drupal\paragraphs_table\Controller
View source
class AjaxController extends ControllerBase {

  /**
   * The entity render build.
   *
   * @var object
   */
  protected $renderBuild;

  /**
   * The field definition.
   *
   * @var object
   */
  protected $fieldsDefinition;

  /**
   * Return output JSON object value.
   */
  public function json($field_name, $host_type, $host_id, $typeData = FALSE) {
    $message = [];
    $entity = $this
      ->entityTypeManager()
      ->getStorage($host_type)
      ->load($host_id);
    if (empty($entity)) {
      $message[] = $this
        ->t("%type %id doesn't exist", [
        "%type" => $host_type,
        "%id" => $host_id,
      ]);
    }
    $paragraph_field = $entity
      ->hasField($field_name) ? $entity->{$field_name} : FALSE;
    if (empty($paragraph_field)) {
      $message[] = $this
        ->t("%field that does not exist on entity type %type", [
        "%field" => $field_name,
        "%type" => $host_type,
      ]);
    }
    if ($paragraph_field && ($paragraph_field_items = $paragraph_field
      ->referencedEntities())) {
      $setting = $this
        ->getFieldSetting($entity, $field_name);
      $hasPermission = ParagraphsTableFormatter::checkPermissionOperation($entity, $field_name);
      if ($hasPermission) {
        $setting['show_operation'] = TRUE;
      }
      $components = $this
        ->getComponents($paragraph_field, $setting['view_mode']);
      $typeLabel = \Drupal::request()
        ->get('type');
      if (empty($typeLabel)) {
        $typeLabel = 'data';
      }
      switch ($typeData) {
        case 'table':
          $data = $this
            ->getTable($paragraph_field_items, $components, $setting);
          break;
        case 'data':
          $data = $this
            ->getData($paragraph_field_items, $components, $setting);
          break;
        default:
          $data = [
            $typeLabel => $this
              ->getResults($paragraph_field_items, $components, $setting),
          ];
          break;
      }
      return new JsonResponse($data);
    }
    else {
      $message[] = $this
        ->t("%field is not paragraphs", [
        "%field" => $field_name,
      ]);
    }
    return new JsonResponse([
      'error' => $message,
    ]);
  }

  /**
   * Return output JSON data value.
   */
  public function jsondata($field_name, $host_type, $host_id) {
    return $this
      ->json($field_name, $host_type, $host_id, 'data');
  }

  /**
   * Return html render field paragraphs.
   */
  public function ajax($field_name, $host_type, $host_id) {
    return $this
      ->json($field_name, $host_type, $host_id, 'table');
  }

  /**
   * {@inheritdoc}
   */
  protected function getFieldSetting($entity, $field_name) {
    $bundle = $entity
      ->bundle();
    $repository = \Drupal::service('entity_display.repository');
    $viewDisplay = $repository
      ->getViewDisplay($entity
      ->getEntityTypeId(), $bundle, 'default');
    $fieldComponent = $viewDisplay
      ->getComponent($field_name);
    return $fieldComponent['settings'];
  }

  /**
   * {@inheritdoc}
   */
  protected function getComponents($paragraph_field, $view_mode = 'default') {
    $field_definition = $paragraph_field
      ->getFieldDefinition();
    $targetBundle = array_key_first($field_definition
      ->getSetting("handler_settings")["target_bundles"]);
    $targetType = $field_definition
      ->getSetting('target_type');
    $fieldsDefinitions = $this
      ->entityTypeManager()
      ->getStorage($targetType)
      ->create([
      'type' => $targetBundle,
    ])
      ->getFieldDefinitions();
    $repository = \Drupal::service('entity_display.repository');
    $viewDisplay = $repository
      ->getViewDisplay($targetType, $targetBundle, $view_mode);
    $components = $viewDisplay
      ->getComponents();
    uasort($components, 'Drupal\\Component\\Utility\\SortArray::sortByWeightElement');
    foreach ($components as $field_name => $component) {
      if ($fieldsDefinitions[$field_name] instanceof FieldConfigInterface) {
        $this->fieldsDefinition[$field_name] = $fieldsDefinitions[$field_name];
        $components[$field_name]['title'] = $fieldsDefinitions[$field_name]
          ->getLabel();
      }
    }
    $storage = $this
      ->entityTypeManager()
      ->getStorage('entity_view_display');
    $this->renderBuild = $storage
      ->load(implode('.', [
      $targetType,
      $targetBundle,
      $view_mode,
    ]));
    return $components;
  }

  /**
   * {@inheritdoc}
   */
  public function getResults($entities, $components, $setting = []) {
    $data = FALSE;
    foreach ($entities as $delta => $entity) {
      $table_entity = $this->renderBuild
        ->build($entity);
      $objectData = new \stdClass();
      foreach ($components as $field_name => $field) {
        $table_entity[$field_name]['#label_display'] = 'hidden';
        $value = trim(strip_tags(render($table_entity[$field_name])));
        if (in_array($this->fieldsDefinition[$field_name]
          ->getType(), [
          'integer',
          'list_integer',
          'number_integer',
        ])) {
          $value = (int) $value;
        }
        if (in_array($this->fieldsDefinition[$field_name]
          ->getType(), [
          'boolean',
        ])) {
          $list_value = $table_entity[$field_name]["#items"]
            ->getValue();
          $value = (int) $list_value[0]['value'];
        }
        if (in_array($this->fieldsDefinition[$field_name]
          ->getType(), [
          'decimal',
          'list_decimal',
          'number_decimal',
          'float',
          'list_float',
          'number_float',
        ])) {
          $value = (double) $value;
        }
        if (!is_numeric($value) && empty($value) && !empty($setting["empty_cell_value"])) {
          $value = $setting["empty_cell_value"];
        }
        $objectData->{$field_name} = $value;
      }
      if (!empty($setting['show_operation'])) {
        $parent = $entity
          ->getParentEntity();
        $destination = implode('/', [
          $parent
            ->getEntityTypeId(),
          $parent
            ->id(),
        ]);
        $objectData->operation = $this
          ->paragraphsTableLinksAction($entity
          ->id(), $destination);
      }
      $data[$delta] = $objectData;
    }
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getTable($entities, $components, $setting = []) {
    $data = FALSE;
    foreach ($entities as $delta => $entity) {
      $table_entity = $this->renderBuild
        ->build($entity);
      foreach ($components as $field_name => $field) {
        $table_entity[$field_name]['#label_display'] = 'hidden';
        $value = trim(render($table_entity[$field_name]));
        if (!is_numeric($value) && empty($value) && !empty($setting["empty_cell_value"])) {
          $value = $setting["empty_cell_value"];
        }
        $data[$delta][] = $value;
      }
      if (!empty($setting['show_operation'])) {
        $parent = $entity
          ->getParentEntity();
        $destination = implode('/', [
          $parent
            ->getEntityTypeId(),
          $parent
            ->id(),
        ]);
        $data[$delta]['operation'] = $this
          ->paragraphsTableLinksAction($entity
          ->id(), $destination);
      }
    }
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getData($entities, $components, $setting = []) {
    $data = FALSE;
    $header = [];
    foreach ($components as $field_name => $field) {
      $header[] = $field['title'];
    }
    foreach ($entities as $delta => $entity) {
      $table_entity = $this->renderBuild
        ->build($entity);
      foreach ($components as $field_name => $field) {
        $table_entity[$field_name]['#label_display'] = 'hidden';
        $value = trim(strip_tags(render($table_entity[$field_name])));
        if (in_array($this->fieldsDefinition[$field_name]
          ->getType(), [
          'integer',
          'list_integer',
          'number_integer',
        ])) {
          $value = (int) $value;
        }
        if (in_array($this->fieldsDefinition[$field_name]
          ->getType(), [
          'boolean',
        ])) {
          $list_value = $table_entity[$field_name]["#items"]
            ->getValue();
          $value = (int) $list_value[0]['value'];
        }
        if (in_array($this->fieldsDefinition[$field_name]
          ->getType(), [
          'decimal',
          'list_decimal',
          'number_decimal',
          'float',
          'list_float',
          'number_float',
        ])) {
          $value = (double) $value;
        }
        if (!is_numeric($value) && empty($value) && !empty($setting["empty_cell_value"])) {
          $value = $setting["empty_cell_value"];
        }
        $data[$delta][] = $value;
      }
      if (!empty($setting['show_operation'])) {
        $parent = $entity
          ->getParentEntity();
        $destination = implode('/', [
          $parent
            ->getEntityTypeId(),
          $parent
            ->id(),
        ]);
        $data[$delta]['operation'] = $this
          ->paragraphsTableLinksAction($entity
          ->id(), $destination);
      }
    }
    array_unshift($data, $header);
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  private function paragraphsTableLinksAction($paragraphsId = FALSE, $destination = '') {
    $route_params = [
      'paragraph' => $paragraphsId,
    ];
    if (!empty($destination)) {
      $route_params['destination'] = $destination;
    }
    $operation = [
      '#type' => 'dropbutton',
      '#links' => [
        'view' => [
          'title' => $this
            ->t('View'),
          'url' => Url::fromRoute('entity.paragraphs_item.canonical', $route_params),
        ],
        'edit' => [
          'title' => $this
            ->t('Edit'),
          'url' => Url::fromRoute('entity.paragraphs_item.edit_form', $route_params),
        ],
        'duplicate' => [
          'title' => $this
            ->t('Duplicate'),
          'url' => Url::fromRoute('entity.paragraphs_item.clone_form', $route_params),
        ],
        'delete' => [
          'title' => $this
            ->t('Remove'),
          'url' => Url::fromRoute('entity.paragraphs_item.delete_form', $route_params),
        ],
      ],
    ];

    // Alter row operation.
    \Drupal::moduleHandler()
      ->alter('paragraphs_table_operations', $operation, $paragraphsId);
    return render($operation);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxController::$fieldsDefinition protected property The field definition.
AjaxController::$renderBuild protected property The entity render build.
AjaxController::ajax public function Return html render field paragraphs.
AjaxController::getComponents protected function
AjaxController::getData public function
AjaxController::getFieldSetting protected function
AjaxController::getResults public function
AjaxController::getTable public function
AjaxController::json public function Return output JSON object value.
AjaxController::jsondata public function Return output JSON data value.
AjaxController::paragraphsTableLinksAction private function
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
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.