• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP Form\FormState类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Drupal\Core\Form\FormState的典型用法代码示例。如果您正苦于以下问题:PHP FormState类的具体用法?PHP FormState怎么用?PHP FormState使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了FormState类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: buildChildFormState

  /**
   * Build all necessary things for child form (form state, etc.).
   *
   * @param \Drupal\Core\Entity\EntityFormInterface $controller
   *   Entity form controller for child form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Parent form state object.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   Entity object.
   * @param string $operation
   *   Operation that is to be performed in inline form.
   * @param array $parents
   *   Entity form #parents.
   *
   * @return \Drupal\Core\Form\FormStateInterface
   *   Child form state object.
   */
  public static function buildChildFormState(EntityFormInterface $controller, FormStateInterface $form_state, EntityInterface $entity, $operation, $parents) {
    $child_form_state = new FormState();

    $child_form_state->addBuildInfo('callback_object', $controller);
    $child_form_state->addBuildInfo('base_form_id', $controller->getBaseFormID());
    $child_form_state->addBuildInfo('form_id', $controller->getFormID());
    $child_form_state->addBuildInfo('args', array());

    // Copy values to child form.
    $child_form_state->setCompleteForm($form_state->getCompleteForm());
    $child_form_state->setUserInput($form_state->getUserInput());

    // Filter out all submitted values that are not directly relevant for this
    // IEF. Otherwise they might mess things up.
    $form_state_values = $form_state->getValues();
    $form_state_values = static::extractArraySequence($form_state_values, $parents);

    $child_form_state->setValues($form_state_values);
    $child_form_state->setStorage($form_state->getStorage());
    $value = \Drupal::entityTypeManager()->getStorage('entity_form_display')->load($entity->getEntityTypeId() . '.' . $entity->bundle() . '.' . $operation);
    $child_form_state->set('form_display', $value);

    // Since some of the submit handlers are run, redirects need to be disabled.
    $child_form_state->disableRedirect();

    // When a form is rebuilt after Ajax processing, its #build_id and #action
    // should not change.
    // @see drupal_rebuild_form()
    $rebuild_info = $child_form_state->getRebuildInfo();
    $rebuild_info['copy']['#build_id'] = TRUE;
    $rebuild_info['copy']['#action'] = TRUE;
    $child_form_state->setRebuildInfo($rebuild_info);

    $child_form_state->set('inline_entity_form', $form_state->get('inline_entity_form'));
    $child_form_state->set('langcode', $entity->language()->getId());

    $child_form_state->set('field', $form_state->get('field'));
    $child_form_state->setTriggeringElement($form_state->getTriggeringElement());
    $child_form_state->setSubmitHandlers($form_state->getSubmitHandlers());

    return $child_form_state;
  }
开发者ID:joebachana,项目名称:usatne,代码行数:59,代码来源:EntityInlineForm.php


示例2: featureEdit

 /**
  * Displays the edit feature form.
  */
 public function featureEdit(NodeInterface $node, $fid, $pfid)
 {
     $func = uc_product_feature_data($fid, 'callback');
     $form_state = new FormState();
     $form_state->setBuildInfo(array('args' => array($node, uc_product_feature_load($pfid))));
     return $this->formBuilder()->buildForm($func, $form_state);
 }
开发者ID:justincletus,项目名称:webdrupalpro,代码行数:10,代码来源:ProductFeaturesController.php


示例3: testProcessMachineName

  /**
   * @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,
        '#additional_property_with_hash' => TRUE,
      ]
    ];

    $complete_form = [
      'test_source' => [
        '#type' => 'textfield',
        '#id' => 'source',
      ],
      'test_machine_name' => $element
    ];

    $form_state->setCompleteForm($complete_form);

    $language = $this->prophesize(LanguageInterface::class);
    $language->getId()->willReturn('xx-lolspeak');

    $language_manager = $this->prophesize(LanguageManagerInterface::class);
    $language_manager->getCurrentLanguage()->willReturn($language);

    $csrf_token = $this->prophesize(CsrfTokenGenerator::class);
    $csrf_token->get('[^a-z0-9_]+')->willReturn('tis-a-fine-token');

    $container = $this->prophesize(ContainerInterface::class);
    $container->get('language_manager')->willReturn($language_manager->reveal());
    $container->get('csrf_token')->willReturn($csrf_token->reveal());
    \Drupal::setContainer($container->reveal());

    $element = MachineName::processMachineName($element, $form_state, $complete_form);
    $settings = $element['#attached']['drupalSettings']['machineName']['#source'];

    $allowed_options = [
      'replace_pattern',
      'replace',
      'maxlength',
      'target',
      'label',
      'field_prefix',
      'field_suffix',
      'suffix',
      'replace_token',
    ];
    $this->assertEmpty(array_diff_key($settings, array_flip($allowed_options)));
    foreach ($allowed_options as $key) {
      $this->assertArrayHasKey($key, $settings);
    }
  }
开发者ID:Greg-Boggs,项目名称:electric-dev,代码行数:63,代码来源:MachineNameTest.php


示例4: getForm

 /**
  * {@inheritdoc}
  */
 public function getForm($formClass)
 {
     $args = func_get_args();
     array_shift($args);
     if (!class_exists($formClass)) {
         $this->logger->log(LogLevel::CRITICAL, "Form class '@class' does not exists", ['@class' => $formClass]);
         return [];
     }
     if (!method_exists($formClass, 'create')) {
         $this->logger->log(LogLevel::CRITICAL, "Form class '@class' does not implements ::create()", ['@class' => $formClass]);
         return [];
     }
     // God, I do hate Drupal 8...
     $form = call_user_func([$formClass, 'create'], $this->container);
     if (!$form instanceof FormInterface) {
         $this->logger->log(LogLevel::CRITICAL, "Form class '@class' does not implement \\Drupal\\Core\\Form\\FormInterface", ['@class' => $formClass]);
         return [];
     }
     $formId = $form->getFormId();
     $data = [];
     $data['build_info']['args'] = $args;
     $formState = new FormState($data);
     $formState->setFormObject($form);
     $this->formMap[$formId] = [$form, $formState];
     return drupal_build_form($formId, $data);
 }
开发者ID:makinacorpus,项目名称:drupal-sf-dic,代码行数:29,代码来源:FormBuilder.php


示例5: submitFormPage

 /**
  * Page that triggers a programmatic form submission.
  *
  * Returns the validation errors triggered by the form submission as json.
  */
 public function submitFormPage()
 {
     $form_state = new FormState();
     $values = ['name' => 'robo-user', 'mail' => '[email protected]', 'op' => t('Submit')];
     $form_state->setValues($values);
     \Drupal::formBuilder()->submitForm('\\Drupal\\user\\Form\\UserPasswordForm', $form_state);
     return new JsonResponse($form_state->getErrors());
 }
开发者ID:systemick3,项目名称:systemick.co.uk,代码行数:13,代码来源:HoneypotTestController.php


示例6: testValidationComplete

 /**
  * Tests the 'validation_complete' $form_state flag.
  *
  * @covers ::validateForm
  * @covers ::finalizeValidation
  */
 public function testValidationComplete()
 {
     $form_validator = $this->getMockBuilder('Drupal\\Core\\Form\\FormValidator')->setConstructorArgs([new RequestStack(), $this->getStringTranslationStub(), $this->csrfToken, $this->logger, $this->formErrorHandler])->setMethods(NULL)->getMock();
     $form = array();
     $form_state = new FormState();
     $this->assertFalse($form_state->isValidationComplete());
     $form_validator->validateForm('test_form_id', $form, $form_state);
     $this->assertTrue($form_state->isValidationComplete());
 }
开发者ID:neetumorwani,项目名称:blogging,代码行数:15,代码来源:FormValidatorTest.php


示例7: testValidationComplete

 /**
  * Tests the 'validation_complete' $form_state flag.
  *
  * @covers ::validateForm
  * @covers ::finalizeValidation
  */
 public function testValidationComplete()
 {
     $form_validator = $this->getMockBuilder('Drupal\\Core\\Form\\FormValidator')->disableOriginalConstructor()->setMethods(NULL)->getMock();
     $form = array();
     $form_state = new FormState();
     $this->assertFalse($form_state->isValidationComplete());
     $form_validator->validateForm('test_form_id', $form, $form_state);
     $this->assertTrue($form_state->isValidationComplete());
 }
开发者ID:davidsoloman,项目名称:drupalconsole.com,代码行数:15,代码来源:FormValidatorTest.php


示例8: testSetElementErrorsFromFormState

 /**
  * @covers ::handleFormErrors
  * @covers ::setElementErrorsFromFormState
  */
 public function testSetElementErrorsFromFormState()
 {
     $form_error_handler = $this->getMockBuilder('Drupal\\Core\\Form\\FormErrorHandler')->setMethods(['drupalSetMessage'])->getMock();
     $form = ['#parents' => []];
     $form['test'] = ['#type' => 'textfield', '#title' => 'Test', '#parents' => ['test'], '#id' => 'edit-test'];
     $form_state = new FormState();
     $form_state->setErrorByName('test', 'invalid');
     $form_error_handler->handleFormErrors($form, $form_state);
     $this->assertSame('invalid', $form['test']['#errors']);
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:14,代码来源:FormErrorHandlerTest.php


示例9: testSetElementErrorsFromFormState

 /**
  * @covers ::handleFormErrors
  * @covers ::setElementErrorsFromFormState
  */
 public function testSetElementErrorsFromFormState()
 {
     $form_error_handler = $this->getMockBuilder('Drupal\\Core\\Form\\FormErrorHandler')->setConstructorArgs([$this->getStringTranslationStub(), $this->getMock('Drupal\\Core\\Utility\\LinkGeneratorInterface')])->setMethods(['drupalSetMessage'])->getMock();
     $form = ['#parents' => []];
     $form['test'] = ['#type' => 'textfield', '#title' => 'Test', '#parents' => ['test'], '#id' => 'edit-test'];
     $form_state = new FormState();
     $form_state->setErrorByName('test', 'invalid');
     $form_error_handler->handleFormErrors($form, $form_state);
     $this->assertSame('invalid', $form['test']['#errors']);
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:14,代码来源:FormErrorHandlerTest.php


示例10: testGetSelected

 /**
  * @covers ::getSelected
  *
  * @dataProvider providerTestGetSelected
  */
 public function testGetSelected($expected, $element = [], $parents = [], $user_input = [], $not_rebuilding_expected = NULL)
 {
     $not_rebuilding_expected = $not_rebuilding_expected ?: $expected;
     $form_state = new FormState();
     $form_state->setUserInput($user_input);
     $actual = WizardPluginBase::getSelected($form_state, $parents, 'the_default_value', $element);
     $this->assertSame($not_rebuilding_expected, $actual);
     $this->assertSame($user_input, $form_state->getUserInput());
     $form_state->setRebuild();
     $actual = WizardPluginBase::getSelected($form_state, $parents, 'the_default_value', $element);
     $this->assertSame($expected, $actual);
     $this->assertSame($user_input, $form_state->getUserInput());
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:18,代码来源:WizardPluginBaseTest.php


示例11: testLimitValidationErrors

 /**
  * Tests that #limit_validation_errors of the only submit button takes effect.
  */
 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.");
     $this->assertFalse($form_state->hasValue('two'), "Values for section 'two' not found.");
 }
开发者ID:ddrozdik,项目名称:dmaps,代码行数:18,代码来源:TriggeringElementProgrammedUnitTest.php


示例12: testInstallConfigureForm

 /**
  * Tests the root user account form section in the "Configure site" form.
  */
 function testInstallConfigureForm()
 {
     require_once \Drupal::root() . '/core/includes/install.core.inc';
     require_once \Drupal::root() . '/core/includes/install.inc';
     $install_state = install_state_defaults();
     $form_state = new FormState();
     $form_state->addBuildInfo('args', [&$install_state]);
     $form = $this->container->get('form_builder')->buildForm('Drupal\\Core\\Installer\\Form\\SiteConfigureForm', $form_state);
     // Verify name and pass field order.
     $this->assertFieldOrder($form['admin_account']['account']);
     // Verify that web browsers may autocomplete the email value and
     // autofill/prefill the name and pass values.
     foreach (array('mail', 'name', 'pass') as $key) {
         $this->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'{$key}' field: 'autocomplete' attribute not found.");
     }
 }
开发者ID:ravibarnwal,项目名称:laraitassociate.in,代码行数:19,代码来源:UserAccountFormFieldsTest.php


示例13: testEntityRow

 /**
  * Tests the entity row handler.
  */
 public function testEntityRow()
 {
     $vocab = Vocabulary::create(['name' => $this->randomMachineName(), 'vid' => strtolower($this->randomMachineName())]);
     $vocab->save();
     $term = Term::create(['name' => $this->randomMachineName(), 'vid' => $vocab->id()]);
     $term->save();
     $view = Views::getView('test_entity_row');
     $build = $view->preview();
     $this->render($build);
     $this->assertText($term->getName(), 'The rendered entity appears as row in the view.');
     // Tests the available view mode options.
     $form = array();
     $form_state = new FormState();
     $form_state->set('view', $view->storage);
     $view->rowPlugin->buildOptionsForm($form, $form_state);
     $this->assertTrue(isset($form['view_mode']['#options']['default']), 'Ensure that the default view mode is available');
 }
开发者ID:sojo,项目名称:d8_friendsofsilence,代码行数:20,代码来源:RowEntityTest.php


示例14: testExtractFormValues

 /**
  * @covers ::extractFormValues
  */
 public function testExtractFormValues()
 {
     $menu_link_manager = $this->prophesize(MenuLinkManagerInterface::class);
     $menu_parent_form_selector = $this->prophesize(MenuParentFormSelectorInterface::class);
     $module_handler = $this->prophesize(ModuleHandlerInterface::class);
     $menu_link_form = new MenuLinkDefaultForm($menu_link_manager->reveal(), $menu_parent_form_selector->reveal(), $this->getStringTranslationStub(), $module_handler->reveal());
     $static_override = $this->prophesize(StaticMenuLinkOverridesInterface::class);
     $menu_link = new MenuLinkDefault([], 'my_plugin_id', [], $static_override->reveal());
     $menu_link_form->setMenuLinkInstance($menu_link);
     $form_state = new FormState();
     $form_state->setValue('id', 'my_plugin_id');
     $form_state->setValue('enabled', FALSE);
     $form_state->setValue('weight', 5);
     $form_state->setValue('expanded', TRUE);
     $form_state->setValue('menu_parent', 'foo:bar');
     $form = [];
     $result = $menu_link_form->extractFormValues($form, $form_state);
     $this->assertEquals(['id' => 'my_plugin_id', 'enabled' => 0, 'weight' => 5, 'expanded' => 1, 'parent' => 'bar', 'menu_name' => 'foo'], $result);
 }
开发者ID:frankcr,项目名称:sftw8,代码行数:22,代码来源:MenuLinkDefaultFormTest.php


示例15: testSetCacheWithSafeStrings

 /**
  * @covers ::setCache
  */
 public function testSetCacheWithSafeStrings()
 {
     // A call to SafeMarkup::set() is appropriate in this test as a way to add a
     // string to the safe list in the simplest way possible. Normally, avoid it.
     SafeMarkup::set('a_safe_string');
     $form_build_id = 'the_form_build_id';
     $form = ['#form_id' => 'the_form_id'];
     $form_state = new FormState();
     $this->formCacheStore->expects($this->once())->method('setWithExpire')->with($form_build_id, $form, $this->isType('int'));
     $form_state_data = $form_state->getCacheableArray();
     $form_state_data['build_info']['safe_strings'] = ['a_safe_string' => ['html' => TRUE]];
     $this->formStateCacheStore->expects($this->once())->method('setWithExpire')->with($form_build_id, $form_state_data, $this->isType('int'));
     $this->formCache->setCache($form_build_id, $form, $form_state);
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:17,代码来源:FormCacheTest.php


示例16: testRequiredFields

 /**
  * Check several empty values for required forms elements.
  *
  * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
  * valid content for a required field.
  *
  * If the form field is found in $form_state->getErrors() then the test pass.
  */
 function testRequiredFields()
 {
     // Originates from https://www.drupal.org/node/117748.
     // Sets of empty strings and arrays.
     $empty_strings = array('""' => "", '"\\n"' => "\n", '" "' => " ", '"\\t"' => "\t", '" \\n\\t "' => " \n\t ", '"\\n\\n\\n\\n\\n"' => "\n\n\n\n\n");
     $empty_arrays = array('array()' => array());
     $empty_checkbox = array(NULL);
     $elements['textfield']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'textfield');
     $elements['textfield']['empty_values'] = $empty_strings;
     $elements['telephone']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'tel');
     $elements['telephone']['empty_values'] = $empty_strings;
     $elements['url']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'url');
     $elements['url']['empty_values'] = $empty_strings;
     $elements['search']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'search');
     $elements['search']['empty_values'] = $empty_strings;
     $elements['password']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'password');
     $elements['password']['empty_values'] = $empty_strings;
     $elements['password_confirm']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'password_confirm');
     // Provide empty values for both password fields.
     foreach ($empty_strings as $key => $value) {
         $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value);
     }
     $elements['textarea']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'textarea');
     $elements['textarea']['empty_values'] = $empty_strings;
     $elements['radios']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()));
     $elements['radios']['empty_values'] = $empty_arrays;
     $elements['checkbox']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'checkbox', '#required' => TRUE);
     $elements['checkbox']['empty_values'] = $empty_checkbox;
     $elements['checkboxes']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'checkboxes', '#options' => array($this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()));
     $elements['checkboxes']['empty_values'] = $empty_arrays;
     $elements['select']['element'] = array('#title' => $this->randomMachineName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()));
     $elements['select']['empty_values'] = $empty_strings;
     $elements['file']['element'] = array('#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=".*?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 (array(TRUE, FALSE) as $required) {
                 $form_id = $this->randomMachineName();
                 $form = array();
                 $form_state = new FormState();
                 $form['op'] = array('#type' => 'submit', '#value' => t('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 elements of type 'radios' throw all sorts of PHP notices
                 // when you try to render them like this, so we ignore those for
                 // testing the required marker.
                 // @todo Fix this work-around (https://www.drupal.org/node/588438).
                 $form_output = $type == 'radios' ? '' : \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->assertTrue(preg_match($required_marker_preg, $form_output), "Required '{$type}' field is marked as required");
                     }
                 } else {
                     if (!empty($form_output)) {
                         // Make sure the form element is *not* marked as required.
                         $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '{$type}' field is not marked as required");
                     }
                     if ($type == 'select') {
                         // Select elements are going to have validation errors with empty
                         // input, since those are illegal choices. Just make sure the
                         // error is not "field is required".
                         $this->assertTrue(empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE, "Optional '{$type}' field '{$element}' is not treated as a required element");
                     } else {
                         // Make sure there is *no* form error for this element.
                         $this->assertTrue(empty($errors[$element]), "Optional '{$type}' field '{$element}' has no errors with empty input");
                     }
                 }
             }
         }
     }
     // Clear the expected form error messages so they don't appear as exceptions.
     drupal_get_messages();
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:99,代码来源:FormTest.php


示例17: formSubmitHelper

 /**
  * Helper function for the option check test to submit a form while collecting errors.
  *
  * @param $form_element
  *   A form element to test.
  * @param $edit
  *   An array containing post data.
  *
  * @return
  *   An array containing the processed form, the form_state and any errors.
  */
 private function formSubmitHelper($form, $edit)
 {
     $form_id = $this->randomMachineName();
     $form_state = new FormState();
     $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
     // 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_get_messages();
     $form_state->clearErrors();
     // Return the processed form together with form_state and errors
     // to allow the caller lowlevel access to the form.
     return array($form, $form_state, $errors);
 }
开发者ID:eigentor,项目名称:tommiblog,代码行数:36,代码来源:ElementsTableSelectTest.php


示例18: testHandleRedirectWithResponse

 /**
  * Tests the handling of a redirect when FormStateInterface::$response exists.
  */
 public function testHandleRedirectWithResponse()
 {
     $form_id = 'test_form_id';
     $expected_form = $form_id();
     // Set up a response that will be used.
     $response = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Response')->disableOriginalConstructor()->getMock();
     // Set up a redirect that will not be called.
     $redirect = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RedirectResponse')->disableOriginalConstructor()->getMock();
     $form_arg = $this->getMockForm($form_id, $expected_form);
     $form_arg->expects($this->any())->method('submitForm')->will($this->returnCallback(function ($form, FormStateInterface $form_state) use($response, $redirect) {
         // Set both the response and the redirect.
         $form_state->setResponse($response);
         $form_state->set('redirect', $redirect);
     }));
     $form_state = new FormState();
     try {
         $input['form_id'] = $form_id;
         $form_state->setUserInput($input);
         $this->simulateFormSubmission($form_id, $form_arg, $form_state, FALSE);
         $this->fail('EnforcedResponseException was not thrown.');
     } catch (EnforcedResponseException $e) {
         $this->assertSame($response, $e->getResponse());
     }
     $this->assertSame($response, $form_state->getResponse());
 }
开发者ID:Nikola-xiii,项目名称:d8intranet,代码行数:28,代码来源:FormBuilderTest.php


示例19: processForm

 /**
  * {@inheritdoc}
  */
 public function processForm($form_id, &$form, FormStateInterface &$form_state)
 {
     $form_state->setValues([]);
     // With GET, these forms are always submitted if requested.
     if ($form_state->isMethodType('get') && $form_state->getAlwaysProcess()) {
         $input = $form_state->getUserInput();
         if (!isset($input['form_build_id'])) {
             $input['form_build_id'] = $form['#build_id'];
         }
         if (!isset($input['form_id'])) {
             $input['form_id'] = $form_id;
         }
         if (!isset($input['form_token']) && isset($form['#token'])) {
             $input['form_token'] = $this->csrfToken->get($form['#token']);
         }
         $form_state->setUserInput($input);
     }
     // self::doBuildForm() finishes building the form by calling element
     // #process functions and mapping user input, if any, to #value properties,
     // and also storing the values in $form_state->getValues(). We need to
     // retain the unprocessed $form in case it needs to be cached.
     $unprocessed_form = $form;
     $form = $this->doBuildForm($form_id, $form, $form_state);
     // Only process the input if we have a correct form submission.
     if ($form_state->isProcessingInput()) {
         // Form values for programmed form submissions typically do not include a
         // value for the submit button. But without a triggering element, a
         // potentially existing #limit_validation_errors property on the primary
         // submit button is not taken account. Therefore, check whether there is
         // exactly one submit button in the form, and if so, automatically use it
         // as triggering_element.
         $buttons = $form_state->getButtons();
         if ($form_state->isProgrammed() && !$form_state->getTriggeringElement() && count($buttons) == 1) {
             $form_state->setTriggeringElement(reset($buttons));
         }
         $this->formValidator->validateForm($form_id, $form, $form_state);
         // \Drupal\Component\Utility\Html::getUniqueId() maintains a cache of
         // element IDs it has seen, so it can prevent duplicates. We want to be
         // sure we reset that cache when a form is processed, so scenarios that
         // result in the form being built behind the scenes and again for the
         // browser don't increment all the element IDs needlessly.
         if (!FormState::hasAnyErrors()) {
             // In case of errors, do not break HTML IDs of other forms.
             Html::resetSeenIds();
         }
         // If there are no errors and the form is not rebuilding, submit the form.
         if (!$form_state->isRebuilding() && !FormState::hasAnyErrors()) {
             $submit_response = $this->formSubmitter->doSubmitForm($form, $form_state);
             // If this form was cached, delete it from the cache after submission.
             if ($form_state->isCached()) {
                 $this->deleteCache($form['#build_id']);
             }
             // If the form submission directly returned a response, return it now.
             if ($submit_response) {
                 return $submit_response;
             }
         }
         // Don't rebuild or cache form submissions invoked via self::submitForm().
         if ($form_state->isProgrammed()) {
             return;
         }
         // If $form_state->isRebuilding() has been set and input has been
         // processed without validation errors, we are in a multi-step workflow
         // that is not yet complete. A new $form needs to be constructed based on
         // the changes made to $form_state during this request. Normally, a submit
         // handler sets $form_state->isRebuilding() if a fully executed form
         // requires another step. However, for forms that have not been fully
         // executed (e.g., Ajax submissions triggered by non-buttons), there is no
         // submit handler to set $form_state->isRebuilding(). It would not make
         // sense to redisplay the identical form without an error for the user to
         // correct, so we also rebuild error-free non-executed forms, regardless
         // of $form_state->isRebuilding().
         // @todo Simplify this logic; considering Ajax and non-HTML front-ends,
         //   along with element-level #submit properties, it makes no sense to
         //   have divergent form execution based on whether the triggering element
         //   has #executes_submit_callback set to TRUE.
         if (($form_state->isRebuilding() || !$form_state->isExecuted()) && !FormState::hasAnyErrors()) {
             // Form building functions (e.g., self::handleInputElement()) may use
             // $form_state->isRebuilding() to determine if they are running in the
             // context of a rebuild, so ensure it is set.
             $form_state->setRebuild();
             $form = $this->rebuildForm($form_id, $form_state, $form);
         }
     }
     // After processing the form, the form builder or a #process callback may
     // have called $form_state->setCached() to indicate that the form and form
     // state shall be cached. But the form may only be cached if
     // $form_state->disableCache() is not called. Only cache $form as it was
     // prior to self::doBuildForm(), because self::doBuildForm() must run for
     // each request to accommodate new user input. Rebuilt forms are not cached
     // here, because self::rebuildForm() already takes care of that.
     if (!$form_state->isRebuilding() && $form_state->isCached()) {
         $this->setCache($form['#build_id'], $unprocessed_form, $form_state);
     }
 }
开发者ID:komejo,项目名称:article-test,代码行数:98,代码来源:FormBuilder.php


示例20: submitForm

 /**
  * Form submit handler to flush Mollom session and form information from cache.
  *
  * This is necessary as the entity forms will no longer automatically save
  * the data with the entity.
  *
  * @todo: Possible problems:
  *   - This submit handler is invoked too late; the primary submit handler might
  *     send out e-mails directly after saving the entity (e.g.,
  *     user_register_form_submit()), so mollom_mail_alter() is invoked before
  *     Mollom session data has been saved.
  */
 public static function submitForm($form, FormState $form_state)
 {
     // Some modules are implementing multi-step forms without separate form
     // submit handlers. In case we reach here and the form will be rebuilt, we
     // need to defer our submit handling until final submission.
     $is_rebuilding = $form_state->isRebuilding();
     if ($is_rebuilding) {
         return;
     }
     $mollom = $form_state->getValue('mollom');
     $form_object = $form_state->getFormObject();
     // If an 'entity' and a 'post_id' mapping was provided via
     // hook_mollom_form_info(), try to automatically store Mollom session data.
     if (empty($mollom) || empty($mollom['entity']) || !$form_state->getFormObject() instanceof EntityFormInterface) {
         return;
     }
     /* @var $form_object \Drupal\Core\Entity\EntityFormInterface */
     $entity_id = $form_object->getEntity()->id();
     $data = (object) $mollom;
     $data->id = $entity_id;
     $data->moderate = $mollom['require_moderation'] ? 1 : 0;
     $stored_data = ResponseDataStorage::save($data);
     $form_state->setValue(['mollom', 'data'], $stored_data);
 }
开发者ID:isramv,项目名称:camp-gdl,代码行数:36,代码来源:FormController.php



注:本文中的Drupal\Core\Form\FormState类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP Form\FormStateInterface类代码示例发布时间:2022-05-23
下一篇:
PHP Form\ConfirmFormBase类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap