0

I have a custom form with min and max price value:

    $form['price']['min'] = [
      '#type'          => 'hidden',
      '#default_value' => isset($_GET['price']['min']) ? $_GET['price']['min'] : '',
      '#attributes'    => ['id' => 'price-min'],
    ];

    $form['price']['max'] = [
     '#type'          => 'hidden',
     '#default_value' => isset($_GET['price']['max']) ? $_GET['price']['max'] : '',
     '#attributes'    => ['id' => 'price-max'],
    ];

and I would like the URL after the form is submitted to look like this:

/search?price%5Bmin%5D=5000&price%5Bmax%5D=10000

but actually it's coming out like this:

/search?min=5000&max=10000

How can I get the form values to appear in the URL in the required format?

  • 1
    Apart from your 'question' missing some details and the actual question, you should not use $_GET in your form, but get the parameters from the request object. – Mario Steinitz Aug 20 '18 at 16:16
  • Ok Mario like this: '#default_value' => $form_state->getValue('price[min]'); ? – Kipmag Aug 20 '18 at 16:33
  • This makes no sense. As soon as you have a form state with a valid value (after a submission of this form), it will be the actual value of this field anyway. If you like to initialize the default values from the request URL, you'd have to use the request object. See drupal.stackexchange.com/questions/207044/… – Mario Steinitz Aug 20 '18 at 16:41
  • There was a point to this question, which is addressed in my answer, but it does need editing for clarity. – Alfred Armstrong Aug 21 '18 at 13:16
2

Try adding:

$form['price']['#tree'] = TRUE;

This tells the form builder you want to nest field names. Otherwise it will just use the most immediate element keys for the field names, as you have found.

This is actually useful behaviour most of the time, as it means you can group fields in containers such as fieldsets without affecting their name attributes.

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.