?
Solved

Recognising dynamic form fields in PHP

Posted on 2009-07-16
17
Medium Priority
?
266 Views
Last Modified: 2013-11-10
Hi there, I have a form that contains an unknown number of dynamic fields in the format shown below, I would like to know how to group together the fields with the same id in PHP and loop through them so I can add each row to the database. An example of how to do this would be great thanks!


<div id='1'>
<label for='title1'>
<span class='label'>Name</span>
<input name='title1' type='text' id='title1' />
 
</label><label for='importance1'>
<span class='label'>Importance:</span>
<select id='importance1' name='importance1' size='1'>
<option value='primary'>Primary</option>
<option value='secondary'>Secondary</option>
<option value='optional'>Optional</option>
</select>
</label>
 
<label for='description1'>
<span class='label'>Description:</span><
textarea name='description1' id='description1'>
</textarea>
</label>
</div>
 
<div id='2'>
<label for='title2'>
<span class='label'>Name</span>
<input name='title2' type='text' id='title2' />
 
</label><label for='importance2'>
<span class='label'>Importance:</span>
<select id='importance2' name='importance2' size='1'>
<option value='primary'>Primary</option>
<option value='secondary'>Secondary</option>
<option value='optional'>Optional</option>
</select>
</label>
 
<label for='description2'>
<span class='label'>Description:</span><
textarea name='description2' id='description2'>
</textarea>
</label>
</div>
 
and so on...

Open in new window

0
Comment
Question by:cookiejest
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 3
  • +2
17 Comments
 
LVL 14

Expert Comment

by:flob9
ID: 24869992
<input name='title[1]' type='text' id='title1' />

[...]

<input name='title[2]' type='text' id='title2' />

etc

you will get:
$_POST =
Array
(
    [title] => Array
        (
            [1] => 123
            [2] => 456
        )

)
0
 
LVL 7

Expert Comment

by:ajkhalifa
ID: 24870082

The best easy way is to make the id of the field as a combination of name and number, like this:
<input name='phone_1' type='text' />
<input name='phone_2' type='text' />
<input name='phone_3' type='text' />
<input name='phone_4' type='text' />

and then in the action page:
$phones_arr=array();
for($i=1;1;$i++){
           if(!isset($_POST['phone_'.$i])
                      break;
           $phones[]=$_POST['phone_'.$i];
}
print_r($phones_arr);
0
 
LVL 14

Expert Comment

by:flob9
ID: 24870144
ajkhalifa>

<input name='phone[1]' type='text' />
<input name='phone[2]' type='text' />
<input name='phone[3]' type='text' />
<input name='phone[4]' type='text' />

$phones_arr = $_POST['phone'];
0
WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

 
LVL 2

Expert Comment

by:SaWey
ID: 24870171
You can use this:
$result = array();
foreach($_POST as $name => $value){
    if(substr($name, 0, 5) == 'title'){
        $result[substr($name, 5)]['title'] = $value;
    }elseif(substr($name, 0, 10) == 'importance'){
        $result[substr($name, 10)]['importance'] = $value;
    }elseif(substr($name, 0, 11) == 'description'){
        $result[substr($name, 11)]['description'] = $value;
    }
}
echo '<pre>';
print_r($result);
echo '</pre>';

Open in new window

0
 

Author Comment

by:cookiejest
ID: 24870431
hmm im not sure i understand, how would I group together all the fields for a given ID and loop through them though? I would like to use the array like so : title[]
0
 
LVL 14

Expert Comment

by:flob9
ID: 24870502
Let's claify my proposition :


<?php
	if(isset($_POST['title']))
	{
		foreach($_POST['title'] as $id => $title)
		{
			echo "Title $id = $ti <br/>";
	        echo "Importance $id = ".$_POST['importance'][$id]." <br/>";
	        echo "Description $id = ".$_POST['description'][$id]." <br/>";
		}
	}
  
?>
<form method="post">
<div id='1'>
<label for='title1'>
<span class='label'>Name</span>
<input name='title[1]' type='text' id='title1' />
 
</label><label for='importance1'>
<span class='label'>Importance:</span>
<select id='importance1' name='importance[1]' size='1'>
<option value='primary'>Primary</option>
<option value='secondary'>Secondary</option>
<option value='optional'>Optional</option>
</select>
</label>
 
<label for='description1'>
<span class='label'>Description:</span><textarea name='description[1]' id='description1'>
</textarea>
</label>
</div>
 
<div id='2'>
<label for='title2'>
<span class='label'>Name</span>
<input name='title[2]' type='text' id='title2' />
 
</label><label for='importance2'>
<span class='label'>Importance:</span>
<select id='importance2' name='importance[2]' size='1'>
<option value='primary'>Primary</option>
<option value='secondary'>Secondary</option>
<option value='optional'>Optional</option>
</select>
</label>
 
<label for='description2'>
<span class='label'>Description:</span><textarea name='description[2]' id='description2'>
</textarea>
</label>
</div>
 
<input type="submit" />
</form>

Open in new window

0
 
LVL 9

Expert Comment

by:rg20
ID: 24870504
HTML title alone without a subscript will give you a comma delimited string.  

On the next page a split function will give you an array.
0
 
LVL 14

Expert Comment

by:flob9
ID: 24870519
sorry typo :

echo "Title $id = $ti <br/>"; => echo "Title $id = $title <br/>";
0
 
LVL 7

Expert Comment

by:ajkhalifa
ID: 24870707
The very basic way is to make the id of the field as a combination of name and number, like this:
-------------------------------------------------------------------------
<input name='title_1' type='text' />
<input name='title_2' type='text' />
<input name='title_3' type='text' />
<input name='title_4' type='text' />
-------------------------------------------------------------------------
and then in the action page:
-------------------------------------------------------------------------
$titles_arr=array();
for($i=1;1;$i++){
           if(!isset($_POST['title_'.$i])
                      break;
           $titles[]=$_POST['title_'.$i];
}
print_r($titles_arr);
-------------------------------------------------------------------------
0
 
LVL 14

Accepted Solution

by:
flob9 earned 2000 total points
ID: 24870795
ajkhalifa> It makes no sense to do this since php already handle the name="identifier[id]" and give it in a post array.

0
 

Author Comment

by:cookiejest
ID: 24870933
flob I would like to use your method and I beleive that I have implemented it correctly but for some reason nothing is being passed through post... Is there any reason why dynamic fields would not be passed on submit through post? I have attached my full code below:
<script type="text/javascript">
function addFormField() {
	var id = document.getElementById("id").value;
		id = (id - 1) + 2;
		
	$("#requirementsrows").append("<div id='" + id + "'><label for='title" + id + "'><span class='label'>Name</span><input name='title[" + id + "]' type='text' id='title" + id + "' /></label><label for='importance" + id + "'><span class='label'>Importance:</span><select id='importance" + id + "' name='importance[" + id + "]' size='1'><option value='primary'>Primary</option><option value='secondary'>Secondary</option><option value='optional'>Optional</option></select></label><label for='description" + id + "'><span class='label'>Description:</span><textarea name='description[" + id + "]' id='description" + id + "'></textarea></label><br /><a href='#' onClick='removeFormField(\"#" + id + "\"); return false;'>Remove</a></div>");
 
	
	document.getElementById("id").value = id;
}
 
function removeFormField(id) {
	$(id).remove();
}
 
</script>
<?php include('header.php'); ?>
<p><a href="#" onClick="addFormField(); return false;">Add Requirement</a></p>
 
<form action="requirements.php" method="post" id="form1">
<fieldset>
<input type="hidden" id="project" value="<?php echo $_POST['q']; ?>">
<input type="hidden" id="id" value="0">
<div id ="requirementsrows"></div>
</fieldset>
<input name="submit" type="submit" />
</form>

Open in new window

0
 

Author Comment

by:cookiejest
ID: 24870947
Here is an easier to read layout of the form with the javascript:
<div id='" + id + "'>
<label for='title" + id + "'>
<span class='label'>Name</span>
<input name='title[" + id + "]' type='text' id='title" + id + "' />
 
</label><label for='importance" + id + "'>
<span class='label'>Importance:</span>
<select id='importance" + id + "' name='importance[" + id + "]' size='1'>
<option value='primary'>Primary</option>
<option value='secondary'>Secondary</option>
<option value='optional'>Optional</option>
</select>
</label>
 
<label for='description" + id + "'>
<span class='label'>Description:</span><
textarea name='description[" + id + "]' id='description" + id + "'>
</textarea>
</label>
<br />
<a href='#' onClick='removeFormField(\"#" + id + "\"); return false;'>Remove</a></div>

Open in new window

0
 
LVL 14

Expert Comment

by:flob9
ID: 24871132
use this php debug line at the beginning of the file :

print_r($_POST);
0
 
LVL 9

Expert Comment

by:rg20
ID: 24871338
Why not this

<input name='title' type='text' id='title" + id + "' />

In the next page, you will

array split ( title,"," )

This will give you a title array where you could use the index to associate the related fields;
0
 

Author Comment

by:cookiejest
ID: 24871447
The title array seems to pass correctly when I do print_r($_POST['title']); However the foreach does not seem to work?!
0
 

Author Comment

by:cookiejest
ID: 24871484
Ah ive managed to fix it, it was a silly error on my behalf, thank you for the help!
0
 
LVL 9

Expert Comment

by:rg20
ID: 24871711
What was the fix?
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question