You are here

class JsonapiResourceConfigForm in JSON:API Extras 8

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

Base form for jsonapi_resource_config.

Hierarchy

Expanded class hierarchy of JsonapiResourceConfigForm

File

src/Form/JsonapiResourceConfigForm.php, line 24

Namespace

Drupal\jsonapi_extras\Form
View source
class JsonapiResourceConfigForm extends EntityForm {

  /**
   * The bundle information service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $bundleInfo;

  /**
   * The JSON API resource type repository.
   *
   * @var \Drupal\jsonapi\ResourceType\ResourceTypeRepository
   */
  protected $resourceTypeRepository;

  /**
   * The field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManager
   */
  protected $fieldManager;

  /**
   * The entity type repository.
   *
   * @var \Drupal\Core\Entity\EntityTypeRepositoryInterface
   */
  protected $entityTypeRepository;

  /**
   * The field enhancer manager.
   *
   * @var \Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerManager
   */
  protected $enhancerManager;

  /**
   * The JSON API extras config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * The current route match.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * The typed config manager.
   *
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
   */
  protected $typedConfigManager;

  /**
   * JsonapiResourceConfigForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
   *   Bundle information service.
   * @param \Drupal\jsonapi\ResourceType\ResourceTypeRepository $resource_type_repository
   *   The JSON API resource type repository.
   * @param \Drupal\Core\Entity\EntityFieldManager $field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Entity\EntityTypeRepositoryInterface $entity_type_repository
   *   The entity type repository.
   * @param \Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerManager $enhancer_manager
   *   The plugin manager for the resource field enhancer.
   * @param \Drupal\Core\Config\ImmutableConfig $config
   *   The config instance.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The HTTP request.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager
   *   The typed config manager.
   */
  public function __construct(EntityTypeBundleInfoInterface $bundle_info, ResourceTypeRepository $resource_type_repository, EntityFieldManager $field_manager, EntityTypeRepositoryInterface $entity_type_repository, ResourceFieldEnhancerManager $enhancer_manager, ImmutableConfig $config, Request $request, TypedConfigManagerInterface $typed_config_manager) {
    $this->bundleInfo = $bundle_info;
    $this->resourceTypeRepository = $resource_type_repository;
    $this->fieldManager = $field_manager;
    $this->entityTypeRepository = $entity_type_repository;
    $this->enhancerManager = $enhancer_manager;
    $this->config = $config;
    $this->request = $request;
    $this->typedConfigManager = $typed_config_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.bundle.info'), $container
      ->get('jsonapi.resource_type.repository'), $container
      ->get('entity_field.manager'), $container
      ->get('entity_type.repository'), $container
      ->get('plugin.manager.resource_field_enhancer'), $container
      ->get('config.factory')
      ->get('jsonapi_extras.settings'), $container
      ->get('request_stack')
      ->getCurrentRequest(), $container
      ->get('config.typed'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    // Disable caching on this form.
    $form_state
      ->setCached(FALSE);
    $entity_type_id = $this->request
      ->get('entity_type_id');
    $bundle = $this->request
      ->get('bundle');

    /** @var \Drupal\jsonapi_extras\Entity\JsonapiResourceConfig $entity */
    $entity = $this
      ->getEntity();
    $resource_id = $entity
      ->get('id');

    // If we are editing an entity we don't want the Entity Type and Bundle
    // picker, that info is locked.
    if (!$entity_type_id || !$bundle) {
      if (!$resource_id) {

        // We can't build the form without an entity type and bundle.
        throw new \InvalidArgumentException('Unable to load entity type or bundle for the overrides form.');
      }
      list($entity_type_id, $bundle) = explode('--', $resource_id);
      $form['#title'] = $this
        ->t('Edit %label resource config', [
        '%label' => $resource_id,
      ]);
    }
    if ($entity_type_id && ($resource_type = $this->resourceTypeRepository
      ->get($entity_type_id, $bundle))) {

      // Get the JSON API resource type.
      $resource_config_id = sprintf('%s--%s', $entity_type_id, $bundle);
      $existing_entity = $this->entityTypeManager
        ->getStorage('jsonapi_resource_config')
        ->load($resource_config_id);
      if ($existing_entity && $entity
        ->isNew()) {
        drupal_set_message($this
          ->t('This override already exists, please edit it instead.'));
        return $form;
      }
      $form['bundle_wrapper']['fields_wrapper'] = $this
        ->buildOverridesForm($resource_type, $entity);
      $form['id'] = [
        '#type' => 'hidden',
        '#value' => sprintf('%s--%s', $entity_type_id, $bundle),
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!method_exists($this->typedConfigManager, 'createFromNameAndData')) {

      // Versions of Drupal before 8.4 have poor support for constraints. In
      // those scenarios we don't validate the form submission.
      return;
    }
    $typed_config = $this->typedConfigManager
      ->createFromNameAndData($this->entity
      ->id(), $this->entity
      ->toArray());
    $constraints = $typed_config
      ->validate();

    /** @var \Symfony\Component\Validator\ConstraintViolation $violation */
    foreach ($constraints as $violation) {
      $form_path = str_replace('.', '][', $violation
        ->getPropertyPath());
      $form_state
        ->setErrorByName($form_path, $violation
        ->getMessage());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $resource_config = $this->entity;
    $status = $resource_config
      ->save();
    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this
          ->t('Created the %label JSON API Resource overwrites.', [
          '%label' => $resource_config
            ->label(),
        ]));
        break;
      default:
        drupal_set_message($this
          ->t('Saved the %label JSON API Resource overwrites.', [
          '%label' => $resource_config
            ->label(),
        ]));
    }
    $form_state
      ->setRedirectUrl($resource_config
      ->urlInfo('collection'));
  }

  /**
   * Builds the part of the form that contains the overrides.
   *
   * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
   *   The resource type being overridden.
   * @param \Drupal\jsonapi_extras\Entity\JsonapiResourceConfig $entity
   *   The configuration entity backing this form.
   *
   * @return array
   *   The partial form.
   */
  protected function buildOverridesForm(ResourceType $resource_type, JsonapiResourceConfig $entity) {
    $entity_type_id = $resource_type
      ->getEntityTypeId();
    $entity_type = $this->entityTypeManager
      ->getDefinition($entity_type_id);
    $bundle = $resource_type
      ->getBundle();
    if ($entity_type instanceof ContentEntityTypeInterface) {
      $field_names = array_map(function (FieldDefinitionInterface $field_definition) {
        return $field_definition
          ->getName();
      }, $this->fieldManager
        ->getFieldDefinitions($entity_type_id, $bundle));
    }
    else {
      $field_names = array_keys($entity_type
        ->getPropertiesToExport());
      array_unshift($field_names, $entity_type
        ->getKey('id'));
    }
    $overrides_form['overrides']['entity'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Entity'),
      '#description' => $this
        ->t('Override configuration for the resource entity.'),
      '#open' => !$entity
        ->get('resourceType') || !$entity
        ->get('path'),
    ];
    $overrides_form['overrides']['entity']['disabled'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Disabled'),
      '#description' => $this
        ->t('Check this if you want to disable this resource. Disabling a resource can have unexpected results when following relationships belonging to that resource.'),
      '#default_value' => $entity
        ->get('disabled'),
    ];
    $resource_type_name = $entity
      ->get('resourceType');
    if (!$resource_type_name) {
      $resource_type_name = sprintf('%s--%s', $entity_type_id, $bundle);
    }
    $overrides_form['overrides']['entity']['resourceType'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Resource Type'),
      '#description' => $this
        ->t('Overrides the type of the resource. Example: Change "node--article" to "articles".'),
      '#default_value' => $resource_type_name,
      '#states' => [
        'visible' => [
          ':input[name="disabled"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $path = $entity
      ->get('path');
    if (!$path) {
      $path = sprintf('%s/%s', $entity_type_id, $bundle);
    }
    $prefix = $this->config
      ->get('path_prefix');
    $overrides_form['overrides']['entity']['path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Resource Path'),
      '#field_prefix' => sprintf('/%s/', $prefix),
      '#description' => $this
        ->t('Overrides the path of the resource. Example: Use "articles" to change "/@prefix/node/article" to "/@prefix/articles".', [
        '@prefix' => $prefix,
      ]),
      '#default_value' => $path,
      '#required' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="disabled"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $overrides_form['overrides']['fields'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Fields'),
      '#open' => TRUE,
    ];
    $markup = '';
    $markup .= '<dl>';
    $markup .= '<dt>' . $this
      ->t('Disabled') . '</dt>';
    $markup .= '<dd>' . $this
      ->t('Check this if you want to disable this field completely. Disabling required fields will cause problems when writing to the resource.') . '</dd>';
    $markup .= '<dt>' . $this
      ->t('Alias') . '</dt>';
    $markup .= '<dd>' . $this
      ->t('Overrides the field name with a custom name. Example: Change "field_tags" to "tags".') . '</dd>';
    $markup .= '<dt>' . $this
      ->t('Enhancer') . '</dt>';
    $markup .= '<dd>' . $this
      ->t('Select an enhancer to manipulate the public output coming in and out.') . '</dd>';
    $markup .= '</dl>';
    $overrides_form['overrides']['fields']['info'] = [
      '#markup' => $markup,
    ];
    $overrides_form['overrides']['fields']['resourceFields'] = [
      '#type' => 'table',
      '#header' => [
        'disabled' => $this
          ->t('Disabled'),
        'fieldName' => $this
          ->t('Field name'),
        'publicName' => $this
          ->t('Alias'),
        'enhancer' => $this
          ->t('Enhancer'),
      ],
      '#empty' => $this
        ->t('No fields available.'),
      '#states' => [
        'visible' => [
          ':input[name="disabled"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    foreach ($field_names as $field_name) {
      $overrides_form['overrides']['fields']['resourceFields'][$field_name] = $this
        ->buildOverridesField($field_name, $entity);
    }
    return $overrides_form;
  }

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

    /** @var \Drupal\jsonapi_extras\Entity\JsonapiResourceConfig $entity */
    $entity = parent::buildEntity($form, $form_state);

    // Trim slashes from path.
    $path = trim($form_state
      ->getValue('path'), '/');
    if (strlen($path) > 0) {
      $entity
        ->set('path', $path);
    }
    return $entity;
  }

  /**
   * Builds the part of the form that overrides the field.
   *
   * @param string $field_name
   *   The field name of the field being overridden.
   * @param \Drupal\jsonapi_extras\Entity\JsonapiResourceConfig $entity
   *   The config entity backed by this form.
   *
   * @return array
   *   The partial form.
   */
  protected function buildOverridesField($field_name, JsonapiResourceConfig $entity) {
    $resource_fields = array_filter($entity
      ->get('resourceFields'), function (array $resource_field) use ($field_name) {
      return $resource_field['fieldName'] == $field_name;
    });
    $resource_field = array_shift($resource_fields);
    $overrides_form = [];
    $overrides_form['disabled'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Disabled'),
      '#title_display' => 'invisible',
      '#default_value' => $resource_field['disabled'],
    ];
    $overrides_form['fieldName'] = [
      '#type' => 'hidden',
      '#value' => $field_name,
      '#prefix' => $field_name,
    ];
    $overrides_form['publicName'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Override Public Name'),
      '#title_display' => 'hidden',
      '#default_value' => empty($resource_field['publicName']) ? $field_name : $resource_field['publicName'],
      '#states' => [
        'visible' => [
          ':input[name="resourceFields[' . $field_name . '][disabled]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];

    // Build the select field for the list of enhancers.
    $overrides_form['enhancer'] = [
      '#type' => 'fieldgroup',
      '#states' => [
        'visible' => [
          ':input[name="resourceFields[' . $field_name . '][disabled]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $options = array_reduce($this->enhancerManager
      ->getDefinitions(), function (array $carry, array $definition) {
      $carry[$definition['id']] = $definition['label'];
      return $carry;
    }, [
      '' => $this
        ->t('- Select -'),
    ]);
    $id = empty($resource_field['enhancer']['id']) ? '' : $resource_field['enhancer']['id'];
    $overrides_form['enhancer']['id'] = [
      '#type' => 'select',
      '#options' => $options,
      '#ajax' => [
        'callback' => '::getEnhancerSettings',
        'wrapper' => $field_name . '-settings-wrapper',
      ],
      '#default_value' => $id,
    ];
    $overrides_form['enhancer']['settings'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => $field_name . '-settings-wrapper',
      ],
    ];
    if (!empty($resource_field['enhancer']['id'])) {

      /** @var \Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerInterface $enhancer */
      $enhancer = $this->enhancerManager
        ->createInstance($resource_field['enhancer']['id'], []);
      $overrides_form['enhancer']['settings'] += $enhancer
        ->getSettingsForm($resource_field);
    }
    return $overrides_form;
  }

  /**
   * AJAX callback to get the form settings for the enhancer for a field.
   *
   * @param array $form
   *   The reference to the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return mixed
   *   The specific form sub-tree in the form.
   */
  public static function getEnhancerSettings(array &$form, FormStateInterface $form_state) {

    // Find what is the field name that triggered the AJAX request.
    $user_input = $form_state
      ->getUserInput();
    $parts = explode('[', $user_input['_triggering_element_name']);
    $field_name = rtrim($parts[1], ']');

    // Now return the sub-tree for the settings on the enhancer plugin.
    return $form['bundle_wrapper']['fields_wrapper']['overrides']['fields']['resourceFields'][$field_name]['enhancer']['settings'];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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.
JsonapiResourceConfigForm::$bundleInfo protected property The bundle information service.
JsonapiResourceConfigForm::$config protected property The JSON API extras config.
JsonapiResourceConfigForm::$enhancerManager protected property The field enhancer manager.
JsonapiResourceConfigForm::$entityTypeRepository protected property The entity type repository.
JsonapiResourceConfigForm::$fieldManager protected property The field manager.
JsonapiResourceConfigForm::$request protected property The current route match.
JsonapiResourceConfigForm::$resourceTypeRepository protected property The JSON API resource type repository.
JsonapiResourceConfigForm::$typedConfigManager protected property The typed config manager.
JsonapiResourceConfigForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity
JsonapiResourceConfigForm::buildOverridesField protected function Builds the part of the form that overrides the field.
JsonapiResourceConfigForm::buildOverridesForm protected function Builds the part of the form that contains the overrides.
JsonapiResourceConfigForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
JsonapiResourceConfigForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
JsonapiResourceConfigForm::getEnhancerSettings public static function AJAX callback to get the form settings for the enhancer for a field.
JsonapiResourceConfigForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
JsonapiResourceConfigForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
JsonapiResourceConfigForm::__construct public function JsonapiResourceConfigForm constructor.
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.