FormState example


  protected function assertFormOptions(ViewExecutable $view, string $display_link_id): void {
    $form = [];
    $form_state = new FormState();
    /** @var \Drupal\views\Plugin\views\area\DisplayLink $display_handler */
    $display_handler = $view->display_handler->getHandler('header', $display_link_id);
    $display_handler->buildOptionsForm($form$form_state);
    $this->assertTrue(isset($form['display_id']['#options']['page_1']));
    $this->assertTrue(isset($form['display_id']['#options']['page_2']));
    $this->assertFalse(isset($form['display_id']['#options']['block_1']));
  }

  /** * Assert the display links are correctly rendered for a display. * * @param \Drupal\views\ViewExecutable $view * The view to check. * @param string $display_id * The display ID to check the links for. * * @internal */
'#parents' => [],
      '#disable_inline_form_errors' => TRUE,
      '#array_parents' => [],
    ];
    $form['test'] = [
      '#type' => 'textfield',
      '#title' => 'Test',
      '#parents' => ['test'],
      '#id' => 'edit-test',
      '#array_parents' => ['test'],
    ];
    $form_state = new FormState();

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

    // Just test if the #error_no_message property is TRUE. FormErrorHandlerTest     // tests if the property actually hides the error message.     $this->assertTrue($form['test']['#error_no_message']);
  }

}
$this->renderer->expects($this->once())
      ->method('renderPlain')
      ->willReturnCallback(function D$render_array) {
        $links = [];
        foreach ($render_array[1]['#items'] as $item) {
          $links[] = htmlspecialchars($item['#title']);
        }

        return $render_array[0]['#markup'] . '<ul-comma-list-mock><li-mock>' . implode('</li-mock><li-mock>', $links) . '</li-mock></ul-comma-list-mock>';
      });

    $form_state = new FormState();
    $form_state->setErrorByName('test1', 'invalid');
    $form_state->setErrorByName('test2', 'invalid');
    $form_state->setErrorByName('fieldset][test3', 'invalid');
    $form_state->setErrorByName('test4', 'no error message');
    $form_state->setErrorByName('test5', 'no title given');
    $form_state->setErrorByName('test6', 'element is invisible');
    $form_state->setErrorByName('missing_element', 'this missing element is invalid');
    $this->formErrorHandler->handleFormErrors($this->testForm, $form_state);

    // Assert the #errors is populated for proper input.     $this->assertSame('invalid', $this->testForm['test1']['#errors']);
    
$data[] = ['', ['test']];
    $data[] = ['test', 'test'];
    $data[] = ['123', 123];

    return $data;
  }

  /** * @covers ::processMachineName */
  public function testProcessMachineName() {
    $form_state = new FormState();

    $element = [
      '#id' => 'test',
      '#field_suffix' => 'test_suffix',
      '#field_prefix' => 'test_prefix',
      '#machine_name' => [
        'source' => [
          'test_source',
        ],
        'maxlength' => 32,
        'additional_property' => TRUE,
        

  protected static $modules = ['views_ui', 'workspaces'];

  /** * Tests creating a view of workspace entities. * * @see \Drupal\views\Plugin\views\wizard\WizardPluginBase */
  public function testCreateWorkspaceView() {
    $wizard = \Drupal::service('plugin.manager.views.wizard')->createInstance('standard:workspace', []);
    $form = [];
    $form_state = new FormState();
    $form = $wizard->buildForm($form$form_state);
    $random_id = strtolower($this->randomMachineName());
    $random_label = $this->randomMachineName();

    $form_state->setValues([
      'id' => $random_id,
      'label' => $random_label,
      'base_table' => 'workspace',
    ]);

    $wizard->validateView($form$form_state);
    
/** * Tests widget constraint validation. */
  public function testValidation() {
    $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);

    


  /** * @covers ::buildResponse */
  public function testBuildResponseNoTriggeringElement() {
    $this->renderer->expects($this->never())
      ->method('renderResponse');

    $request = new Request();
    $form = [];
    $form_state = new FormState();
    $commands = [];

    $this->expectException(HttpException::class);
    $this->formAjaxResponseBuilder->buildResponse($request$form$form_state$commands);
  }

  /** * @covers ::buildResponse */
  public function testBuildResponseNoCallable() {
    $this->renderer->expects($this->never())
      
/** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

  /** * Tests that #limit_validation_errors of the only submit button takes effect. */
  public function testLimitValidationErrors() {
    // Programmatically submit the form.     $form_state = new FormState();
    $form_state->setValue('section', 'one');
    $form_builder = $this->container->get('form_builder');
    $form_builder->submitForm($this$form_state);

    // Verify that only the specified section was validated.     $errors = $form_state->getErrors();
    $this->assertTrue(isset($errors['one']), "Section 'one' was validated.");
    $this->assertFalse(isset($errors['two']), "Section 'two' was not validated.");

    // Verify that there are only values for the specified section.     $this->assertTrue($form_state->hasValue('one'), "Values for section 'one' found.");
    
parent::setUp();
    $this->urlGenerator = $this->createMock(UrlGeneratorInterface::class);
    $this->unroutedUrlAssembler = $this->createMock(UnroutedUrlAssemblerInterface::class);
  }

  /** * @covers ::doSubmitForm */
  public function testHandleFormSubmissionNotSubmitted() {
    $form_submitter = $this->getFormSubmitter();
    $form = [];
    $form_state = new FormState();

    $return = $form_submitter->doSubmitForm($form$form_state);
    $this->assertFalse($form_state->isExecuted());
    $this->assertNull($return);
  }

  /** * @covers ::doSubmitForm */
  public function testHandleFormSubmissionNoRedirect() {
    $form_submitter = $this->getFormSubmitter();
    

  public function testProgrammatic($value = 1) {
    $form_state = (new FormState())->setValues([
      'value' => $value,
    ]);
    \Drupal::formBuilder()->submitForm('Drupal\batch_test\Form\BatchTestChainedForm', $form_state);
    return [
      'success' => [
        '#markup' => 'Got out of a programmatic batched form.',
      ],
    ];
  }

  /** * Runs a batch for testing theme used on the progress page. * * @return \Symfony\Component\HttpFoundation\RedirectResponse|null * A redirect response if the batch is progressive. No return value otherwise. */

  public function validateForm(array &$form, FormStateInterface $form_state) {}

  /** * Ensures maxlength attribute can be used in compatible elements. */
  public function testAttributes() {

    /** @var \Drupal\Core\Form\FormBuilderInterface $form_builder */
    $form_builder = $this->container->get('form_builder');
    $form_state = new FormState();
    $elements = $form_builder->buildForm($this$form_state);
    $this->render($elements);

    $css_selector_converter = new CssSelectorConverter();
    $elements = $this->xpath($css_selector_converter->toXPath('input[name=title][maxlength=255]'));
    $this->assertCount(1, $elements, 'Text field has correct maxlength in form.');
    $elements = $this->xpath($css_selector_converter->toXPath('textarea[name=description][maxlength=255]'));
    $this->assertCount(1, $elements, 'Textarea field has correct maxlength in form.');
  }

}
$elements['file']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'file'];
    $elements['file']['empty_values'] = $empty_strings;

    // Regular expression to find the expected marker on required elements.     $required_marker_preg = '@<.*?class=".*?js-form-required.*form-required.*?">@';
    // Go through all the elements and all the empty values for them.     foreach ($elements as $type => $data) {
      foreach ($data['empty_values'] as $key => $empty) {
        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.

  public function validateForm(array &$form, FormStateInterface $form_state) {}

  /** * Tests that default handlers are added even if custom are specified. */
  public function testPathElement() {
    $form_state = (new FormState())
      ->setValues([
        'required_validate' => 'user/' . $this->testUser->id(),
        'required_non_validate' => 'magic-ponies',
        'required_validate_route' => 'user/' . $this->testUser->id(),
        'required_validate_url' => 'user/' . $this->testUser->id(),
        'optional_validate' => 'user/' . $this->testUser->id(),
        'optional_validate_route' => 'user/' . $this->testUser->id(),
      ]);
    $form_builder = $this->container->get('form_builder');
    $form_builder->submitForm($this$form_state);

    
/** * Tests the submitConfigurationForm() method. * * @covers ::submitConfigurationForm */
  public function testSubmitConfigurationForm() {
    $display_variant = $this->setUpDisplayVariant();
    $this->assertSame('', $display_variant->label());

    $form = [];
    $label = $this->randomMachineName();
    $form_state = new FormState();
    $form_state->setValue('label', $label);
    $display_variant->submitConfigurationForm($form$form_state);
    $this->assertSame($label$display_variant->label());
  }

}
// Test non-existent tables/fields.     $items = [
      [
        'table' => 'table_invalid',
        'field' => 'id',
      ],
      [
        'table' => 'views_test_data',
        'field' => 'field_invalid',
      ],
    ];
    $form_state = new FormState();
    $description_top = '<p>The handler for this item is broken or missing. The following details are available:</p>';
    $description_bottom = '<p>Enabling the appropriate module may solve this issue. Otherwise, check to see if there is a module update available.</p>';
    foreach ($types as $type => $class) {
      foreach ($items as $item) {
        $handler = $this->container->get('plugin.manager.views.' . $type)
          ->getHandler($item);
        $this->assertTrue($handler instanceof $class);
        // Make sure details available at edit form.         $form = [];
        $handler->buildOptionsForm($form$form_state);
        $this->assertEquals($description_top$form['description']['description_top']['#markup']);
        
Home | Imprint | This part of the site doesn't use cookies.