I have a list of organizations in a DDL where the Text displays the full name of each organization and the Value is the key for that organization. I need both the full name and the key entered into my database when an organization is selected. I have been unable to access both the Value and the Text using PHP, so I ended up stringing the full name and key together in the Value field and using Explode to split them into different variables (see below). Is this the best way to do this? I want to make sure I'm not overlooking something cleaner and simpler.
HTML:
<form method="post" action="submit.php" name="requestDetailsForm">
<label>Organization Name:</label>
<select id="org_name" name="org_name">
<option value="Organization 1.abc">Organization 1</option>
<option value="Organization 2.def">Organization 2</option>
</select>
<input type="Submit" value="Submit">
</form>
PHP:
<?php
$org_name = mysql_escape_string($_POST['org_name']);
$org_name_split = explode('.', $org_name);
$org_name_full = $org_name_split[0];
$org_name_key = $org_name_split[1];
$strSQL = "INSERT INTO Database(org_name_full, org_name_key) VALUES ('$org_name_full', '$org_name_key')";
?>
I would use jQuery to do this one, I would add a hidden element and assign the value as the option's text value on form submission.
<form method="post" action="submit.php" name="requestDetailsForm">
<label>Organization Name:</label>
<select id="org_name" name="org_name">
<option value="Organization 1.abc">Organization 1</option>
<option value="Organization 2.def">Organization 2</option>
</select>
<input type='hidden' name='option_text'value='' >
<input type="Submit" value="Submit">
</form>
<script type="text/javascript">
$('form').on('submit', function(e){
e.preventDefault();
var text = $('#org_name').find(":selected").text();
$('input[name="option_text"]').val(text);
$('form').submit();
});
</script>
There is no way to access both the selected value and the name through something like the $_POST array.
However, what I would generally do in a situation like this is create a table in the database of all possible organizations with their names and codes. In PHP, I would generate the list of select options using SELECT * on that database when generating the HTML for the original page. Then, when the data is submitted you just insert the organization code into the second table that you're dealing with. When you need to know the full organization code and name associated with the record in that table, you use a JOIN statement.
For example, say the original database that you're dealing with now represents users and each user has an organization. When someone submits the form, you insert a new user record into that table and insert the organization code into an organization_id field in that same users table. Then, when you want to know the organization code and name for a given user, you do SELECT * FROM users LEFT JOIN organizations ON user.organization_id = organization.id WHERE user.id = blah. This will return the user record along with their organization code and name.
This is the best way when only using PHP.
A possible improvement could be to improve how you split the POST in variables:
list($org_name_full, $org_name_key) = explode('.', $org_name);
Otherwise you should use javascript to add either variable you need to the post
Related
This is a bit hard for me to explain and I don't really have any examples to show as I don't know how to do it.
What I am trying to do is to have fields automatically filled up for me based on my selection which is taken from my database.
Let's say I'm trying to fill data up for a casualties form and I'm getting my selection for my fields from a people's database and that database contains all the information of everybody inside, information such as the contact number, next of kin, full name, their IC etc etc.
Is there a way to display data such contact number, next of kin, IC number based on let's say their name inside the form itself?
$query = "SELECT * FROM staff";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
.... in the form itself
<tr>
<td><label><b>Staff ID</b></label></td>
<td><select name="staffID"><option value="">Select staff ID</option>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['staff_id']; ?>">
<?php echo $row['staff_id']; ?>
</option>
<?php } ?>
</select></td>
</tr>
The idea is, after they selected an ID from the dropdown box, additional fields will appear, giving the user more details of the staff such as their full name, contact number etc etc.
I can echo out all their ID and I know how to generate out additional fields but I don't know how to auto fill up data on those fields based on the staff_ID they selected.
Sorry if this is confusing, english is not my main language and I'm pretty terrible with programming
English is not my natural language (i`m from brazil).
In this case you will need to use AJAX. The easier way to do that is using Jquery (www.jquery.com). I will put here the easier way, but if cant help, tell me again.
---Let`s go --------------
<option id="reportedBy" name="reportedBy">
<option value="staff" data-name="Full Name of Staff" data-no="(222)2222-2222">
</option>
So you will make a script using jquery. When this option change his value, you will get the selected option value and get the others data using the dataset.
<script>
$(document).ready(function(){
$("#reportedBy").change(function(){
name = $(this).find(":selected").data("name"); //data-name less data-
no = $(this).find(":selected").data("no"); //data-no less data-
//Assuming your textfilds use the id "name" and no
$("#name").val(name);
$("#no").val(no);
});
});
</script>
I'm having a problem with the coding because I cannot get the chosen dropdown menu multi-select Version 1.4.2 to retrieve the previous selected subject value(s) from the dropdown menu when I click it again to activate it.
I'm using two different tables with one field name for each one, so I'm trying to match the t_subjects field name(s) in the member table with the name field name in the category table and if there is a match, that subjects field name will result in <option value='subject_name' selected >subject_name</option> and where there is no match it will be <option value='subject_name'>subject_name</option>
This is what I'm trying to get to happen for those subjects that match when I click it anytime after the first post.
There are forty-two subjects that are dynamically loaded in a chosen multi-select dd menu option.
I have no problem with posting the subject(s) names to the database using the implode method.
if(isset($_POST['submit']))
{
$subjects = implode(',', $_POST['subjects']);
But, if I open the page again to make another post with the subjects field name blank, I get an error that says:
Warning: implode() [function.implode]: Invalid arguments passed in...
So, you can see why I need to have the previous subject(s) values selected when I activate it again. Here is the code for the chosen dd menu.
<tr>
<td width="32%">Subjects:</td>
<td width="68%">
<input type="radio" name="utype" id="sutype" value="s" />Subject(s)
<div id="studspan" style="display:none;">
<strong style="vertical-align:top;">Select Subject(s) :</strong>
<select name="subjects" id="subjects" data-placeholder="Select Subject(s)" style="width:350px;" multiple class="chosen-select">
<?php
$cat_sele = mysql_query("SELECT * FROM category");
while ($cat_row=mysql_fetch_array($cat_sele)) {
if($_POST['subjects'] == $cat_row['name']) $s = " selected"; else $s = "";
echo "<option value='{$cat_row['name']}'$s>{$cat_row['name']}</option>";
}
?>
</select>
</div>
The problem seems to be in this part of the code: if($_POST['subjects'] == $cat_row['name']), because when I replace $_POST['subjects'] with 'Accounting' to check it, it will show that Accounting has been selected when I activate it again, but if I add another subject name, it will show all of the subjects as selected. I even tried if($_POST['t_subjects'] == $cat_row['name']) as well as ("SELECT name FROM category"), but they didn't work either. So any help to help this teacher make it work will be very appreciative.
I have also included other parts of the code that are involved in the process too.
elseif($_SESSION['user_type']=="m")
{
$getuser_sele = "select * from member where member_id = '".$_SESSION['ses_id']."'";
$getuser_qry = mysql_query($getuser_sele);
$getuser_row = mysql_fetch_array($getuser_qry);
$subjects = stripslashes($getuser_row['t_subjects']);
=============================================================
elseif($subjects=="" && $_SESSION['user_type']=="m")
{
$error="Please Enter Preferred Subjects";
}
=============================================================
elseif($_SESSION['user_type']=="m")
{
$qr=mysql_query("update member set
t_subjects='".addslashes($subjects)."',
=============================================================
<body onload="$('.chosen-select').show();
$('.chosen-select').chosen();">
=============================================================
<script type="text/javascript">
$("#sutype").click(function () {
$("#studspan").show(1000);
$('.chosen-select').chosen('destroy');
$('.chosen-select').show();
$('.chosen-select').chosen();
});
</script>
<script src="js/chosen.jquery.js" type="text/javascript"></script>
=============================================================
Update:
Tristan, it works but it shows all of the subject names as selected and de-seleted in the choice list, which is not what I want to happen. I also got the following error in the source code for each of the subject names. I'm just showing the first one below.
<b>Warning</b>: array_search() expects parameter 2 to be array, null given in <b>/home/.../.../edit.php</b> on line <b>2784</b><br /> <option value='Accounting' selected>Accounting</option><br />
I think the problem is how the table/fields are setup in the dbase.
Here is what should happen based upon the first row of the t_subjects. If I log in as member 1 and open the chosen dd menu, Accounting,Athletics,Art from row one of t_subjects should be selected while the rest of the subject list would be non selected in the chosen dd menu. This would happen for each member's row t_subjects they have listed when they initially posted them the first time.
all images to show what I'm talking about.
Using <select name="subjects" ... multiple> will only send post data for one selection. You need to use <select name="subjects[]" ... multiple> to send all selected options in the post data.
Then $_POST['subjects'] will be an array so you will need to search the array for the category name.
$cat_sele = mysql_query("SELECT * FROM category");
while ($cat_row=mysql_fetch_array($cat_sele)) {
if(array_search($cat_row['name'], $_POST['subjects']) !== false) $s = " selected"; else $s = "";
echo "<option value='{$cat_row['name']}'$s>{$cat_row['name']}</option>";
}
I am unable to figure it out on how to retain select option value after submission. I have looked at various forums and self-help sites:
store drop down options in mysql database, PHP1
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
insert value of html select form into mysql database
Using $_POST to get select option value from HTML
Yet, when refresh the page after selecting the dopwdown options, it wasn't able to retain the last selected value:
Select PHP codes:
$dropdown = elgg_echo('<DIV align="left", >
<form method="post" action="Select.php">
<select name="mycustomFile" >
<option>Select Value..</option>
<option value="A">a</option>
<option value="B">b</option>
<option value="C">c</option>
<option value="D">d</option>
</select>
<p><input type="submit" value="Submit"</p>
</form>
</DIV>');
2nd Code: Select.php (where I perform $_POST[''] action)
<?php
/**
* Override the ElggFile
*/
class FilePluginSelect extends ElggObject {
protected function initializeAttributes() {
parent::initializeAttributes();
$this->attributes['customFile'] = "my_select";
}
public function __construct($guid = null) {
parent::__construct($guid);
}
public function customFile(){
//method to call on model to allow select option
//To post select option into mysql database
$selectOption =$_POST['mycustomFile'];
if(isset($selectOption)){
$sql = "INSERT INTO Entries (mycustomFile) VALUES (".$_POST['selectOption'].")";
}else { // User selected nothing
echo 'No options selected!';
}
}
}
Could someone please help to enlighten me what has gone wrong. Thanks
You're doing it completely wrong. You probably just should use Elgg data model and store your value in metadata unless you have very good reason to ignore framework and do stuff on your own.
First of all don't bother extending ElgObject, you're doing it completely wrong and don't really need it.
To retain selection, you have to read the value and mark tag with selected attribute.
You need to update also action of saving file to include new field value. To save it to metadata you just need to use EAV interface of the entity (you'll find example in http://learn.elgg.org/en/1.12/tutorials/blog.html). Than you can read it within the view you're extending
As for the select element itself, you should use existing input/dropdown view instead. It will save you some boilerplate code. Also no need to add tag as you should be extending existing form view. Views documentation is here: http://learn.elgg.org/en/1.12/guides/views.html
I strongly recommend starting your search in Elgg documentation first. Elgg does have some learning curve, but you want to learn the proper way for your code to be maintainable in future.
set mycustomFile to mycustomFile[] . Also don't post anything into the database without clearing it, its very dangerous.
update:
Your php for getting the value of the select form is correct. Your script isn't working for another reason. Here is a sample of retrieving the select fields data.
<?php
if(isset($_POST['button']))
{
echo 'select value: ' . $_POST['something'];
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="something">
<option value="a">some a</option>
<option value="b">some b</option>
<option value="c">some c</option>
</select>
<button name="button">
click
</button>
</form>
</body>
</html>
I've read other questions on here that dealt with what I am looking for. But it still did not help me.
I want to have multiple values in an option of the select tag of a form that will be posting the information onto a different file that is viewable to the visitor by iframe. Example of what I am trying to do:
The following is on the file: Form.php
<div>
<form action"blank.php" method="post" target="box">
<select name="g1">
<option name="g1" value="Value 1, Value 2"> Text </option>
<option name="g1" value="Value 1, Value 2"> Text Blah </option>
</select>
<input type="submit" />
</form>
</div>
<iframe src="blank.php" name="box"></iframe>
The Following is a long the lines of what I want to appear on the: blank.php which is visible by iframe.
Option 1 or 2 value's should appear like this
[ Value 1 ] [ Value 2 ]
An Example:
Its a drop down menu that will post two seperate values when you select one option.
Like if I selected an option that says Hola - hello and it will post:
[Hola] means [Hello].
and the option tag would have the values as:
<option name="g1" value="Hola, Hello">Hola - Hello</option>
Sounds like you want to build an array of your form fields where multiple values are allowed. Read the PHP manual for more.
From the manual:
How do I get all the results from a select multiple HTML tag?
The
select multiple tag in an HTML construct allows users to select
multiple items from a list. These items are then passed to the action
handler for the form. The problem is that they are all passed with the
same widget name. I.e.
<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable.
The solution is to use PHP's "array from form element" feature. The
following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a
value to var[] adds an item to the array. The first item becomes
$var[0], the next $var[1], etc. The count() function can be used to
determine how many options were selected, and the sort() function can
be used to sort the option array if necessary. Note that if you are
using JavaScript the [] on the element name might cause you problems
when you try to refer to the element by name. Use it's numerical form
element ID instead, or enclose the variable name in single quotes and
use that as the index to the elements array, for example:
variable = document.forms[0].elements['var[]'];
First of all, you don't need a name attribute on each of your <option> elements. Just the <select> box.
Second of all, I think all you need is the handy dandy explode function. You'll get the value like this...
$values = $_POST['g1'];
...and then split them into an array like this...
$values = explode(', ', $values);
...and finally just access the values like so:
$value1 = $values[0];
$value2 = $values[1];
I know that this is in the PHP section, but what you are trying to do would be much easier to achieve with javascript. If you change the iframe tags to:
<div id="valueDisplay"></div>
and add an ID and listener to the select
<select name="g1" id="dropDown" onchange="showValues()">
<option name="g1" value="1"> Text </option>
<option name="g1" value="2"> Text Blah </option>
</select>
You just write a little script like this and put it in the body somewhere:
<script type="text/javascript">
function showValues(){
var outDiv = document.getElementById('valueDisplay');
var selectValue = document.getElementById('dropDown').value;
var divText;
if(selectValue == 1) divText = '[ Value 1 ][ Value 2 ]';
if(selectValue == 2) divText = '[ Value 1 ][ Value 2 ]';
outDiv.innerHTML = divText;
}
</script>
To achieve what you are trying to do with iframes would be more difficult. It would require you to use javascript/jquery to post the data within the iframe.
Note that using onchange="" is no longer the accepted method of adding listeners. It is just easier if you are not familiar with javascript.
I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed