You are here

function ajax_form_entity_entity_view in Ajax form entity 8

Implements hook_entity_view().

File

./ajax_form_entity.module, line 213
Contain ajax form entity module.

Code

function ajax_form_entity_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $entity_type = $entity
    ->getEntityTypeId();
  $bundle = $entity
    ->bundle();
  $entity_id = $entity
    ->id();
  $config_ajax_form_entity = \Drupal::config('ajax_form_entity.settings');
  $confs = $config_ajax_form_entity
    ->get('content');

  // Add AJAX edit link.
  if (isset($confs[$entity_type][$bundle]['activate']) && $confs[$entity_type][$bundle]['activate'] && $display
    ->getComponent('ajax_form_entity_edit_link') && $entity
    ->access('edit')) {

    // Popin edit mode.
    $popin = $confs[$entity_type][$bundle]['popin'];

    // Build the AJAX link.
    $build['ajax_form_entity_edit_link'] = [
      '#theme' => 'links',
      '#weight' => -10,
      '#links' => [
        'ajax_edit_link' => [
          'title' => t('Edit'),
          'url' => Url::fromRoute('ajax_form_entity.ajaxform', [
            'entity_type' => $entity_type,
            'id' => $entity_id,
            'popin' => $popin,
            'view_mode' => $view_mode,
          ]),
          'attributes' => [
            'class' => [
              'use-ajax',
            ],
          ],
        ],
      ],
    ];

    // Ajax popin mode.
    // @todo : handle better dimensions of the dialog.
    if ($popin) {
      $build['ajax_form_entity_edit_link']['#links']['ajax_edit_link']['attributes']['data-dialog-type'] = 'modal';
      $build['ajax_form_entity_edit_link']['#links']['ajax_edit_link']['attributes']['data-dialog-options'] = json_encode([
        'width' => 1000,
        'height' => 700,
      ]);
      $build['ajax_form_entity_edit_link']['#attached']['library'] = [
        'core/drupal.ajax',
        'core/drupal.dialog',
      ];
    }

    // Add AJAX class for replacement.
    $build['#attributes']['class'][] = 'ajax-form-entity-view-' . $entity_type . '-' . $entity_id;
  }

  // Edit form inside the content.
  if (isset($confs[$entity_type][$bundle]['activate']) && $confs[$entity_type][$bundle]['activate'] && $display
    ->getComponent('ajax_form_entity_form') && $entity
    ->access('edit')) {
    $build['ajax_form_entity_form'] = \Drupal::service('entity.form_builder')
      ->getForm($entity);
  }
}