formBuilder example

$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');
  }

  

  public function overview(Request $request) {

    $filter = $this->buildFilterQuery($request);
    $rows = [];

    $classes = static::getLogLevelClassMap();

    $this->moduleHandler()->loadInclude('dblog', 'admin.inc');

    $build['dblog_filter_form'] = $this->formBuilder()->getForm('Drupal\dblog\Form\DblogFilterForm');

    $header = [
      // Icon column.       '',
      [
        'data' => $this->t('Type'),
        'field' => 'w.type',
        'class' => [RESPONSIVE_PRIORITY_MEDIUM],
      ],
      [
        'data' => $this->t('Date'),
        

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

  /** * Tests the order of the machine name field and the source. */
  public function testMachineNameOrderException() {
    $this->expectException(\LogicException::class);
    $this->expectErrorMessage('The machine name element "test_machine_name" is defined before the source element "test_source", it must be defined after or the source element must specify an id.');
    $form = \Drupal::formBuilder()->getForm($this);
    $this->render($form);
  }

}
$this->drupalGet('form-test/pattern');
    $this->submitForm($edit, 'Submit');
    $this->assertSession()->pageTextNotContains('Client side validation field is not in the right format.');
  }

  /** * Tests #required with custom validation errors. * * @see \Drupal\form_test\Form\FormTestValidateRequiredForm */
  public function testCustomRequiredError() {
    $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestValidateRequiredForm');

    // Verify that a custom #required error can be set.     $edit = [];
    $this->drupalGet('form-test/validate-required');
    $this->submitForm($edit, 'Submit');

    foreach (Element::children($form) as $key) {
      if (isset($form[$key]['#required_error'])) {
        $this->assertSession()->pageTextNotContains($form[$key]['#title'] . ' field is required.');
        $this->assertSession()->pageTextContains((string) $form[$key]['#required_error']);
      }
      
$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'");
            if (!empty($form_output)) {
              // Make sure the form element is marked as required.               $this->assertMatchesRegularExpression($required_marker_preg(string) $form_output, "Required '$type' field is marked as required");
            }
          }
          
$state = MediaLibraryState::create('test', ['image', 'remote_video']$selected_type_id, -1);
    return \Drupal::service('media_library.ui_builder')->buildUi($state);
  }

  /** * Tests the validation of the library state in the media library add form. */
  public function testFormStateValidation() {
    $form_state = new FormState();
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage('The media library state is not present in the form state.');
    \Drupal::formBuilder()->buildForm(FileUploadForm::class$form_state);
  }

  /** * Tests the validation of the selected type in the media library add form. */
  public function testSelectedTypeValidation() {
    $state = MediaLibraryState::create('test', ['image', 'remote_video', 'header_image'], 'header_image', -1);
    $form_state = new FormState();
    $form_state->set('media_library_state', $state);
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage("The 'header_image' media type does not exist.");
    
      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);
    $expected_values = [];
    
$user = $this->userStorage->load($uid);
    if ($user === NULL || !$user->isActive()) {
      // Blocked or invalid user ID, so deny access. The parameters will be in       // the watchdog's URL for the administrator to check.       throw new AccessDeniedHttpException();
    }

    // Time out, in seconds, until login URL expires.     $timeout = $this->config('user.settings')->get('password_reset_timeout');

    $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
    return $this->formBuilder()->getForm(UserPasswordResetForm::class$user$expiration_date$timestamp$hash);
  }

  /** * Validates user, hash, and timestamp; logs the user in if correct. * * @param int $uid * User ID of the user requesting reset. * @param int $timestamp * The current timestamp. * @param string $hash * Login link hash. * @param \Symfony\Component\HttpFoundation\Request $request * The request. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * Returns a redirect to the user edit form if the information is correct. * If the information is incorrect redirects to 'user.pass' route with a * message for the user. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * If $uid is for a blocked user or invalid user ID. */

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

  /** * Tests that trusted callbacks are executed. */
  public function testDatelistElement() {
    $form_state = new FormState();
    $form = \Drupal::formBuilder()->buildForm($this$form_state);
    $this->render($form);

    $this->assertTrue($form['datelist_element']['datelistDateCallbackExecuted']['#value']);
    $this->assertTrue($form_state->get('datelistDateCallbackExecuted'));
  }

  /** * Tests that exceptions are raised if untrusted callbacks are used. * * @group legacy */
  

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

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

  public function testDropbuttonWithBubbleableMetadata() {
    $result = \Drupal::formBuilder()->getForm($this);
    \Drupal::service('renderer')->renderRoot($result);
    $this->assertEquals(['system/base', 'core/drupal.dropbutton']$result['#attached']['library']);
    $this->assertEquals(['foo']$result['#cache']['tags']);
  }

}
$plugin = $entity->getPlugin();

    // Build the form first, because it may redirect during the submit,     // and we don't want to build the results based on last time's request.     $build['#cache']['contexts'][] = 'url.query_args:keys';
    if ($request->query->has('keys')) {
      $keys = trim($request->query->get('keys'));
      $plugin->setSearch($keys$request->query->all()$request->attributes->all());
    }

    $build['#title'] = $plugin->suggestedTitle();
    $build['search_form'] = $this->formBuilder()->getForm(SearchPageForm::class$entity);

    // Build search results, if keywords or other search parameters are in the     // GET parameters. Note that we need to try the search if 'keys' is in     // there at all, vs. being empty, due to advanced search.     $results = [];
    if ($request->query->has('keys')) {
      if ($plugin->isSearchExecutable()) {
        // Log the search.         if ($this->config('search.settings')->get('logging')) {
          $this->logger->notice('Searched %type for %keys.', ['%keys' => $keys, '%type' => $entity->label()]);
        }

        

  protected function doSubmitForm($values$valid_input) {
    // Programmatically submit the given values.     $form_state = (new FormState())->setValues($values);
    \Drupal::formBuilder()->submitForm('\Drupal\form_test\Form\FormTestProgrammaticForm', $form_state);

    // Check that the form returns an error when expected, and vice versa.     $errors = $form_state->getErrors();
    $valid_form = empty($errors);
    $args = [
      '%values' => print_r($values, TRUE),
      '%errors' => $valid_form ? 'None' : implode(' ', $errors),
    ];
    $this->assertSame($valid_form$valid_inputnew FormattableMarkup('Input values: %values<br />Validation handler errors: %errors', $args));

    // We check submitted values only if we have a valid input.
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormState;

/** * Controller for block_test module. */
class TestMultipleFormController extends ControllerBase {

  public function testMultipleForms() {
    $form_state = new FormState();
    $build = [
      'form1' => $this->formBuilder()->buildForm('\Drupal\block_test\Form\TestForm', $form_state),
      'form2' => $this->formBuilder()->buildForm('\Drupal\block_test\Form\FavoriteAnimalTestForm', $form_state),
    ];

    // Output all attached placeholders trough     // \Drupal\Core\Messenger\MessengerInterface::addMessage(), so we can     // see if there's only one in the tests.     $post_render_callable = function D$elements) {
      $matches = [];
      preg_match_all('<form\s(.*?)action="(.*?)"(.*)>', $elements$matches);

      $action_values = $matches[2];

      

  protected $defaultTheme = 'stark';

  public function testFormCheckbox() {
    // Ensure that the checked state is determined and rendered correctly for     // tricky combinations of default and return values.     foreach ([FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar'] as $default_value) {
      // Only values that can be used for array indices are supported for       // #return_value, with the exception of integer 0, which is not supported.       // @see \Drupal\Core\Render\Element\Checkbox::processCheckbox().       foreach (['0', '', 1, '1', 'foobar', '1foobar'] as $return_value) {
        $form_array = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestCheckboxTypeJugglingForm', $default_value$return_value);
        $form = \Drupal::service('renderer')->renderRoot($form_array);
        if ($default_value === TRUE) {
          $checked = TRUE;
        }
        elseif ($return_value === '0') {
          $checked = ($default_value === '0');
        }
        elseif ($return_value === '') {
          $checked = ($default_value === '');
        }
        elseif ($return_value === 1 || $return_value === '1') {
          
'id' => $source_plugin_id,
      'op' => 'Save',
    ]);

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

    // Source field not created yet.     $fields = $field_manager->getFieldDefinitions('media', $source_plugin_id);
    $this->assertArrayNotHasKey($field_name$fields);

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

    // Source field exists now.     $fields = $field_manager->getFieldDefinitions('media', $source_plugin_id);
    $this->assertArrayHasKey($field_name$fields);
  }

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