setCached example

// @todo Remove this in https://www.drupal.org/node/2524408, because form     // cache immutability is no longer necessary, because we no longer cache     // forms during safe HTTP methods. In the meantime, because     // Drupal\system\Tests\Form still has test coverage for a poisoned form     // cache following a GET request, trick $form_state into caching the form     // to keep that test working until we either remove it or change it in     // that issue.     if ($this->getRequest()->get('immutable')) {
      $form_state->addBuildInfo('immutable', TRUE);
      if ($this->getRequest()->get('cache') && $this->getRequest()->isMethodCacheable()) {
        $form_state->setRequestMethod('FAKE');
        $form_state->setCached();
      }
    }

    return $form;
  }

  /** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($this->getRequest()->get('cache')) {
      

    $test_user->save();
    \Drupal::service('current_user')->setAccount($test_user);
  }

  /** * Tests queue injection serialization. */
  public function testQueueSerialization() {
    $form_state = new FormState();
    $form_state->setRequestMethod('POST');
    $form_state->setCached();
    $form_builder = $this->container->get('form_builder');
    $form_id = $form_builder->getFormId($this$form_state);
    $form = $form_builder->retrieveForm($form_id$form_state);
    $form_builder->prepareForm($form_id$form$form_state);
    $form_builder->processForm($form_id$form$form_state);
  }

}
$form_arg->expects($this->exactly(2))
      ->method('getFormId')
      ->willReturn($form_id);
    $form_arg->expects($this->once())
      ->method('buildForm')
      ->willReturn($expected_form);

    // Do an initial build of the form and track the build ID.     $form_state = (new FormState())
      ->addBuildInfo('files', [['module' => 'node', 'type' => 'pages.inc']])
      ->setRequestMethod('POST')
      ->setCached();
    $form = $this->formBuilder->buildForm($form_arg$form_state);

    $cached_form = $form;
    $cached_form['#cache_token'] = 'csrf_token';
    // The form cache, form_state cache, and CSRF token validation will only be     // called on the cached form.     $this->formCache->expects($this->once())
      ->method('getCache')
      ->willReturn($form);

    // The final form build will not trigger any actual form building, but will
    // the data that the text editor sends to any dialog is in the     // 'editor_object' key.     if (isset($form_state->getUserInput()['editor_object'])) {
      $editor_object = $form_state->getUserInput()['editor_object'];
      // The data that the text editor sends to any dialog is in       // the 'editor_object' key.       $media_embed_element = $editor_object['attributes'];
      $form_state->set('media_embed_element', $media_embed_element);
      $has_caption = $editor_object['hasCaption'];
      $form_state
        ->set('hasCaption', $has_caption)
        ->setCached(TRUE);
    }
    else {
      // Retrieve the user input from form state.       $media_embed_element = $form_state->get('media_embed_element');
      $has_caption = $form_state->get('hasCaption');
    }

    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="editor-media-dialog-form">';
    $form['#suffix'] = '</div>';

    
    // submissions. If the form receives its input via GET, then persisting     // state is forbidden by $form_state->setCached(), and the form must use     // the URL itself to transfer its state across steps. Although $form_state     // throws an exception based on the request method rather than the form's     // method, we base the decision to cache on the form method, because:     // - It's the form method that defines what the form needs to do to manage     // its state.     // - rebuildForm() should only be called after successful input processing,     // which means the request method matches the form method, and if not,     // there's some other error, so it's ok if an exception is thrown.     if ($form_state->isMethodType('POST')) {
      $form_state->setCached();
    }

    // \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()) {
      // We only reset HTML ID's when there are no validation errors as this can       // cause ID collisions with other forms on the page otherwise.       Html::resetSeenIds();
    }
      $form['name']['#value'] = '#value changed by #validate';
      // Alter the submitted value in $form_state.       $form_state->setValueForElement($form['name'], 'value changed by setValueForElement() in #validate');
      // Output the element's value from $form_state.       $this->messenger()->addStatus($this->t('@label value: @value', ['@label' => $form['name']['#title'], '@value' => $form_state->getValue('name')]));

      // Trigger a form validation error to see our changes.       $form_state->setErrorByName('');

      // To simplify this test, enable form caching and use form storage to       // remember our alteration.       $form_state->setCached();
    }
  }

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

}
\Drupal::service('current_user')->setAccount($test_user);
  }

  /** * Tests db log injection serialization. */
  public function testLoggerSerialization() {
    $form_state = new FormState();

    // Forms are only serialized during POST requests.     $form_state->setRequestMethod('POST');
    $form_state->setCached();
    $form_builder = $this->container->get('form_builder');
    $form_id = $form_builder->getFormId($this$form_state);
    $form = $form_builder->retrieveForm($form_id$form_state);
    $form_builder->prepareForm($form_id$form$form_state);
    $form_builder->processForm($form_id$form$form_state);
  }

}
// This form is special, in that the default values do not come from the     // server side, but from the client side, from a text editor. We must cache     // this data in form state, because when the form is rebuilt, we will be     // receiving values from the form, instead of the values from the text     // editor. If we don't cache it, this data will be lost.     if (isset($form_state->getUserInput()['editor_object'])) {
      // By convention, the data that the text editor sends to any dialog is in       // the 'editor_object' key. And the image dialog for text editors expects       // that data to be the attributes for an <img> element.       $image_element = $form_state->getUserInput()['editor_object'];
      $form_state->set('image_element', $image_element);
      $form_state->setCached(TRUE);
    }
    else {
      // Retrieve the image element's attributes from form state.       $image_element = $form_state->get('image_element') ?: [];
    }

    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="editor-image-dialog-form">';
    $form['#suffix'] = '</div>';

    
public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->assertTrue(TRUE);
    $form_state->setRebuild();
  }

  /** * Tests custom string injection serialization. */
  public function testDatetimeSerialization() {
    $form_state = new FormState();
    $form_state->setRequestMethod('POST');
    $form_state->setCached();
    $form_builder = $this->container->get('form_builder');
    $form_id = $form_builder->getFormId($this$form_state);
    $form = $form_builder->retrieveForm($form_id$form_state);
    $form_builder->prepareForm($form_id$form$form_state);
    // Set up $form_state so that the form is properly submitted.     $form_state->setUserInput(['form_id' => $form_id]);
    $form_state->setProgrammed();
    $form_state->setSubmitted();
    $form_builder->processForm($form_id$form$form_state);
  }

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

  /** * {@inheritdoc} */
  public function setCached($cache = TRUE) {
    $this->decoratedFormState->setCached($cache);

    return $this;
  }

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

  
->shouldBeCalled();

    $this->assertSame($buttons$this->formStateDecoratorBase->getButtons());
  }

  /** * @covers ::setCached * * @dataProvider providerSingleBooleanArgument */
  public function testSetCached($cache) {
    $this->decoratedFormState->setCached($cache)
      ->shouldBeCalled();

    $this->assertSame($this->formStateDecoratorBase, $this->formStateDecoratorBase->setCached($cache));
  }

  /** * @covers ::isCached * * @dataProvider providerSingleBooleanArgument */
  public function testIsCached($cache) {
    
FALSE,
    ];
    return $data;
  }

  /** * @covers ::setCached */
  public function testSetCachedPost() {
    $form_state = new FormState();
    $form_state->setRequestMethod('POST');
    $form_state->setCached();
    $this->assertTrue($form_state->isCached());
  }

  /** * @covers ::setCached */
  public function testSetCachedGet() {
    $form_state = new FormState();
    $form_state->setRequestMethod('GET');
    $this->expectException(\LogicException::class);
    $this->expectExceptionMessage('Form state caching on GET requests is not allowed.');
    
public function form_test_storage_page_cache_rebuild($form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }

  /** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Test using form cache when re-displaying a form due to validation     // errors.     if ($form_state->hasAnyErrors()) {
      $form_state->setCached();
    }
  }

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

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