This question has more to do with the process/logic I'm hoping to implement in terms of "SCALE" than how to write the code.
In WordPress, I have several forms that load as HTML and when the user creates a custom post (actually a new database entry for those not familiar with CMS) to record a new " event". I don't want to manually map everything as this is usingupdate_post_meta()
to set the name and value of the database entry/post - so when the form is submitted I use a php loopforeach ($_POST as $ name => $value) {
to populate all database tables for this event.
This works fine, but now, if the user saves the form and comes back to edit it later, I want the value to be echoed back like this if it exists:
Again, this approach works fine, but I have almost 500 fields on this page, so manually setting a unique variable for each field (in this case$reported_by
) would cost I would go a long way and would basically increase the codebase by almost 50%, making it unmaintainable and inefficient.
Any ideas on how to solve this problem? Understandably, I can build the form via php and echo it in HTML, but this also feels like a very manual process. PHP is server side, so I can't easily get the name value of the tag/input on the client side, unless using AJAX, but I feel like that would also become quite manual.
So no matter what, I'm faced with a lot of duplication of effort, unless there's a way to make this process easier to scale to all 500 fields without requiring me to manually set the variable names.
Thank you for your time!
The first thing to note is that you don't actually need to create a differently named local variable for each form input. In other words, there is no need to write like this:
You can write like this:
Why is this helpful? Because there are only two contents related tothisinput item:
Both of these are just strings, so they are easy to extract into PHP variables:
These look a lot likeparameters, so let’s turn this into a function, remembering to pass in
$incident_id
too: