Here’s the situation: I have a website with a complex address form with multiple inputs for house number, street, telephone, etc. This form is used in many different places around the site.
There are several different scenarios that will affect this form:
- Sometimes, the form will need to be displayed ‘fresh’, with all inputs blank awaiting a new address to be added
- Other times, the form will need to pre-populate itself with an address pulled from the database, for editing
- Lastly, the form might need to re-populate itself, if a user has entered an address, submitted the form, but forgotten to add their house number – in which case it needs to return what was just entered but display a form validation warning.
However…
- I want to only have one HTML form for addresses used across the entire site – to save repeating code
- I want this one form to be able to handle every different scenario shown above – to save repeating code
Here’s what a sample input for the form looks like:
<div class="input">
<input id="house_number" name="house_number" value="<?php echo set_value('house_number', $details->row('house_number'));?>"/>
<label for="house_number">House Number</label>
</div>
As you can see, this solves scenario 2 and scenario 3 – the code echo set_value($house_number, $details->row('house_number'));?> will, by default, pre-populate itself with the data drawn from the MySQL Resultset (1), or – if it detects something has already been submitted – re-populate itself with the previous data stored in house_number.
My question is: How can I build-in Scenario 1 to this as well, ideally without repeating any code, adding nested-ifs, etc? Whenever you load the form up ‘from scratch’, PHP understandably outputs errors about $details not being set – because there is nothing to pull through from the database or my model.
My model returns a MySQL Resultset but I was thinking could you initialise this resultset with a blank row? But I wasn’t sure if that was the correct way to go about it.
Thanks!
Jack
To prevent outputs errors about $details not being set, you should first check whether $details is null before using it. So you can have-
and then
Secondly, you’ll also need to keep posted values in session so that if an error occurs and user has to return to the form, you can retain the values previously posted. Remember, these values have not been stored in database yet.
So you can modify your code:
I Hope that helps.