1

Is it possible to have a search form pass (into the search query) the field params of only fields that have been populated/selected? For example, if the following form is submitted, both q and color params are passed in the receiving template to which the form submits.

<form action="{{ url('search/results') }}">
    <input type="search" name="q">
    <select name="color">
        <option value="">Select a Color</option>
        <option value="black">Black</option>
        <option value="white">White</option>
    </select>
    <input type="submit" value="Go">
</form>

Output URL: http://mydomain.com/people/results?q=&color=

I have a search form that includes a lot of fields, so I want to only pass the params that are not empty or have been selected. This way, the URL that's passed is cleaner and less monstrous.

So in the example above, if the color dropdown isn't selected, the output URL would be http://mydomain.com/people/results?q=somequerystring

1

That's just the way forms work in html. If you don't want to use a POST method, (because that would make the results not URL-addressable at all), I'd recommend using an intermediary Twig template to perform a redirect based on what parameters exist - i.e., set your form action to search/process and in that template write a load of conditional statements to build up a query string to pass into a {% redirect %} tag which loads search/results.

If you don't want two templates, you could instead set your form method to POST and then in your search/results template you could conditionally perform a redirect to the same template appended with your custom query string, and use craft.app.request.method to distinguish between the request types to avoid an inifinte redirect loop.

| improve this answer | |
  • Gotcha. I was thinking there may have been a way to set up the conditionals on the form itself such that if a field was empty or not selected, the field name itself wouldn't be passed into the search query. But I guess that's not possible. – user3092 Sep 1 at 19:51
  • You could only do that with JavaScript - and it's probably not worth the technical debt. – James Smith Sep 1 at 20:50

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.