Im using form_alter on a views exposed filter form. There are 2 date fields (start-date and end-date) which are exposed filters that Ive hidden from the user. I want to populate the url argument of these 2 fields when the form is submitted.

Ive tried both methods using a submit and validation callback but neither seems to work.

My form_alter is:

function mymodule_form_views_exposed_form_alter(&$form, 
  FormStateInterface $form_state, $form_id) {
    if ($form['#id'] == 'views-exposed-form-my-form-id') {

  $form['#submit'][] = '_my_custom_submit';
  $form['#validate'][] = '_my_custom_validate';

My callback looks like:

function _my_custom_validate($form, FormStateInterface $form_state) {

  // Pass date range selection to date fields.
  $date_range = $form_state->getValue('date-range');
  $date_range_split = explode(":", $date_range, 2);
  $start_date = $date_range_split[0];
  $end_date = $date_range_split[1];

  $form_state->setValue('start-date', $start_date);
  $form_state->setValue('end-date', $end_date);

  $input = &$form_state->getUserInput();
  $input['start-date'] = $start_date;
  $input['end-date'] = $start_date;

When I dpm() any of my vars above I see the data but I can not get it passed into the url's arg on submit so I keep getting http://domain.com&start-date=&end-date=

How can I populate/modify the url args after the user clicks submit but before the page reloads?

If theres any other info that I can provide that may be helpful, please let me know.



You might have a logic-error in

$input['end-date'] = $start_date;

should be this:?

$input['end-date'] = $end_date;

How ever you can add a parameter with "query->add":

\Drupal::request()->query->add(['start-date' => $start_date, 'end-date' => $end_date]);

Note that you "mix" POST and GET - variable. So in your "submitForm" - method you need to process the GET - variables by yourself.

  • Thanks for the response @calar. Ah yes, you are right, that var should be $end-date. But \Drupal::request()->query->add() doesnt seem to be working. Ive been able to accomplish what i need by just updating the hidden fields with jquery. I was hoping there was a more drupal way to do this without js.
    – justclint
    May 23 '18 at 14:33

I was hoping there was a more drupal way to do this without js but ended up just using js to populate the fields before form is submit.

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.