getFormObject example

/** * Tests the getFormId() method with a class name form ID. */
  public function testGetFormIdWithClassName() {
    $form_arg = 'Drupal\Tests\Core\Form\TestForm';

    $form_state = new FormState();
    $form_id = $this->formBuilder->getFormId($form_arg$form_state);

    $this->assertSame('test_form', $form_id);
    $this->assertSame($form_argget_class($form_state->getFormObject()));
  }

  /** * Tests the getFormId() method with an injected class name form ID. */
  public function testGetFormIdWithInjectedClassName() {
    $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
    \Drupal::setContainer($container);

    $form_arg = 'Drupal\Tests\Core\Form\TestFormInjected';

    
return $form;
  }

  /** * Process callback: assigns weights and hides extra fields. * * @see \Drupal\Core\Entity\EntityForm::form() */
  public function processForm($element, FormStateInterface $form_state$form) {
    // If the form is cached, process callbacks may not have a valid reference     // to the entity object, hence we must restore it.     $this->entity = $form_state->getFormObject()->getEntity();

    return $element;
  }

  /** * Form element #after_build callback: Updates the entity with submitted data. * * Updates the internal $this->entity object with submitted values when the * form is being rebuilt (e.g. submitted via AJAX), so that subsequent * processing (e.g. AJAX callbacks) can rely on it. */
  

  protected function createMediaTypeViaForm($source_plugin_id$field_name) {
    /** @var \Drupal\media\MediaTypeInterface $type */
    $type = MediaType::create(['source' => $source_plugin_id]);

    $form = $this->container->get('entity_type.manager')
      ->getFormObject('media_type', 'add')
      ->setEntity($type);

    $form_state = new FormState();
    $form_state->setValues([
      'label' => 'Test type',
      'id' => $source_plugin_id,
      'op' => 'Save',
    ]);

    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
    $field_manager = \Drupal::service('entity_field.manager');

    

  public function __construct(EntityTypeManagerInterface $entity_type_manager, FormBuilderInterface $form_builder) {
    $this->entityTypeManager = $entity_type_manager;
    $this->formBuilder = $form_builder;
  }

  /** * {@inheritdoc} */
  public function getForm(EntityInterface $entity$operation = 'default', array $form_state_additions = []) {
    $form_object = $this->entityTypeManager->getFormObject($entity->getEntityTypeId()$operation);
    $form_object->setEntity($entity);

    $form_state = (new FormState())->setFormState($form_state_additions);
    return $this->formBuilder->buildForm($form_object$form_state);
  }

}
public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
    parent::entityFormAlter($form$form_state$entity);

    if (isset($form['content_translation'])) {
      // We do not need to show these values on node forms: they inherit the       // basic node property values.       $form['content_translation']['status']['#access'] = FALSE;
      $form['content_translation']['name']['#access'] = FALSE;
      $form['content_translation']['created']['#access'] = FALSE;
    }

    $form_object = $form_state->getFormObject();
    $form_langcode = $form_object->getFormLangcode($form_state);
    $translations = $entity->getTranslationLanguages();
    $status_translatable = NULL;
    // Change the submit button labels if there was a status field they affect     // in which case their publishing / unpublishing may or may not apply     // to all translations.     if (!$entity->isNew() && (!isset($translations[$form_langcode]) || count($translations) > 1)) {
      foreach ($entity->getFieldDefinitions() as $property_name => $definition) {
        if ($property_name == 'status') {
          $status_translatable = $definition->isTranslatable();
        }
      }

  public function entityPrepareForm(EntityInterface $entity$operation, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
    $form_object = $form_state->getFormObject();

    if ($this->isModeratedEntityEditForm($form_object) && !$entity->isNew()) {
      // Generate a proper revision object for the current entity. This allows       // to correctly handle translatable entities having pending revisions.       /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
      $storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
      /** @var \Drupal\Core\Entity\ContentEntityInterface $new_revision */
      $new_revision = $storage->createRevision($entity, FALSE);

      // Restore the revision ID as other modules may expect to find it still       // populated. This will reset the "new revision" flag, however the entity


  /** * Form submission handler for TermTranslationHandler::entityFormAlter(). * * This handles the save action. * * @see \Drupal\Core\Entity\EntityForm::build() */
  public function entityFormSave(array $form, FormStateInterface $form_state) {
    if ($this->getSourceLangcode($form_state)) {
      $entity = $form_state->getFormObject()->getEntity();
      // We need a redirect here, otherwise we would get an access denied page,       // since the current URL would be preserved and we would try to add a       // translation for a language that already has a translation.       $form_state->setRedirectUrl($entity->toUrl('edit-form'));
    }
  }

  /** * {@inheritdoc} */
  public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
    
return new static(
      $container->get('entity_type.manager'),
      $container->get('content_moderation.moderation_information'),
      $container->get('entity_type.bundle.info')
    );
  }

  /** * {@inheritdoc} */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $workflow = $form_state->getFormObject()->getEntity();

    $header = [
      'type' => $this->t('Items'),
      'operations' => $this->t('Operations'),
    ];
    $form['entity_types_container'] = [
      '#type' => 'details',
      '#title' => $this->t('This workflow applies to:'),
      '#open' => TRUE,
    ];
    $form['entity_types_container']['entity_types'] = [
      
$form_state->setStorage($preview->getStorage());
      $form_state->setUserInput($preview->getUserInput());

      // Rebuild the form.       $form_state->setRebuild();

      // The combination of having user input and rebuilding the form means       // that it will attempt to cache the form state which will fail if it is       // a GET request.       $form_state->setRequestMethod('POST');

      $this->entity = $preview->getFormObject()->getEntity();
      $this->entity->in_preview = NULL;

      $form_state->set('has_been_previewed', TRUE);
    }

    /** @var \Drupal\node\NodeInterface $node */
    $node = $this->entity;

    if ($this->operation == 'edit') {
      $form['#title'] = $this->t('<em>Edit @type</em> @title', [
        '@type' => node_get_type_label($node),
        
// Assign random weight.       do {
        $weight = mt_rand(0, $this->fieldTestData->field_storage_2->getCardinality());
      } while (in_array($weight$weights_2));
      $weights_2[$delta] = $weight;
      $values_2[$delta]['_weight'] = $weight;
    }
    // Leave an empty value. 'field_test' fields are empty if empty().     $values_2[1]['value'] = 0;

    // Pretend the form has been built.     $form_state->setFormObject(\Drupal::entityTypeManager()->getFormObject($entity_type, 'default'));
    \Drupal::formBuilder()->prepareForm('field_test_entity_form', $form$form_state);
    \Drupal::formBuilder()->processForm('field_test_entity_form', $form$form_state);
    $form_state->setValue($this->fieldTestData->field_name, $values);
    $form_state->setValue($this->fieldTestData->field_name_2, $values_2);

    // Extract values for all fields.     $entity = clone($entity_init);
    $display->extractFormValues($entity$form$form_state);

    asort($weights);
    asort($weights_2);
    

  public function isRebuilding() {
    return $this->rebuild;
  }

  /** * {@inheritdoc} */
  public function prepareCallback($callback) {
    if (is_string($callback) && substr($callback, 0, 2) == '::') {
      $callback = [$this->getFormObject()substr($callback, 2)];
    }
    return $callback;
  }

  /** * {@inheritdoc} */
  public function setFormObject(FormInterface $form_object) {
    $this->addBuildInfo('callback_object', $form_object);
    return $this;
  }

  
$view->stack = [];
      }
    }

    // Automatically remove the form cache if it is set and the key does     // not match. This way navigating away from the form without hitting     // update will work.     if (isset($view->form_cache) && $view->form_cache['key'] !== $form_key) {
      unset($view->form_cache);
    }

    $form_class = get_class($form_state->getFormObject());
    $response = $this->ajaxFormWrapper($form_class$form_state);

    // If the form has not been submitted, or was not set for rerendering, stop.     if (!$form_state->isSubmitted() || $form_state->get('rerender')) {
      return $response;
    }

    // Sometimes we need to re-generate the form for multi-step type operations.     if (!empty($view->stack)) {
      $stack = $view->stack;
      $top = array_shift($stack);

      
elseif (!$was_defaulted && $is_defaulted) {
      // We used to have an override for this display, but the user now wants       // to go back to the default display.       // Overwrite the default display with the current form values, and make       // the current display use the new default values.       $display = &$this->getExecutable()->displayHandlers->get($display_id);
      // optionsOverride toggles the override of this section.       $display->optionsOverride($form$form_state);
      $display->submitOptionsForm($form$form_state);
    }

    $submit_handler = [$form_state->getFormObject(), 'submitForm'];
    call_user_func_array($submit_handler[&$form$form_state]);
  }

  /** * Submit handler for cancel button. */
  public function standardCancel($form, FormStateInterface $form_state) {
    if (!empty($this->changed) && isset($this->form_cache)) {
      unset($this->form_cache);
      $this->cacheSet();
    }

    

  public function __construct(PrivateTempStoreFactory $temp_store_factory) {
    $this->tempStoreFactory = $temp_store_factory;
  }

  /** * {@inheritdoc} */
  public function convert($value$definition$name, array $defaults) {
    $store = $this->tempStoreFactory->get('node_preview');
    if ($form_state = $store->get($value)) {
      return $form_state->getFormObject()->getEntity();
    }
  }

  /** * {@inheritdoc} */
  public function applies($definition$name, Route $route) {
    if (!empty($definition['type']) && $definition['type'] == 'node_preview') {
      return TRUE;
    }
    return FALSE;
  }

  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $editor = $form_state->get('editor');
    assert($editor instanceof Editor);
    $language = $this->languageManager->getCurrentLanguage();

    // When enabling CKEditor 5, generate sensible settings from the     // pre-existing text editor/format rather than the hardcoded defaults     // whenever possible.     // @todo Remove after https://www.drupal.org/project/drupal/issues/3226673.     $format = $form_state->getFormObject()->getEntity();
    assert($format instanceof FilterFormatInterface);
    if ($editor->isNew() && !$form_state->get('ckeditor5_is_active') && $form_state->get('ckeditor5_is_selected')) {
      assert($editor->getSettings() === $this->getDefaultSettings());
      if (!$format->isNew()) {
        [$editor$messages] = $this->smartDefaultSettings->computeSmartDefaultSettings($editor$format);
        $form_state->set('used_smart_default_settings', TRUE);
        foreach ($messages as $type => $messages_per_type) {
          foreach ($messages_per_type as $message) {
            $this->messenger()->addMessage($message$type);
          }
        }
        
Home | Imprint | This part of the site doesn't use cookies.