On Tuesday, April 26, 2011 10:12:57 AM UTC-4, jensk_dk wrote: > > I can get stuff done using web2py, but sometimes I have a little > trouble understanding exactly when controller code is called in > certain cases. For self-submitting forms, I'm not sure I quite get > it. > > My current understanding is that the controller function is called > twice. Once for generating the dict, that is passed to the html > template language and then once more when the form is submitted to > e.g. store the values from the form in the db and then redirect to > another page/controller function. It seems customary to control the > flow using form.accepts - the first time the function is call, > the .accepts method fails and the flow continues to the return dict, > to render the page and the second time to set db values and redirect > before the return. > > Am I spot on or way off?
That sounds about right. > If I'm correct here, I still have the > following questions: > > 1) Isn't all code before the form.accepts executed two times? Yes. > 2) How does the form know that the same page should be reloaded - is > there an implicit form action that is set to this by default? In the form tag, action="", which sends the form (back) to the current page. > 3) What happens if form.accept fails its validators on submitting - > doesn't the flow of code cause the same page to be rendered again? When validators fail, errors are added to the form for the failed field, so when the page reloads, the form will be re-displayed with the error messages showing. > The first question is important in a rather complex controller > function I'm messing with - copied below. As you can see, there's a > lot going on before the form.accepts. In general, if there's some code that's not necessary when the request is a form submission, you could probably put it inside an: if not request.vars: request.vars will be empty when the page first loads, but will include the form data when the form is submitted. You could get more specific by checking the value of request.vars._formname. In your case, though, I think you need that initial code to generate the form in order to then call form.accepts upon submission, so you can't just skip all that code. Instead, though, maybe you could store some of the results in the cache or session and conditionally pull from the cache/session upon submission. Anthony

