You are here

class CorrespondingReferenceForm in Corresponding Entity References 8.4

Form handler for corresponding reference add and edit forms.

Hierarchy

Expanded class hierarchy of CorrespondingReferenceForm

File

src/Form/CorrespondingReferenceForm.php, line 17

Namespace

Drupal\cer\Form
View source
class CorrespondingReferenceForm extends EntityForm {

  /** @var EntityTypeManagerInterface */
  protected $entityTypeManager;

  /** @var  EntityFieldManager */
  protected $fieldManager;

  /**
   * Constructs a CorrespondingReferenceForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Entity\EntityFieldManager $field_manager
   *   The entity field manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManager $field_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->fieldManager = $field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    /** @var EntityTypeManagerInterface $entity_query */
    $entity_type_manager = $container
      ->get('entity_type.manager');

    /** @var EntityFieldManager $field_manager */
    $field_manager = $container
      ->get('entity_field.manager');
    return new static($entity_type_manager, $field_manager);
  }

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

    /** @var CorrespondingReferenceInterface $correspondingReference */
    $correspondingReference = $this->entity;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $correspondingReference
        ->label(),
      '#description' => $this
        ->t("Label for the corresponding reference."),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $correspondingReference
        ->id(),
      '#machine_name' => [
        'exists' => [
          $this,
          'exists',
        ],
      ],
      '#disabled' => !$correspondingReference
        ->isNew(),
    ];
    $form['first_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('First field'),
      '#description' => $this
        ->t('Select the first field.'),
      '#options' => $this
        ->getFieldOptions(),
      '#default_value' => $correspondingReference
        ->getFirstField(),
      '#required' => TRUE,
    ];
    $form['second_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Second field'),
      '#description' => $this
        ->t('Select the corresponding field. It may be the same field.'),
      '#options' => $this
        ->getFieldOptions(),
      '#default_value' => $correspondingReference
        ->getSecondField(),
      '#required' => TRUE,
    ];
    $form['bundles'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Bundles'),
      '#description' => $this
        ->t('Select the bundles which should correspond to one another when they have one of the corresponding fields.'),
      '#options' => $this
        ->getBundleOptions(),
      '#multiple' => TRUE,
      '#default_value' => $this
        ->getBundleValuesForForm($correspondingReference
        ->getBundles()),
    ];
    $form['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enabled'),
      '#description' => $this
        ->t('When enabled, corresponding references will be automatically created upon saving an entity.'),
      '#default_value' => $correspondingReference
        ->isEnabled(),
    ];
    return $form;
  }

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

    /** @var CorrespondingReferenceInterface $correspondingReference */
    $correspondingReference = $this->entity;
    $status = $correspondingReference
      ->save();
    if ($status) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Saved the %label corresponding reference.', [
        '%label' => $correspondingReference
          ->label(),
      ]));
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The %label corresponding reference was not saved.', [
        '%label' => $correspondingReference
          ->label(),
      ]));
    }
    $form_state
      ->setRedirect('entity.corresponding_reference.collection');
  }

  /**
   * Helper function to check whether a corresponding reference configuration entity exists.
   */
  public function exists($id) {
    $entity = $this->entityTypeManager
      ->getStorage('corresponding_reference')
      ->getQuery()
      ->condition('id', $id)
      ->execute();
    return (bool) $entity;
  }

  /**
   * Gets a map of possible reference fields.
   *
   * @return array
   *   The reference field map.
   */
  protected function getReferenceFieldMap() {
    $map = $this->fieldManager
      ->getFieldMapByFieldType('entity_reference');
    return $map;
  }

  /**
   * Gets an array of field options to populate in the form.
   *
   * @return array
   *   An array of field options.
   */
  protected function getFieldOptions() {
    $options = [];
    foreach ($this
      ->getReferenceFieldMap() as $entityType => $entityTypeFields) {
      foreach ($entityTypeFields as $fieldName => $field) {
        if (!preg_match('/^field_.*$/', $fieldName)) {
          continue;
        }
        $options[$fieldName] = $fieldName;
      }
    }
    return $options;
  }

  /**
   * Gets an array of bundle options to populate in the form.
   *
   * @return array
   *   An array of bundle options.
   */
  protected function getBundleOptions() {

    /** @var CorrespondingReferenceInterface $correspondingReference */
    $correspondingReference = $this->entity;
    $correspondingFields = $correspondingReference
      ->getCorrespondingFields();
    $options = [];
    foreach ($this
      ->getReferenceFieldMap() as $entityType => $entityTypeFields) {
      $includeType = FALSE;
      foreach ($entityTypeFields as $fieldName => $field) {
        if (!empty($correspondingFields) && !in_array($fieldName, $correspondingFields)) {
          continue;
        }
        if (!preg_match('/^field_.*$/', $fieldName)) {
          continue;
        }
        $includeType = TRUE;
        foreach ($field['bundles'] as $bundle) {
          $options["{$entityType}:{$bundle}"] = "{$entityType}: {$bundle}";
        }
      }
      if ($includeType) {
        $options["{$entityType}:*"] = "{$entityType}: *";
      }
    }
    ksort($options);
    return $options;
  }

  /**
   * Gets bundle options value in a format for use in the form.
   *
   * @param array|NULL $values
   *   The values to convert.
   *
   * @return array
   *   The converted values.
   */
  protected function getBundleValuesForForm(array $values = NULL) {
    $formValues = [];
    if (!is_null($values)) {
      foreach ($values as $entityType => $bundles) {
        foreach ($bundles as $bundle) {
          $formValues[] = "{$entityType}:{$bundle}";
        }
      }
    }
    return $formValues;
  }

  /**
   * Gets bundle options value in a format for use in the config entity.
   *
   * @param array|NULL $values
   *   The values to convert.
   *
   * @return array
   *   The converted values.
   */
  protected function getBundleValuesForEntity(array $values = NULL) {
    $entityValues = [];
    if (!is_null($values)) {
      foreach ($values as $value) {
        list($entityType, $bundle) = explode(':', $value);
        $entityValues[$entityType][] = $bundle;
      }
    }
    return $entityValues;
  }

  /**
   * Copies form values into the config entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The config entity.
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   */
  protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    if ($this->entity instanceof EntityWithPluginCollectionInterface) {

      // Do not manually update values represented by plugin collections.
      $values = array_diff_key($values, $this->entity
        ->getPluginCollections());
    }

    /** @var CorrespondingReferenceInterface $entity */
    $entity
      ->set('id', $values['id']);
    $entity
      ->set('label', $values['label']);
    $entity
      ->set('first_field', $values['first_field']);
    $entity
      ->set('second_field', $values['second_field']);
    $entity
      ->set('bundles', $this
      ->getBundleValuesForEntity($values['bundles']));
    $entity
      ->set('enabled', $values['enabled']);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CorrespondingReferenceForm::$entityTypeManager protected property @var EntityTypeManagerInterface Overrides EntityForm::$entityTypeManager
CorrespondingReferenceForm::$fieldManager protected property @var EntityFieldManager
CorrespondingReferenceForm::copyFormValuesToEntity protected function Copies form values into the config entity. Overrides EntityForm::copyFormValuesToEntity
CorrespondingReferenceForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
CorrespondingReferenceForm::exists public function Helper function to check whether a corresponding reference configuration entity exists.
CorrespondingReferenceForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
CorrespondingReferenceForm::getBundleOptions protected function Gets an array of bundle options to populate in the form.
CorrespondingReferenceForm::getBundleValuesForEntity protected function Gets bundle options value in a format for use in the config entity.
CorrespondingReferenceForm::getBundleValuesForForm protected function Gets bundle options value in a format for use in the form.
CorrespondingReferenceForm::getFieldOptions protected function Gets an array of field options to populate in the form.
CorrespondingReferenceForm::getReferenceFieldMap protected function Gets a map of possible reference fields.
CorrespondingReferenceForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
CorrespondingReferenceForm::__construct public function Constructs a CorrespondingReferenceForm object.
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::$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::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.