I have a web app built with Zend Framework 1.12. I'm pretty comfortable using ZF1 forms, including its form validation machinery. I now need to create a form with a variable number of fields: it has a table with a fixed number of fields at the top, and a table with one empty row at the bottom. As values fill up the empty row, a new empty row appears, etc.
AFAIK, Zend_Form only supports a fixed number of fields in a form. So I resort to javascript, and it is relatively straightforward to detect when focus leaves one of the input elements in the variable-length table, and if there are no empty rows, add a new empty row. And I can scan the input values in all the rows of the table and report errors. This is good.
But the problem comes when the form is submitted. If my javascript has detected errors in the variable table, I can prevent the form from being submitted, because I have a submit button like this:
<a href="javascript:OSH.CheckAndSubmit()">Submit</a>
And OSH.CheckAndSubmit() looks like this:
OSH.CheckAndSubmit = function() {
if (OSH.divisionsOk()) {
document.getElementById('addevent').requestSubmit();
}
else {
return false;
}
}
So errors detected by my javascript prevent the form from being submitted. If there are no errors detect by my javascript, then the form is submitted, where the ZF1 validators go to work on the fixed fields in the form, and if errors are detected, they insert error messages near the erroneous fields, with the erroneous values still in place. But unfortunately, the filled-in rows in the variable-length table disappear.
I guess I could try reading a pile of ZF1 source code to try figure out how the values of the input fields are preserved on the form after it is submitted and the error messages get added, but I'm wondering if anyone here either knows how ZF1 forms accomplish this, or just how to get it done in general.
----EDIT---- It wasn't quite accurate to say that the filled-in rows disappear. Actually, everything added to the DOM by my javascript disappears when the form is submitted and then redisplayed with error messages from Zend_Form validation.
I can only think of two approaches to fixing this:
- Get rid of Zend_Form validation on the form and validate all of the fields in my javascript code. Certainly doable, but a bit annoying since I already have the Zend_Form validators in place and working.
- When the form gets submitted, if Zend validation detects errors, save the values from the variable table in Zend_Session. And when my javascript loads, issue an ajax request to get any values saved in the session, and, if so, create the variable table rows from those values. I guess this would also require a GET request to the same endpoint that displays the form to clear all variable table values from the session.
Having a hard time trying to decide between those two - but if someone has experience with this kind of thing and has a better suggestion, I'd love to hear it.