PHP generate multiple form fields - php

I am working on a system to edit/create an online food menu.
On the system that creates/edits the menu I would like the user to be able to enter a new item and price in two form fields and then press 'add another item' in turn this generates another form field. The user can keep pressing 'add another item' or simply submit the form.
Ideally it would keep generating forms fields then when the form is submitted an I handle the POST array and do the DB work.
I'm just not too sure on how I can allow the user to essentially keep adding form fields.
This is system is currently written in PHP.
Hi, Looking into this and my current code, this issue I see is that the form itself is also dynamically generated from database results. Your idea I can see working when I create an entirely new menu, but what if I want to edit a current menu and add a new item to it.
This is the code that generate the current form.
if($menuItems->count()) {
echo '<form class="updateMenu" action="" method="post">';
echo '<table class="gridtable gridtableMenu">';
echo '<tr><th>Item Name</th><th>Item Price</th></tr>';
foreach($menuItems->results() as $item){
echo '<tr>';
echo '<td class="menu-name"><input type="text" name="itemName[]" value="' . $item->item_name . '" required></td>';
echo '<td class="menu-price"><input type="number" step="any" name="itemPrice[]" value="' . $item->item_price . '" required></td>';
echo '<input type="hidden" name="id[]" value="' . $item->id . '">';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="updateMneu" value="Update Menu">';
echo '</form>';
} else {
echo '<div class="error">No items have been added to this menu</div>';
}

Related

Check form before submit

The form/table filled with data based on the the status. So the rows in the table are build dynamically.
What i want is that the person who wants to submit the form, has filled in the three fields (STIN / STOUT / REASON) (are dropdown menu's) and the field ITEM must be filled in from the database (not a user input).
If it was one row i think it would be easy, but it depends on the status of an order how many rows it will display and depends on the field ITEM if it has an ITEM.
Example:
Row 1 has the item STIN is selected STOUT is selected REASON is
selected
Row 2 has no item STIN is selected STOUT is selected REASON is
selected
Row two or row 3 with no item must be checked and all the other available rows must be checked when the generate xml button is clicked.
<?php
while ($row = sqlsrv_fetch_array($result)) {
$S1 = $row['Qty_ExchangeStock'];
$S2 = $row['Qty_InService'];
$S3 = $row['Qty_TotalStock'];
$status = '1';
$Stock = $S1 - $S2;
if ($Stock < 1) {
$status = '2';
$Stock = 0;
}
echo '<tr>';
echo '<td><input type="text" name="SONR-'.$counter.'" value="'.$row['No_'].'" size="6" readonly /></td>';
echo '<td><div>'.$row['Brand']. '</div></td>';
echo '<td><div>'.$row['Model']. '</div>';
echo ' <input type="hidden" name="SIGC-'.$counter.'" value="'.$row['Service Item Group Code']. '" /></td>';
echo '<td><input type="text" name="ITEM-'.$counter.'" value="'.$row['Item No_'].'" size="8" readonly /></td>';
echo '<td class="center"><div>'.$Stock. '</div></td>';
echo '<td class="center"><div>'.$row['Claim']. '</div></td>';
echo '<td><input type="text" class="small" maxlength="20" placeholder="Serienummer" name="SNR-'.$counter.'" /></td>';
echo '<td><input type="text" class="small" maxlength="10" placeholder="Approval NR" name="APPNR-'.$counter.'" /></td>';
echo '<td><select id="check" name="STIN-'.$counter.'" class="small">'.$ruilin.'</select></td>';
echo '<td><select name="STOUT-'.$counter.'" class="small">'.$ruiluit.'</select></td>';
echo '<td><select name="REASON-'.$counter.'" class="small">'.$dropdown.'</select></td>';
echo '<td><input type="text" maxlength="70" title="Opmerking: maximaal 80 tekens" name="OPM-'.$counter.'" /></td>';
echo "</tr>\r\n";
$counter++;
}
?>
</tbody>
</table>
<input type="submit" value="Generate XML">
</form>
</div>
</div>
<?php
}
?>
You probably want to start off with server-side validation. The reason is people can turn off validation or use scripting to make calls and you need to be able to validate the logic properly on the server.
In this case you need to define a server-side API (what data does the server have to know?), check and document it. But that starts with design and I don't think you are there yet.
Once you have that done you can add similar checks in Javascript. This improves user experience but it is no replacement for server-side checks.

Can't pass hidden form value from database to PHP if-statement

My database table (Related) contains 3 columns:
related_id
article_id
object_id
It's a table which keeps track of relationships between articles and objects. I have stripped the code. Now it just contains the delete button (x). If someone press that button I want the user to be redirected to if(isset($_POST['deleteRelated'])) to get a "Are you sure"-message etc. But the hidden ID isn't passed correctly. The last related_id in the table is 29. When I try to echo out the hidden ID i just get 29 for every delete button (x).
The complete version of the code below gives me a table with the article title, object title and the delete button (x). Because of a submit button can't pass a value by itself I need a hidden value. But when I pass it by pressing the delete button (x) i just gets 29 every time.
Code
if(isset($_POST['deleteRelated'])) {
echo $_POST['hidden-id']; // Will just display the last 'related_id' value.
else {
echo '
<form method="post">';
$stmt = $db->prepare("SELECT * FROM Related");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $related) {
echo '
<input type="hidden" name="hidden-id" value="' . $related['related_id'] . '">
<input type="submit" name="deleteRelated" value="x">';
}
echo '
</form>';
}
If I type:
<input type="submit" name="deleteRelated" value="' . $related['related_id'] . '">
It will display the correct value from the database instead of the x for the delete/submit button. But when I press the delete/submit button I just get the last related_id which is 29.
Can someone solve this problem? Should not be that hard?
Explanation
You have one <form> for the entire table, which includes (say) a dozen <input type="hidden" name="hidden-id" value="...">s.
Those values will ALL be sent to the server when the form is submitted (how do you expect it to know to only send the hidden-id which is next to the specific submit button that was pressed?) This is why you are only seeing the last hidden-id – they are all being sent, so the final one overrides/wins.
Solution
One solution would be to have a <form> per row instead of one <form> for the whole table:
foreach ($result as $related) {
echo '<form method="POST" action="...">';
echo '
<input type="hidden" name="hidden-id" value="' . $related['related_id'] . '">
<input type="submit" name="deleteRelated" value="x">';
echo '</form>';
}
That way, only the hidden-id value of the pressed button would be sent.
Alternatively, you really don't need a form for each row, you could use a button here instead and ditching those hidden inputs.
Example:
foreach ($result as $related) {
echo '<button type="submit" name="deleteRelated" value="' . $related['related_id'] . '">Delete</button>';
}
So now each value of that pressed button on each row will go to:
$related_id = $_POST['deleteRelated'];
You will have to put the in the foreach.
In your code, you have one form with a lot of button submit.
Try this:
foreach ($result as $related) {
echo '
<form method="POST" action="...">
<input type="hidden" name="hidden-id" value="' . $related['related_id'] . '">
<input type="submit" name="deleteRelated" value="x">
</form>';}
If I understood you right, why do you need multiple hidden inputs?
you might want to put this input once:
<input type="hidden" name="hidden-id" value="" />
Next, change the submit button to something like this:
echo '<input type="submit" name="deleteRelated" value="x" onclick="setValue('" . $related['related_id'] . "'); />';
And use a js function:
setValue(val) {
document.getElementsByName("hidden-id")[0].value = val;
}
Easy solution: Put your form tag inside foreach loop
$stmt = $db->prepare("SELECT * FROM Related");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $related)
{
echo '<form method="post">';
echo '
<input type="hidden" name="hidden-id" value="' . $related['related_id'] . '">
<input type="submit" name="deleteRelated" value="x">';
echo '</form>';
}

When and how to insert data into DB on a Joomla page

I'm altering an existing Joomla 2.5 component and I wish to add data to a specific table (already existent upon install) to a couple custom columns.
So, I have this view (_quizInfo.php on the quiz view folder) code which consists of a form that displays some information (retrieved from the DB) and to proceed upon a checkbox being checked to another view (the quiz view). (Basically, it's a couple JS lines enabling the "proceed" button).
Heres the (simplified) code:
<?php defined( '_JEXEC' ) or die( 'Restricted access' ); ?>
<script type="text/javascript" language="javascript">
function proceed()
{
check = document.getElementById('checkToProceed') ;
proceedButton = document.getElementById('proceedButton') ;
if (check.checked) {
proceedButton.disabled = false ;
} else {
proceedButton.disabled = true ;
}
}
</script>
<form name="quiz_info" method="post">
<?php
echo '<div class="items-row"><div class="item">';
echo '<h2>' . JText::sprintf('YOU_HAVE_CHOSEN_TO_TAKE_QUIZ', '"'.$this->quiz- >title.'"') . '</h2>' ;
echo '<ul>' ;
...
echo '</ul>' ;
$option = JRequest::getCmd('option');
$link = JRoute::_('index.php?option='. $option . '&controller=quiz&layout=default') ;
echo '<p><input type="checkbox" id="checkToProceed" name="checkToProceed" onclick="proceed();" /><label for="checkToProceed">' . JText::_('I_HAVE_READ_AND_UNDERSTOOD') . '</label></p>' ;
echo '<input id="proceedButton" name="proceedButton" disabled="true" value="' . JText::_('PROCEED_TO_QUIZ') . '" type="submit" />' ;
echo '</div></div>';
?>
<input type="hidden" name="option" value="com_jquarks" />
<input type="hidden" name="id" value="<?php echo $this->quiz->id ; ?>"/>
<input type="hidden" name="task" value="showQuiz" />
<input type="hidden" name="view" value="quiz" />
<input type="hidden" name="layout" value="default" />
<?php echo JHTML::_( 'form.token' ); ?>
Now, I've added a form to this page so a user can fill out his/her data and then proceed (I need this data at this step to be stored), so now besides the code already showed I've added the following lines on the form tag:
//Added
echo '<li><p>' . JText::sprintf('Before proceeding you must fill the form bellow:') . '</p></li>' ;
echo '<div style="width: 50%; border: 1px solid; padding: 15px;"><form><div style="width: 100px">Full Name: </div><input type="text" name="fullname" style="width: 100%;"><br/><div style="width:100px"><br>ID document: </div><input type="text" name="iddoc" style="width: 100%;"></form></div>';
//END Added
I've noticed that the form is of POST type but there is no action defined.
The quiz view then stores all the necessary data before displaying the quiz (on the intended table) but I don't know how to proceed to store the _quizInfo view form data in the DB since it apparently isn't supposed to store anything.
The "session" is only stored (on the corresponding table) after clicking proceed and the quiz view is called.
Can anyone point me in the right direction? Not really comfortable with the way Joomla handles DB calls.
-Should I capture the POST data on the default.php file of the quiz view?
-Should I store the form data immediately?
Any help would be greatly appreciated.
Best Regards
Well, I eventually found the answer to my question, which I'm leaving here for anyone who needs it:
Any data that gets passed as POST or GET, even without a clear target/action definition (since we're working with MVC) can be accessed by using JRequest::getVar() or JRequest::get(), as mentioned in the documentation here: http://docs.joomla.org/Retrieving_and_Filtering_GET_and_POST_requests_with_JRequest::getVar

generating dynamic select box after form submit

Im building an upload form where a user can upload a document along with details about the document such as its name etc. The issue that I am having is that when a user selects a category using a select I have to generate another select which then gives the user the option of choosing a sub category. see the following:-
$(".department").change(function() {
var url = "includes/get-categories.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#upload-modal").serialize(), // serializes the form's elements.
success: function(data){
//this is where the select is generated
$(".sub").html(data); // show response from the php script.
//The alert works but the above line does not
alert("yeahhhhhhhhhhhhhhh boi");
}
});
Now this works like it should in that when the select is changed it generates another select from get-categories and gives the user another select box. But for some reason when a user submits the form and they are presented with a list of errors in the form (fields left blank etc) the select box will no longer be generated by selecting a category. I even tested the code with an alert which did work so im really confused as to why the following line doesnt work
$(".sub").html(data);
Here is my form which is pretty standard
echo "<form enctype='multipart/form-data' action='".$_SERVER['PHP_SELF']."' method='POST' autocomplete='off' id='upload-modal'>";
echo '<fieldset>';
echo '<legend>Please fill in all the fields below:- </legend>';
echo '<label for="docname">Document name</label>';
echo '<input class="block" type="text" name="docname" id="docname" value="'.$_POST['docname'].'" />';
echo '<label for="version">Version (if left blank it will be entered as 1.0)</label>';
echo '<input class="block" type="text" name="version" id="version" value="'.$_POST['version'].'" />';
//We need to now give a drop down for the admin to select a department
try {
$conn = new PDO(DB_HOST,DB_USER,DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT X FROM Y WHERE Z = :id');
$stmt->execute(array('id' => A));
while($row = $stmt->fetch()) {
// if the user is an admin we provide them with the admin link
if($row['admin_level']=="super" || $row['admin_level']=="admin" && $row['department']=="Assurance" ){
echo '<select id="department" class="block department" name="department">';
echo '<option value="0">department...</option>';
echo '<option value="policies">Policies</option>';
echo '<option value="procedures">Procedures</option>';
echo '</select>';
}
echo '<p class="sub"></p>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo '<label for="keywords">Enter keywords (seperate with ",")</label>';
echo '<textarea id="keywords block" name="keywords" rows="4" cols="50" value="'.$_POST['keywords'].'"></textarea> ';
echo '<label for="filename">Supported formats - .docx & .pdf</label>';
echo '<input type="file" name="filename" id="filename" title="Supported formats - .docx and .pdf" />';
echo '<input class="submit-ie6" type="submit" name="submit" value="Upload" id="upload-modal-submit" />';
echo '</fieldset>';
echo '</form>';
Any help is most appeciated
Try using a tool like Firebug and see why after the submit, this: $(".sub").html(data); does not work. The reason probably is because after you submit the form(with errors) the:
echo '<p class="sub"></p>';
is not there.
I would suggest the below:
Get your
<p class="sub"></p>
out of try{} and just use css like:
<p class="sub" style="display:none;"></p>
So all you have to do, is when the user selects a category, create the second select box and remove the display:none from the p like:
$(".sub").html(data);
$(".sub").show();

Assign every TD in PHP While Loop Table a Link

I have a while loop that retrieves info from the mysql db. Now there is a column called profile. So I want every <td> in the profile to be a button that would have an action which would lead to a PHP page. How do I do that?
<form action="profile.php" method="get">
while($result)
{
echo '<table>';
echo '<tr>';
echo '<td>';
echo $result['profile'];
echo '</tr>';
echo '</td>';
echo '</table>';
}
Now every $result['profile'] should be a submit like - <input type="submit">
Thanks.
rewrite
echo $result['profile'];
to this code:
echo ''.$result['name'].'' ;
First of all,
echo '</tr>';
echo '</td>';
should be:
echo '</td>';
echo '</tr>';
To add a Submit button, change
echo '<td>';
to
echo '<td><input type="Submit" value="Submit">';
and
echo '</td>';
to
echo '</input></td>';
You will need to add the appropriate attributes to the submit button if applicable. Also, you will need to surround the submit button with a form element. Whether each link has its own form, or the entire table is surrounded by one is up to you.
Edit
To surround the table with a form tag, change echo '<table>'; to echo '<form><table>';. Then, change echo '</table>'; to echo '</table></form>';. Submit buttons are automatically "linked" to the form element they are contained in. All you have to do is to define the form action.
Edit
Actually, because you are using a GET request, this entire thing can be simplified by using links instead of forms. So go with RAMe0's answer.

Categories