Dynamic Forms with PHP

Dynamic Forms with PHP

Advert

Dynamic Form Processing with PHP

Dynamic Form Processing with PHP

In this tutorial we are going to create HTML forms with dynamically modifiable filed (or a set of fields) using Java Script & HTML Tables and PHP code to process them in the back end. The idea behind this demo is to make a form that is able to expand its fields on user requirement, we won't be focusing much on the design and the form field verification.

The Agenda of this article is to make a Form that can.

  • Allow user to add fields (or set of fields) as and when required.
  • The added fields can also be removed by the user within the set limits.
  • PHP script to fetch the data from the dynamically added field.

HTML

As we discussed earlier we won't be considering the design part as that is not in the agenda of this article, I have added some basic styles just to make it pleasant for human eyes.

The key idea in this method is to treat all the fields that are to be made modifiable by the user as a row of a table, using Java script we can replicate the rows as required. Just to make the article short and focus on the key areas only the HTML code for modifiable fields is shown below, you can get the full code in the file.

Although we are not concerned about form field verification HTML5 required="required" is used to force input here, it's advised to employ further verification with Java script or in the back end when using this on a production environment.

The key elements to be noted in HTML is to make the names of the modified fields end with square brackets [ ] , since these fields are treated as an array its a necessary to access the data in it.

<p> 
  <input type="button" value="Add Passenger" onClick="addRow('dataTable')" /> 
  <input type="button" value="Remove Passenger" onClick="deleteRow('dataTable')" /> 
  <p>(All acions apply only to entries with check marked check boxes only.)</p>
</p>
				
<table id="dataTable" class="form" border="1">
 <tbody>
  <tr>
	<p>
	<td >
		<input type="checkbox" name="chk[]" checked="checked" />
	</td>
	<td>
	<label>Name</label>
	<input type="text" name="BX_NAME[]">
	</td>
	<td>
	<label for="BX_age">Age</label>
	<input type="text" class="small"  name="BX_age[]">
	</td>
	<td>
	<label for="BX_gender">Gender</label>
	<select id="BX_gender" name="BX_gender">
		<option>....</option>
		<option>Male</option>
		<option>Female</option>
	</select>
	</td>
	<td>
	<label for="BX_birth">Berth Pre</label>
	<select id="BX_birth" name="BX_birth">
		<option>....</option>
		<option>Window</option>
		<option>No Choice</option>
	</select>
	</td>
	</p>
  </tr>
 </tbody>
</table>

You may have noticed the two input buttons, linked with Java script, The two function addRow('dataTable') and deleteRow('dataTable') is used to duplicate and remove the rows, we will see in detail below.

Java Script

The magic happens here, the functions addRow & deleteRow are called passing the Table ID in the argument to fetch the table details for the respective operations.


function addRow(tableID) {
	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;
	if(rowCount < 5){                            // limit the user from creating fields more than your limits
		var row = table.insertRow(rowCount);
		var colCount = table.rows[0].cells.length;
		for(var i=0; i <colCount; i++) {
			var newcell = row.insertCell(i);
			newcell.innerHTML = table.rows[0].cells[i].innerHTML;
		}
	}else{
		 alert("Maximum Passenger per ticket is 5");
			   
	}
}

function deleteRow(tableID) {
	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;
	for(var i=0; i<rowCount; i++) {
		var row = table.rows[i];
		var chkbox = row.cells[0].childNodes[0];
		if(null != chkbox && true == chkbox.checked) {
			if(rowCount <= 1) {               // limit the user from removing all the fields
				alert("Cannot Remove all the Passenger.");
				break;
			}
			table.deleteRow(i);
			rowCount--;
			i--;
		}
	}
}

Limiting Row addition : To limit the user for adding more than permissible fields / entry is essential, that is possible here too,rowCount stores the number of fields (rows) already created by the user and it can be used to limit the addition beyond your limit. In the example I have used 5 you can modify it to your needs.

Limiting Row Removal : Similar to the above function, it's also possible to prevent users from removing the rows completely, in the above code its already embedded, the limits are set to 1, again its modifiable.

PHP

Things here are fairly simple, non modifiable field is fetched as its done usually, but these fields will have an array of data regardless of whether the user used multiple fields or single field, all we need in is a loop to access them. In here I just echoed them out, there is no insertion into databases.


<?php if(isset($_POST)==true && empty($_POST)==false){ 
	$chkbox = $_POST['chk'];                              // array
	$bus = $_POST['bus'];
	$day = $_POST['day'];
	$month = $_POST['month'];
	$mob = $_POST['mob'];
	$type = $_POST['type'];
	$from = $_POST['from'];
	$to=$_POST['to'];
	$root=$_POST['root'];
	$BX_NAME=$_POST['BX_NAME'];        // array
	$BX_age=$_POST['BX_age'];	   // array		
	$BX_gender=$_POST['BX_gender'];    // array
	$BX_birth=$_POST['BX_birth'];	   // array
}				
?>

You may have noted that all the variable including modifiable fields are accepted just as a normal variable, but they arrays accessing them is a bit different, foreach loop is employed in the demo any loops will work fine.

For the demo I just echoed them on another page.
Regarding the check box we used for identification in Java script can also be used here for the same purpose as well.


<?php foreach($BX_NAME as $a => $b){ ?>
	<tr>
	<p>
		<td>
			<?php echo $a+1; ?>
		</td>
		<td>
			<label>Name</label>
			<input type="text" readonly="readonly" name="BX_NAME[$a]" value="<?php echo $BX_NAME[$a]; ?>">
		</td>
		<td>
			<label for="BX_age">Age</label>
			<input type="text" readonly="readonly" class="small"  name="BX_age[]" value="<?php echo $BX_age[$a]; ?>">
		</td>
		<td>
			<label for="BX_gender">Gender</label>
			<input type="text" readonly="readonly" name="BX_gender[]" value="<?php echo $BX_gender[$a]; ?>">
		</td>
		<td>
			<label for="BX_birth">Berth Pre</label>
			<input type="text" readonly="readonly" name="BX_birth[]" value="<?php echo $BX_birth[$a]; ?>">
		</td>
	</p>
	</tr>
<?php } ?>

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. How to Remove an App from Django Project

     
  2. Parse Time HH:mm:ss without date in javascript

     
  3. Software Testing

     
  4. Best WordPress Themes For Photographers And Photography

     
  5. Problems That Affect Conversion Rates

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.