CakePHP dynamic form inputs - javascript

I'm using CakePHP 2.3.8 and I'm trying to create a form with dynamically added inputs from this tutorial but I'm having some issues. The adding and removing of inputs works just fine, but when I submit the form I get a black hole error message. Upon inspecting the inputs, it doesn't appear as if the key value isn't properly set and causing some issues with the id's of the inputs.
For example, with this code in an element
//Elements/users.ctp
$key = isset($key) ? $key : '<%= key %>';
<tr>
<td><?php echo $this->Form->input("Role.{$key}.user_id", array('options' => $users, 'label' => false)); ?></td>
<td class="actions">
Remove User
</td>
</tr>
this is the select that is generated
<select name="data[Role][0][user_id]" id="Role<%=Key%>UserId">
Edit
The value of $key is being set correctly on /Elements/users.ctp. I can create a row and echo the output of $key, and a number for the row appears correctly. As you can see above, the name of the element is set correctly, but the id is still being set strangely.
The name of the select element is being set properly, but not the id.
What is causing the select id to be Role<%=Key%>UserId rather than Role0UserId?

The Problem:
If you observe the generated select tag you posted in question, it shows
<%=Key%>
The variable expected by underscore library utilized by the tutorial you are using is
<%= key %>
CakePHP form input is replacing the html characters and space of that underscore variable, hence its not detectable by underscore library.
The Solution:
In order to fix the issue, you must use plain html code for the template part. Your grades.ctp must be as shown below (partial code for understanding)
<?php if (isset($key)) : ?>
<tr>
<td>
<?php echo $this->Form->input("Grade.{$key}.id") ?>
<?php echo $this->Form->input("Grade.{$key}.subject", array('label' => false)); ?>
</td>
</tr>
...rest of the code
<?php else: ?>
<tr>
<td>
<input type="hidden" id="Grade<%= key %>Id" name="data[Grade][<%= key %>][id]">
<div class="input text required">
<input type="text" required="required" id="Grade<%= key %>Subject" maxlength="200" name="data[Grade][<%= key %>][subject]">
</div>
</td>
...rest of the code
</tr>
<?php endif; ?>

Related

Populating Inputs Based on HTML Dropdown Selection

I know there are many questions like this one on Stack Overflow, but I am really needing something more related towards what I am doing...so that is why I am posting this question.
I have an HTML form with PHP that pulls data from an MSSQL database in order to populate a dropdown box. I want to be able to populate the contact information text boxes once I select a name from my dropdown box. So far, I have it to where, if I select a specific vendor, the vendor name gets entered automatically into the Name, Email, and Phone Number fields. However, I want to have different attributes entered into the text fields and not the vendor name itself. How could I do this?
The fields from my database with the name, email, and phone number that I want imported are named MR_POC_N, MR_POC_E, and MR_POC_P
Also the "MR_Name" that you see is the field with all names of the vendors FYI
Here is my code for the HTML dropdown:
<select name="vendor_dropdown" id="ven" onChange="updateinput();">
<option value="">Choose a Vendor</option>
<?php foreach($users->fetchAll() as $user): ?>
<option><?php echo $user['MR_Name'];?></option>
<?php endforeach; ?>
</select>
Here is my Contact Info code:
<table align="center">
<tr>
<td align="right">Name:</td>
<td><input class="textbox" type="text" id="name" name="name"></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input class="textbox" type="email" id="email" name="email"></td>
</tr>
<tr>
<td align="right">Phone Number:</td>
<td><input class="textbox" type="tel" id="tel" name="number"></td>
</tr>
</table>
Here is the update input function I have in JS. I know this is off but looking for some sort of direction as I am not the best in JS:
function updateinput() {
var e = document.getElementById("ven");
var venSelected = e.options[e.selectedIndex].value;
document.getElementById("name").value=venSelected;
document.getElementById("email").value=venSelected;
document.getElementById("tel").value=venSelected;
}
Keep your script the same as it currently is but change your JavaScript and the dropdown. In your dropdown try doing
<option value = "<?=$user['MR_Name'];?>"><?php echo $user['MR_Name'];?></option>
You want to make what's called an AJAX request. This will allow you to go off to another page get some data in your case you would be getting some user information, and return it to the page, without the user physically changing page!
Check this link out for more information on AJAX.
Your AJAX call will look something like this.
function updateinput() {
var e = $("#ven").val();
$.ajax({
url: "get-user-info.php",
type: "POST",
data: {e: e},
success: function(data){
data = JSON.parse(data);
var email = data[0];
var tel = data[1];
$("#email").val(email);
$("#tel").val(tel);
}
});
}
This script first gets the selected value of the dropdown. Then it starts the make the AJAX call, it's like submitting a form, we are POSTING the values across to the next page. So the page the AJAX will talk to is get-user-info.php it's posting the values from data. The data is sending across e which is what the dropdown value is. On success it will then do the code underneath which is saying parse data from a PHP array to JavaScript and then it is saying email is the first value of the array and tel is the second value from the array. Then we are saying the input with ID 'email' now equals email from the array and the input with ID 'tel' now equals tel from the array.
You will now need to create a php script in the same directory called get-user-info.php
In this script make a call to your database where the user is the same as the selected value e and return a PHP array that looks like this:
array(email, telephone)
This is pseudo-code for your PHP script get-user-info.php:
<?php
$e = $_POST["e"];
//Do your SQL
//In the loop
$array[] = $user["email"];
$array[] = $user["tel"];
echo json_encode($array);
?>

PHP echo javascript to change iframe source

I have a text input search form for support tickets. If the user inputs a ticket id (checked using a PHP if statement), the background color of the search box is changed to yellow (using a PHP echo) to highlight the search text entered. This part works.
I would like to also change the source value of an iframe as part of the PHP if condition like this:
<td align="left">
<input type="text" name="ticket" id="ticket" placeholder="Ticket" value="<?php echo $this->state->ticket;?>" class="input-mini search-query" onchange="document.adminForm.submit();"
<?php if ($this->state->ticket != "")
{
echo 'style="background-color: yellow;"';
echo '<script language="javascript">';
echo 'document.getElementById("ticketIframe").contentWindow.document.location.href="http://myurl.com"';
echo '</script>';
}?>/>
</td>
The javascript function (document.getElementById...) displays on the page rather than executing. I tried a simple javascript alert, but got the same result.
Suggestions?
Need to close the input tag before you insert script tag. You simply are generating invalid html that looks like:
<input <script></script> />
You get unexpected results when html is invalid

Getting value of select option php

I want to get a value of select option php on the same page. I brought selection list from database and listed them on the select. But even though I choose something on the list, it's not posted. Is there any problem in the code below? Thanks in advance.
<div class="ibox-content m-b-sm border-bottom">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label class="control-label" for="status">Search by category</label>
<form action="" method="POST" >
<select name="category" class="form-control">
<option value="" selected>All</option>
<?php
while($category = mysqli_fetch_array($result1)) {
// output data from each row
echo "<option value=\"{$category['categoryID']}\">{$category['name']}</option>";
}
?>
</select>
<input class="btn btn-primary" type="submit" name="submit" value="Search">
</input>
</form>
</div>
</div>
</div>
</div>
<?php
if (isset($_POST['submit'])) {
echo "Got it!";
echo $_POST['category'];
}?>
You should specify a name for the option:
<option name='category' value=\"{$category['categoryID']}\"...
And try adding action='#', and then it works:
array (size=2)
'category' => string '1' (length=1)
'submit' => string 'Search' (length=6)
Got it!1
And take care, in your code the option for 'all' has no value, and won't be displayed.
You have:
<?php
while($category = mysqli_fetch_array($result1)) {
// output data from each row
echo "<option value=\"{$category['categoryID']}\">{$category['name']}</option>";
}
?>
An array key -> inside a template var -> inside an option -> in a double-quoted string (which will parse vars), -> inside a while loop (which may or may not be running). That level of nested complexity will certainly decrease your time-to-debug and simplicity-to-debug.
I would first ignore the html entirely and:
$category = mysqli_fetch_array($result1)
var_dump($category, $category['categoryID'], $category['name']);
in naked php, to make sure that you have exactly what you need before you put anything into the html.
Also, form action='' sometimes causes problems, so make that and everything else you can explicit and fixed just while debugging.
I have to say that you're making things harder for yourself by not using a template engine, especially at the early stages. Your html+php is low-readability, and that decreases the ease of debugging. Use a clean template and it'll be easier to debug echoing issues, and as a side benefit you'll get easy escaping.

detecting input in dynamically generated input

My code dynamically generates a series of input fields. Each row of fields belongs to one database record and I use php's dynamic array notation ('[]') to capture the values.
Then at the input field i want to show the price input value that have been multiplied by total number of item that the data is generated from database.
I used javascript that placed inside foreach looping to detect the input and multiply it, but it only works for the first field, at the second field the multiplied value shown on the first field too.
this is the code structure :
<?php foreach ($barang->result_array() as $row): ?>
<tr>
<td><?php echo $row['nmbr']; ?> </td>
<td><?php echo $row['jumlah']?> </td>
<td><input id="pnwrn" type="text" name="pnwrn[]" value="" />
<input type="hidden" name="id_barang[]" value="<?php echo $row['id_barang']?>" />
<input type="hidden" name="jumlah[]" value="<?php echo $row['jumlah']?>" /> </td>
<td><div id="output"><script type="text/javascript">
var harga = <?php echo $row['jumlah']; ?>;
$('input').bind('input propertychange', function () {
$('#output').html($(this).val()*harga);
});
</script>
</div></td>
</tr>
<?php endforeach; ?>
I tried to make the output show the multiply value in each row but have no result yet..can someone tell me where i make my mistake?
thanks ~
There are several issues that others have pointed out in the comments.
The reason why every value on the page is changing is because you are using an id for the output div instead of a class and your jQuery change handler is saying: "get everything with an id of output and put this new html in it." Aside from that, it's not valid to use an id more than once on a page. So, change both the output and pnwrn to classes.
To make it simple to get the corresponding 'harga' value later, you can just store it as data on the input.
<?php foreach ($barang->result_array() as $row): ?>
<tr>
<td><?php echo $row['nmbr']; ?> </td>
<td><?php echo $row['jumlah']?> </td>
<td><input class="pnwrn" type="text" name="pnwrn[]" value="" data-harga="<?php echo $row['jumlah']?>" />
<input type="hidden" name="id_barang[]" value="<?php echo $row['id_barang']?>" />
<input type="hidden" name="jumlah[]" value="<?php echo $row['jumlah']?>" /> </td>
<td><div class="output"></div></td>
</tr>
<?php endforeach; ?>
The second issue is that you are writing a separate handler in every single table row. This is not only inefficient, it's hard to read the output and completely unnecessary. You just want your script once on the page so don't include it in your loop. To get to the corresponding values for your calculation, you can just retrieve the data value stored on the input. Then, you can use DOM traversal to find the corresponding output div. In this case, go up to the nearest ancestor row, then find its descendent element with the output class. Also, unless you are using a really old version of jQuery, use the on method instead of the deprecated bind.
<script type="text/javascript">
$('input').on('change', function () {
var harga = parseInt($(this).data('harga'));
$('this').parents('tr').find('.output').html($(this).val()*harga);
});
</script>

Submitting radio button values without page refresh

I'm currently having radio buttons to choose which payment the user want on the website, they can choose between (invoice, card, part payment(?)).
I'm using scripting to submit the radio buttons so no button is needed, however the page reloads every time they choose a different payment option, which is bad for the customer since they have to scroll down again to input the values of the form (phone number etc.) that appear when the radio button is selected.
So after a few complaints I've been trying to fix this issue to make the form appear without the page getting refreshed.
Is it possible to make a few changes in the scripting to make this possible?
Thanks in advance.
Here's the scripting i use:
function autoSubmit(){
var formObject = document.forms['choice_form'];
formObject.submit();
}
Here's the PHP: //I use the post values to show the form where you enter phone number and email
<?php
$value = '';
if(isset($_POST['choice'])) {
$value = $_POST['choice'];
}
?>
Here's the "radio" form:
<form name="choice_form" id="choice_form" method="post">
<table>
<tr>
<td>
<input type="radio" name="choice" <?php if ($value == 'faktura') { ?>checked='checked' <?php } ?> onChange="autoSubmit();" value="faktura"> Faktura
</td>
</tr>
<tr>
<td>
<input type="radio" name="choice" <?php if ($value == 'kort-direkt') { ?>checked='checked' <?php } ?> onChange="autoSubmit();" value="kort-direkt"> Kort / Direktbetalning
</td>
<tr>
<td>
<input type="radio" name="choice" <?php if ($value == 'delbet') { ?>checked='checked' <?php } ?> onChange="autoSubmit();" value="delbet"> Delbetalning
</td>
</tr>
</table>
</form>
If every time a payment option is selected a different form needs to appear underneath the radio buttons, you could render all forms in hidden state in individual <div>s, and then display the corresponding <div> every time an option is selected.
If you need to do something more complex than that, you will probably need to use AJAX.

Categories