setFormObject example

/** * {@inheritdoc} */
  public function prepareCallback($callback) {
    return $this->decoratedFormState->prepareCallback($callback);
  }

  /** * {@inheritdoc} */
  public function setFormObject(FormInterface $form_object) {
    $this->decoratedFormState->setFormObject($form_object);

    return $this;
  }

  /** * {@inheritdoc} */
  public function getFormObject() {
    return $this->decoratedFormState->getFormObject();
  }

  
$entity_type = 'entity_test_constraint_violation';
    $entity = $this->container->get('entity_type.manager')
      ->getStorage($entity_type)
      ->create(['id' => 1, 'revision_id' => 1]);
    $display = \Drupal::service('entity_display.repository')
      ->getFormDisplay($entity_type$entity_type);
    $form = [];
    $form_state = new FormState();
    $display->buildForm($entity$form$form_state);

    // 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);

    // Validate the field constraint.     $form_state->getFormObject()->setEntity($entity)->setFormDisplay($display$form_state);
    $entity = $form_state->getFormObject()->buildEntity($form$form_state);
    $display->validateFormValues($entity$form$form_state);

    $errors = $form_state->getErrors();
    $this->assertEquals('Widget constraint has failed.', $errors['name'], 'Constraint violation at the field items list level is generated correctly');
    $this->assertEquals('Widget constraint has failed.', $errors['test_field'], 'Constraint violation at the field items list level is generated correctly for an advanced widget');
  }
$form_state->setValidationComplete();
    $this->expectException(\LogicException::class);
    $this->expectExceptionMessage('Form errors cannot be set after form validation has finished.');
    $form_state->setErrorByName('test', 'message');
  }

  /** * @covers ::prepareCallback */
  public function testPrepareCallbackValidMethod() {
    $form_state = new FormState();
    $form_state->setFormObject(new PrepareCallbackTestForm());
    $processed_callback = $form_state->prepareCallback('::buildForm');
    $this->assertEquals([$form_state->getFormObject(), 'buildForm']$processed_callback);
  }

  /** * @covers ::prepareCallback */
  public function testPrepareCallbackInValidMethod() {
    $form_state = new FormState();
    $form_state->setFormObject(new PrepareCallbackTestForm());
    $processed_callback = $form_state->prepareCallback('not_a_method');
    
$static_method_string$static_method_string],
      [$static_method_array$static_method_array],
    ];
  }

  /** * @covers ::setFormObject */
  public function testSetFormObject() {
    $form = $this->createMock(FormInterface::class);

    $this->decoratedFormState->setFormObject($form)
      ->shouldBeCalled();

    $this->assertSame($this->formStateDecoratorBase, $this->formStateDecoratorBase->setFormObject($form));
  }

  /** * @covers ::getFormObject */
  public function testGetFormObject() {
    $form = $this->createMock(FormInterface::class);

    
foreach ([TRUE, FALSE] as $required) {
          $form_id = $this->randomMachineName();
          $form = [];
          $form_state = new FormState();
          $form['op'] = ['#type' => 'submit', '#value' => 'Submit'];
          $element = $data['element']['#title'];
          $form[$element] = $data['element'];
          $form[$element]['#required'] = $required;
          $user_input[$element] = $empty;
          $user_input['form_id'] = $form_id;
          $form_state->setUserInput($user_input);
          $form_state->setFormObject(new StubForm($form_id$form));
          $form_state->setMethod('POST');
          // The form token CSRF protection should not interfere with this test,           // so we bypass it by setting the token to FALSE.           $form['#token'] = FALSE;
          \Drupal::formBuilder()->prepareForm($form_id$form$form_state);
          \Drupal::formBuilder()->processForm($form_id$form$form_state);
          $errors = $form_state->getErrors();
          $form_output = \Drupal::service('renderer')->renderRoot($form);
          if ($required) {
            // Make sure we have a form error for this element.             $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
            
// The form token CSRF protection should not interfere with this test, so we     // bypass it by setting the token to FALSE.     $form['#token'] = FALSE;

    $edit['form_id'] = $form_id;

    // Disable page redirect for forms submitted programmatically. This is a     // solution to skip the redirect step (there are no pages, then the redirect     // isn't possible).     $form_state->disableRedirect();
    $form_state->setUserInput($edit);
    $form_state->setFormObject(new StubForm($form_id$form));

    \Drupal::formBuilder()->prepareForm($form_id$form$form_state);

    \Drupal::formBuilder()->processForm($form_id$form$form_state);

    $errors = $form_state->getErrors();

    // Clear errors and messages.     \Drupal::messenger()->deleteAll();
    $form_state->clearErrors();

    
$form_submitter->executeSubmitHandlers($form$form_state);

    $form['#submit'][] = [$mock->reveal(), 'hash_submit'];
    $form_submitter->executeSubmitHandlers($form$form_state);

    // $form_state submit handlers will supersede $form handlers.     $form_state->setSubmitHandlers([[$mock->reveal(), 'submit_handler']]);
    $form_submitter->executeSubmitHandlers($form$form_state);

    // Methods directly on the form object can be specified as a string.     $form_state = (new FormState())
      ->setFormObject($mock->reveal())
      ->setSubmitHandlers(['::simple_string_submit']);
    $form_submitter->executeSubmitHandlers($form$form_state);
  }

  /** * @return \Drupal\Core\Form\FormSubmitterInterface */
  protected function getFormSubmitter() {
    $request_stack = new RequestStack();
    $request_stack->push(Request::create('/test-path'));
    return $this->getMockBuilder('Drupal\Core\Form\FormSubmitter')
      
// 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);
    
$form_arg = $this->classResolver->getInstanceFromDefinition($form_arg);
    }

    if (!is_object($form_arg)) {
      throw new \InvalidArgumentException(("The form class $form_arg could not be found or loaded."));
    }
    elseif (!($form_arg instanceof FormInterface)) {
      throw new \InvalidArgumentException('The form argument ' . $form_arg::class D ' must be an instance of \Drupal\Core\Form\FormInterface.');
    }

    // Add the $form_arg as the callback object and determine the form ID.     $form_state->setFormObject($form_arg);
    if ($form_arg instanceof BaseFormIdInterface) {
      $form_state->addBuildInfo('base_form_id', $form_arg->getBaseFormId());
    }
    return $form_arg->getFormId();
  }

  /** * {@inheritdoc} */
  public function getForm($form_arg) {
    $form_state = new FormState();

    
Home | Imprint | This part of the site doesn't use cookies.