You are here

class ScheduledUpdateTypeForm in Scheduled Updates 8

Class ScheduledUpdateTypeForm.

@package Drupal\scheduled_updates\Form

Hierarchy

Expanded class hierarchy of ScheduledUpdateTypeForm

File

src/Form/ScheduledUpdateTypeForm.php, line 21
Contains \Drupal\scheduled_updates\Form\ScheduledUpdateTypeForm.

Namespace

Drupal\scheduled_updates\Form
View source
class ScheduledUpdateTypeForm extends ScheduledUpdateTypeBaseForm {
  use FieldUtilsTrait;
  use ClassUtilsTrait;

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $this->entity
        ->label(),
      '#description' => $this
        ->t("Label for the Scheduled update type."),
      '#required' => TRUE,
      '#weight' => -110,
    );
    $form['id'] = array(
      '#type' => 'machine_name',
      '#default_value' => $this->entity
        ->id(),
      '#machine_name' => array(
        'exists' => '\\Drupal\\scheduled_updates\\Entity\\ScheduledUpdateType::load',
      ),
      '#disabled' => !$this->entity
        ->isNew(),
      '#weight' => -100,
    );
    $default_type = $this
      ->getCurrentEntityType($form_state);
    $disabled = !$this->entity
      ->isNew();
    $form['update_entity_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Entity Type'),
      '#description' => $this
        ->t('The entity type to update. This <strong>cannot</strong> be changed after this type is created.'),
      '#options' => $this
        ->entityTypeOptions(),
      '#default_value' => $default_type,
      '#required' => TRUE,
      // @todo why doesn't this work?
      '#disabled' => $disabled,
      '#weight' => -90,
    ];

    // @todo Remove when bug is fixed.
    if (!$form['update_entity_type']['#disabled']) {

      // Just to duplicate issues on d.o for now.
      $form['update_entity_type']['#description'] .= '<br /><strong>**KNOWN BUG**</strong> : Ajax error when selecting one entity type and then selecting another: https://www.drupal.org/node/2643934';
    }
    $form['update_entity_type'] += $this
      ->typeDependentAjax();
    $form['field_map'] = $this
      ->createFieldMapElements();

    /* You will need additional form elements for your custom properties. */
    return $form;
  }

  /**
   * Create select element entity type options.
   *
   * @return array
   */
  protected function entityTypeOptions() {
    $options[''] = '';
    foreach ($this->entityTypeManager
      ->getDefinitions() as $entity_id => $entityTypeInterface) {
      if ($entity_id == 'scheduled_update') {

        // Don't allow updating of updates! Inception!
        continue;
      }
      if (is_subclass_of($entityTypeInterface
        ->getClass(), 'Drupal\\Core\\Entity\\ContentEntityInterface')) {
        $options[$entity_id] = $entityTypeInterface
          ->getLabel();
      }
    }
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::doSave($form, $form_state);
    $clone_field = $form_state
      ->getValue('clone_field');
    $multi_field = FALSE;
    if ($clone_field) {
      if ($clone_field != 'multiple-field') {
        $this
          ->cloneSingleField($this->entity
          ->getUpdateEntityType(), $clone_field, $form_state);
      }
      else {
        $multi_field = TRUE;
      }
    }
    drupal_set_message("clone field {$clone_field}, status {$status}");
    switch ($status) {
      case SAVED_NEW:
        if ($multi_field) {
          $this
            ->messenger()
            ->addStatus($this
            ->t('Select fields to add to these updates'));

          // TODO: Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
          // Please confirm that `$entity` is an instance of `Drupal\Core\Entity\EntityInterface`. Only the method name and not the class name was checked for this replacement, so this may be a false positive.
          $form_state
            ->setRedirectUrl($this->entity
            ->toUrl('clone-fields'));
        }
        else {
          $form_state
            ->setRedirectUrl(Url::fromRoute("entity.entity_form_display.scheduled_update.default", array(
            'scheduled_update_type' => $this->entity
              ->id(),
          )));
        }
        break;
      default:
        $this
          ->messenger()
          ->addStatus($this
          ->t('Saved the %label Scheduled update type.', [
          '%label' => $this->entity
            ->label(),
        ]));

        // TODO: Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
        // Please confirm that `$entity` is an instance of `Drupal\Core\Entity\EntityInterface`. Only the method name and not the class name was checked for this replacement, so this may be a false positive.
        $form_state
          ->setRedirectUrl($this->entity
          ->toUrl('collection'));
    }
  }

  /**
   * Create form elements to update field map.
   *
   * @return array
   * @internal param array $form
   * @internal param $scheduled_update_type
   *
   */
  protected function createFieldMapElements() {
    if ($this->entity
      ->isNew()) {
      return [];
    }
    $field_map_help = 'Select the destination fields for this update type.' . ' Not all field have to have destinations if you using them for other purposes.';
    $elements = [
      '#type' => 'details',
      '#title' => 'destination fields',
      '#description' => $this
        ->t($field_map_help),
      '#tree' => TRUE,
    ];
    $source_fields = $this
      ->getSourceFields($this->entity);
    $field_map = $this->entity
      ->getFieldMap();
    foreach ($source_fields as $source_field_id => $source_field) {
      $destination_fields_options = $this
        ->getDestinationFieldsOptions($this->entity
        ->getUpdateEntityType(), $source_field);
      $elements[$source_field_id] = [
        '#type' => 'select',
        '#title' => $source_field
          ->label(),
        '#options' => [
          '' => $this
            ->t("(Not mapped)"),
        ] + $destination_fields_options,
        '#default_value' => isset($field_map[$source_field_id]) ? $field_map[$source_field_id] : '',
      ];
    }
    return $elements;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $runner_settings = $form_state
      ->getValue('update_runner');
    $update_runner = $this
      ->createRunnerInstance($runner_settings, $form_state);
    $update_runner
      ->validateConfigurationForm($form, $form_state);
  }

  /**
   * Overridden to provide multi-field choice.
   *
   * This option will route the user to the clone fields page.
   * @todo should this option always be available?
   *
   * {@inheritdoc}
   */
  protected function createCloneFieldSelect(array $form, FormStateInterface $form_state) {
    $elements = parent::createCloneFieldSelect($form, $form_state);
    if (isset($elements['clone_field']['#options'])) {
      $elements['clone_field']['#options']['multiple-field'] = '(' . $this
        ->t('Create a multiple field update') . ')';
    }
    return $elements;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ClassUtilsTrait::bundleLabel protected function
ClassUtilsTrait::definitionClassImplementsInterface protected function Determines if the class for an entity type definition implements and interface.
ClassUtilsTrait::entityLabel protected function
ClassUtilsTrait::entityTypeManager protected function
ClassUtilsTrait::getEntityOwner protected function Get the entity owner if applicable.
ClassUtilsTrait::getRevisionOwner protected function Get the revision owner for an ContentEntity.
ClassUtilsTrait::implementsInterface protected function Determines if an object or class name implements any interfaces in a list.
ClassUtilsTrait::revisionOwnerInterfaces protected function Get class names of interfaces that support revision ownership.
ClassUtilsTrait::targetSupportBundles protected function
ClassUtilsTrait::targetTypeBundleLabel protected function
ClassUtilsTrait::targetTypeLabel public function
ClassUtilsTrait::typeSupportsBundles protected function
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::$entityTypeManager protected property The entity type manager. 3
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::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
FieldUtilsTrait::FieldManager abstract function 3
FieldUtilsTrait::getBundleDestinationOptions protected function
FieldUtilsTrait::getDestinationFields protected function Return all fields that can be used as destinations fields.
FieldUtilsTrait::getDestinationFieldsOptions protected function
FieldUtilsTrait::getEntityDestinationOptions protected function
FieldUtilsTrait::getFieldDefinition public function Get field definition on bundle.
FieldUtilsTrait::getFieldLabel protected function
FieldUtilsTrait::getFieldStorageDefinition protected function Utility Function to load a single field definition.
FieldUtilsTrait::getMatchingFieldTypes protected function Get Fields that can used as a destination field for this type.
FieldUtilsTrait::getSourceFields protected function
FieldUtilsTrait::isDestinationFieldCompatible protected function Check if a field on the entity type to update is a possible destination field.
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.
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.
ScheduledUpdateTypeBaseForm::$entity protected property @var ScheduledUpdateType Overrides EntityForm::$entity
ScheduledUpdateTypeBaseForm::$entityFieldManager protected property
ScheduledUpdateTypeBaseForm::$fieldManager protected property
ScheduledUpdateTypeBaseForm::$moduleHandler protected property Overrides EntityForm::$moduleHandler
ScheduledUpdateTypeBaseForm::$runnerManager protected property
ScheduledUpdateTypeBaseForm::$updateUtils protected property
ScheduledUpdateTypeBaseForm::cloneSingleField protected function Clone a single field from the settings on type add form.
ScheduledUpdateTypeBaseForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ScheduledUpdateTypeBaseForm::createDefaultValueElements protected function Create the default value elements for a field.
ScheduledUpdateTypeBaseForm::createNewFieldsElements protected function Create options for create a new entity reference field.
ScheduledUpdateTypeBaseForm::createRunnerElements protected function Create form elements for runner selection and options.
ScheduledUpdateTypeBaseForm::createRunnerInstance protected function Create an instance of the Runner plugin to be used with this Update Type.
ScheduledUpdateTypeBaseForm::doSave public function Save the entity on submit.
ScheduledUpdateTypeBaseForm::existingReferenceFields protected function Get existing entity reference field on target entity type that reference scheduled updates.
ScheduledUpdateTypeBaseForm::fieldNameExists public function Checks if a field machine name is taken.
ScheduledUpdateTypeBaseForm::getCurrentEntityType protected function Get the current entity type to be updated for update type.
ScheduledUpdateTypeBaseForm::getDefaultBundle protected function Determine the default that should be used to create default value elements. 1
ScheduledUpdateTypeBaseForm::getSupportedRunnerDefinitions protected function Get definitions for Runner Plugins that should be supported. 1
ScheduledUpdateTypeBaseForm::getWidgetOverride protected function Get the widget that should used for the default value.
ScheduledUpdateTypeBaseForm::isDefaultCompatible private function Determine if we should try to make a default value widget.
ScheduledUpdateTypeBaseForm::runnerSupportsEmbedded protected function
ScheduledUpdateTypeBaseForm::setUpFieldReferences protected function Setup entity reference field for this update type on add.
ScheduledUpdateTypeBaseForm::typeDependentAjax protected function
ScheduledUpdateTypeBaseForm::updateRunnerSettings public function Ajax Form call back for Update Runner Fieldset.
ScheduledUpdateTypeBaseForm::updateTypeDependentSet public function Ajax Form call back for Create Reference Fieldset.
ScheduledUpdateTypeBaseForm::__construct public function Constructs a ScheduledUpdateTypeForm object.
ScheduledUpdateTypeForm::createCloneFieldSelect protected function Overridden to provide multi-field choice. Overrides ScheduledUpdateTypeBaseForm::createCloneFieldSelect
ScheduledUpdateTypeForm::createFieldMapElements protected function Create form elements to update field map.
ScheduledUpdateTypeForm::entityTypeOptions protected function Create select element entity type options.
ScheduledUpdateTypeForm::form public function Gets the actual form array to be built. Overrides ScheduledUpdateTypeBaseForm::form
ScheduledUpdateTypeForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
ScheduledUpdateTypeForm::validateForm public function Form validation handler. Overrides ScheduledUpdateTypeBaseForm::validateForm
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.