1

I am using drupal 8 fapi and i have user case as below

I have a form on https://example.com/landing-page and I submit the form and there are validation errors .the page should reload as https://example.com/landing-page#lead-form.

Is there any hack we can implement?

I came with logic

if validation has error set form redirect page to example.com/landing-page#lead-form

if($form_state->getErrors() ) {
  $response = new TrustedRedirectResponse('example.com/landing-page#lead-form');
  $form_state->setResponse($response);
}

some how its not working.

Is there any way we can change the url to example.com/landing-page#lead-form and show the validation error at same time .

1
  • @jaypan if you can help me on this
    – Aditya
    May 26, 2017 at 16:28

2 Answers 2

0

You can use like

For Internal:

global $base_url;
$response = new TrustedRedirectResponse($base_url.'/landing-page#lead-form');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);

For External: Use full link

$response = new TrustedRedirectResponse('https://facebook.com');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);
0

You can use EnforcedResponseException to terminate form processing and redirect:

$response = new RedirectResponse(Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString());
throw new \Drupal\Core\Form\EnforcedResponseException($response);

For external urls use TrustedRedirectResponse not RedirectResponse:

$response = TrustedRedirectResponse('http://www.google.com');
throw new \Drupal\Core\Form\EnforcedResponseException($response);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.