You are here

protected function ConditionalFieldEditForm::getDummyField in Conditional Fields 8

Same name and namespace in other branches
  1. 4.x src/Form/ConditionalFieldEditForm.php \Drupal\conditional_fields\Form\ConditionalFieldEditForm::getDummyField()

Creates dummy field instance.

1 call to ConditionalFieldEditForm::getDummyField()
ConditionalFieldEditForm::buildForm in src/Form/ConditionalFieldEditForm.php
Form constructor.

File

src/Form/ConditionalFieldEditForm.php, line 515

Class

ConditionalFieldEditForm
Class ConditionalFieldEditForm.

Namespace

Drupal\conditional_fields\Form

Code

protected function getDummyField($entity_type, $bundle, $condition, FormStateInterface $form_state, $default_value = NULL) {
  $field_name = $condition['dependee'];
  $dummy_field = [];
  $entityTypeManager = $this->entityTypeManager;
  $storage = $entityTypeManager
    ->getStorage($entity_type);
  $bundle_key = $storage
    ->getEntityType()
    ->getKey('bundle');
  $dummy_entity = $storage
    ->create([
    'uid' => $this
      ->currentUser()
      ->id(),
    $bundle_key => $bundle,
  ]);

  // Set current value.
  if ($default_value) {
    $dummy_entity
      ->set($field_name, $default_value);
  }
  try {

    // Be able to add new and edit existing conditional fields on entities,
    // where "edit" form class is not defined.
    $handlers = $entityTypeManager
      ->getDefinition($entity_type)
      ->getHandlerClasses();
    $operation = isset($handlers['form']['edit']) ? 'edit' : 'default';
    $form_object = $entityTypeManager
      ->getFormObject($entity_type, $operation);
    $form_object
      ->setEntity($dummy_entity);
  } catch (InvalidPluginDefinitionException $e) {
    watchdog_exception('conditional_fields', $e);

    // @TODO May be it make sense to return markup?
    return NULL;
  }
  $form_builder_service = $this->formBuilder;
  $form_state_additions = [];
  $form_state_new = (new FormState())
    ->setFormState($form_state_additions);
  if ($form_state
    ->isMethodType("POST")) {
    $form_state_new
      ->setRequestMethod("POST");
  }

  // Set Submitted value.
  $user_input = $form_state
    ->getUserInput();
  if (isset($user_input[$field_name])) {

    // Set field value.
    $form_state_new
      ->setUserInput([
      $field_name => $user_input[$field_name],
    ]);
    $form_state_new
      ->setProgrammed(TRUE);
    $form_state_new
      ->setValidationComplete(TRUE);
  }
  $dummy_entity_form = $form_builder_service
    ->buildForm($form_object, $form_state_new);
  if (isset($dummy_entity_form[$field_name])) {
    $dummy_field = $dummy_entity_form[$field_name];

    // Unset required for dummy field in case field will be hidden.
    $this
      ->setFieldProperty($dummy_field, '#required', FALSE);
  }
  return $dummy_field;
}