Friday, February 17, 2012

Plone : Check if a form was submitted

I'm still continuing my journey with Plone.

Recently, I was implementing a search form in one of my templates. So, I wanted my form to submit to the same page but I didn't know how. The reason for wanting this feature was because I needed to enable certain parts of the page to be viewed i.e. the search results DIV, only when the form in the page has been submitted.

Below are the steps I used to achieve the functionality.

The Steps
I used a tal:condition and checked for data that is inside the request object upon form submission. To examine what is in the request object, simply put the following on your page:
<div tal:replace="structure request" />
Note: when the request object is called, it renders a readable, HTML version of the data. We use "structure" to prevent escaping the HTML.

Now, for my case, I needed to check whether my search form was submitted. So inside the DIV tag, I checked if the query string was empty or not. Below is a sample of the code:
<!-- Form has been submitted -->
<div tal:condition="python:request.environ.get('QUERY_STRING') != ''"></div>

<!-- Form has not been submitted -->
<div tal:condition="python:request.environ.get('QUERY_STRING') == ''"></div>

Note that you can use any variable you want. I simply chose to use the QUERY_STRING from the request object.

This might not be perfect, but I hope it will give direction to someone else.

UPDATE : 17-02-2012

You can also add a hidden field, name for example "submitedform" with value="1" and then, make a condition on :
request.get('submitedform', 0)

No comments:

Post a Comment