2

I have a form :

function buildForm(array $form, FormStateInterface $form_state) {
    $form['edit'] = array(
          '#type' => 'textfield',
    );
    $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Go'),
          //'#markup' => "<div><a href='?word=1'>Go</a></div>",
        );
    return $form;
}

Now I want is; when I submit form,$form_state->getValue('edit'); should get appended as a query parameter in form route.

Let's say my form route is:

mymodule.admin_page:
  path: '/mypage'
  defaults:
    _form: '\Drupal\mymodule\Form\myform'

And when I hit submit button of form, the route should get changed to /mypage?word=$form_state->getValue('edit').

I tried below approach, but it is throwing error:

Created 1 more route with a parameter:

mymodule.word:
  path: '/mypage/{word}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

And in my form submit function,

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

    $data = $form_state->getValue('edit');
    $url = Url::fromRoute('mymodule.word',['word'=>$data]);
    $form_state->setRedirectUrl($url);
   }

But when I hit submit button, it is giving me error,

Uncaught PHP Exception Symfony\Component\Routing\Exception\MissingMandatoryParametersException: "Some mandatory parameters are missing"

3

Stick with your original route definition:

mymodule.word:
  path: '/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

Then set your submit handler to this:

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

  $data = $form_state->getValue('edit');
  $url = Url::fromRoute('mymodule.word', [], ['query' => ['word' => $data]]);
  $form_state->setRedirectUrl($url);
}
  • tried, still giving same error, mandatory parameters are missing. – Sugandh Khanna Feb 8 '17 at 8:55
  • You either didn't put your route back to the original, or you didn't clear your cache. The path should be '/mypage' – Jaypan Feb 8 '17 at 8:56
  • Can you please share some other approach to achieve this? This is not working for me – Sugandh Khanna Feb 8 '17 at 9:18
  • There isn't another approach - how I told you to do it is how it's done! – Jaypan Feb 8 '17 at 9:18
  • I updated my code to show it all though. – Jaypan Feb 8 '17 at 9:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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