Search code examples
javaphpformsclassfill

Fill HTML Form with PHP data using field's ID as identifier


I have this array named $clientinfo:

[id] => 1
[dlastname] => Brown
[dfirstname] => George
[dmob] => 189328937
[dlandline] => 92839283

and so on... I want to populate this form:

<li class="hidden"><label for="did">unique id:</label><input id="did" type="text" name="did" style="background-color:gray" readonly="readonly" /></li>
<li class="firstcell"><label for="dlastname">lastname:</label><input id="dlastname" type="text" name="dlastname" /></li>
<li class="middlecell"><label for="dfirstname">firstname: </label><input id="dfirstname" type="text" name="dfirstname"  /></li> 
<li class="middlecell"><label for="dmob">mob </label><input id="dmob" type="text" name="dmob" /></li>

and so on...

I am able to fill the fields using php by adding this at the end of each input tag:

value="<?php echo isset($docinfo['dlastname']) ? htmlspecialchars($docinfo['dlastname']) : ''; ?>

This works fine, but it needs me to write something at the end of each line, which is ok if the form is small but I am working on one with at least 250 fields.

I was wondering, since the input ID is the same as the keys of the associative array, if there is an easier, more automated way to fill this cells I had two things in mind, one to import the array to java and then do

 document.INPUTID.value='$clientinfo[INPUTID]';

or something like that... but I cannot figure out the specifics and the second one was to somehow add a php command at each fields' code to write something like:

 value="<?php $id= $get_class($this); echo $clientinfo[$id]; ?>"

I dont really know how the $get_class works and it screwed up my code whenever I put it in there, but maybe someone could work something out to get the specific area's id?

I should mention i am very new at this, so you will find errors above and i will need a very detailed explanation.


Solution

  • if you have jQuery do this:

    <script type="text/javascript">
     <? foreach($yourArrayWithValues as $key=>$val) { ?>
           $('#<?=$key?>').val('<?=htmlspecialchars($val)?>');
     <? } ?>
    </script>
    

    otherwise do this with bare javascript:

    <script type="text/javascript">
     <? foreach($yourArrayWithValues as $key=>$val) { ?>
          document.getElementById('<?=$key?>').value = '<?=htmlspecialchars($val)?>';
     <? } ?>
    </script>