how can i make a dynamic drop down box in php? - php

i need in an php file three drop down boxes or multiple select boxes.
the entries from these boxes are in a mysql database.
the single problem is that the entries in the thrid box depend on the second, and the entries in the second depend on the first.
can someone help? know any examples?

There are basically 3 ways to achieve this:
Use JavaScript to submit() the form to the server side during onchange of the dropdown and let PHP load the options and render the child dropdown accordingly based on the selected dropdown value. Technically the simplest way, but also the least user friendly way. You probably also want to revive all other input values of the form.
Let PHP populate all possible child dropdown values in a JavaScript array and use a JavaScript function to fill and display the child dropdown. A little bit trickier, certainly if you don't know JavaScript yet, but this is more user friendly. Only caveat is that this is bandwidth and memory inefficient when you have relatively a lot of dropdown items. Imagine three dropdowns which can each hold 100 items, that would mean a JS array of 100 * 100 * 100 = 1 million items. The page might then grow over 1MB in size.
Let JavaScript fire an asynchronous (ajaxical) HTTP request to the server side and fill and display the child dropdown accordingly. Combines the best of options 1 and 2. Efficient and user friendly. jQuery is extremely helpful in this since it removes the concerns about crossbrowser compatibility with regard to firing ajaxical requests and traversing the HTML DOM tree. You would otherwise end up with double, triple or even much more of code needed to achieve this.
If you let know in a comment or an update of your question which way you would prefer and where exactly you're stucking while implementing the solution, then I'll maybe update the answer to include a basic kickoff example.

I'm from Portugal, so, what we do it's based on Portuguese language, never the less, we've made many working websites and platform's with what you want, please check this link...
if this is what you want, I can send you the code:
http://www.medipedia.pt/home/home.php?module=farmacia

Related

Yii Cgridview Dynamic Columns

I am looking at customising the yii cgridview. I want to be able to allow users to select which columns they wish to see. Currently I am selecting the exact columns which will be displayed.
I have had a look for information on this but do not seem to be getting very far, maybe I am not looking for the correct terms or their is a specific term for this. Ideally users can click a button and tick the boxes which will be seen. I have seen this implemented on x2crm
http://demo.x2engine.com/index.php/accounts/index
I also like the ability to move the columns around ie resort the order of the columns and the ability to resize the columns when more are added. I realise someone isn't going to come along and do this for me, but certainly if someone could provide me any information or similar requests, it would be greatly appreciated.
After a long gruelling search I have found something that may in fact be the solution to both of my requests. An extension for Yii exists that allow for you to chooser the columns you wish to display with a simple tick box selection, as well as allowing for reordering of columns.
http://ecolumns.demopage.ru/index.php
The link above takes you to the demo page for the extension and the link below is the link to the extension download page.
http://www.yiiframework.com/extension/ecolumns/
This is by far the easiest way to implement this functionality on your web app.
Start by reading the docs for CGridView,
The constructor for it takes in an array specifying which columns to display (and whether to allow sort on them, etc) so allowing users to select which columns they want to see is almost trivial:
Display a form with checkboxes, the values of which are the names of the columns. When the user submits the form, loop over the checkboxes and add each of the present fields to the array that is passed to CGridView.
It is a little more complicated if you want to have specific settings for the column (i.e. a specific column header, or formatting) however not too much - in that case you just define an array holding the settings for it, and add that array to the total array you submit to CGridView.
Allowing drag and drop of the columns is a far more challenging enterprise, and may not actually be possible without a custom implementation - this is because CGridView is inherently just a table i.e. you could drag and drop rows easily (as they are whole items), but dragging a dropping a row is in reality dragging and dropping a lot of separate cells. However, there are jQuery examples that could get you started - and it wouldnt be a huge issue to implement a CGridView that uses divs instead of a table, and uses cells inside columns, rather than cells inside rows.
I hope that helps a little.

Creating Interactive Poll With Results Page

I'm looking to create a poll/form that will allow the user to select a starting 11 for a football game (or soccer if you're American), and then submit it and then see an image of the most popular team selection among the fans (maybe most popular for each position instead of most popular team selection all together).
Ideally I would like the form to have options for formation (4-4-2, 4-3-3, 4-5-1 etc) that would change the layout/inputs on the form (but this is definitely not essential, would just be a nice touch - I would just stick with 4-4-2 otherwise).
My dream idea is that there will be a dashboard on the bottom that had player profile pictures that can be dragged and dropped into their positions; However having simple drop down boxes would work too (as long as a player cant be used twice - which is another stumbling block because you don't want the same player to be in both CB positions.)
Design Concept (Results page would basically be the same just without the bottom dashboard):
I have absolutely no idea how to approach this as it is way more complex than anything I have attempted in the past. (Forgot to mention I would like to be able to reset the results every week or so if possible)
So if someone could let me know if its do-able, and if it is, take me through how to do it step by step or even mock one up for me it would be much appreciated.
Thanks.
It doesn't have to be a form.
Here how you do it:
Create the divs for the squares on the field.
Assign each of them a unique id e.g.
id="square-1"
and give them a common class e.g class="field-square"
Create the divs for the squares outside the field. Give them a common class, and a unique id for each.
When you drop the squares, have a function that extracts the ids when they are dropped.
Then simply post them to your PHP site with jQuery.post()
Update
To extract the ids, in your callback (after you have dropped the square) do something like this:
square_id = square_id.replace('square-', '');
Since you've not assigned number ids (which you should, so that you can easily change the players in future by getting them from a database), you can simply get the ids using $(this).attr('id') in your callback.
Also look up http://api.jquery.com/jQuery.post/
I wouldn't even think about dragging and dropping at this point. Outline what the minimal viable product would be and come up with a set of steps to do that.
Going off the data you provided I would suggest something like this...
1) Build an html form that list simply a list of all the positions and a dropdown of all the possible players that can fill that position.
2) Fill out the form (select the players) and on form submit get the data echo'd as an array.
3) Create the graphic...I see two approaches....(1) server side (GD or Imagick are probably what you are going to want to use) or (2) CSS/html images
Either one will a fine approach....this step should probably be broken into little steps...start with simply displaying a list and an image of the player next to it...
HTML would be
echo "<img src='/images/players".$_POST["position1"]."' alt=''/>";
//(NOTE YOU HAVE TO CLEAN ANY DATA YOU ARE OUTPUTTING PROPERLY)
Imagick would be something like..
$bg = new Imagick("/images/bg.jpg");
$position = new Imagick("/images/players".$_POST["position1"]);
//Second image is put on top of the first
$bg->compositeImage($position, $position->getImageCompose(), 5, 5);
//new image is saved as final.jpg
$bg->writeImage('final.jpg');

PHP or JS Templateing engine? (for multiple blocks of the same html)

Main questions are in bold at the bottom, But I'll walk you through what and why i'm asking.
Basically taking what i'm now doing for users one-at-a-time, and trying to give them the option of displaying everything on one-page. Was using PHP to place data in html, but interested in improving my code and wondering if a handlebars.js with javascript would make more sense, even just for my own sanity.
Say a user has a list with check box's next to each
[x] Option 1
[ ] Option 2
[ ] Option 3
...
[x] Option 20
For each box checked, a block of html is displayed with information from the database.
Right now, I only display one block of html per page. PHP was on the same page, grabbing the data, and looping through the 2 arrays generated from two queries, with inline php inside the html to generate the current blocks of html.
....
<div class="option-wrapper">
<?php foreach ( $option_list as $option ) : ?>
....
With needing to be able to generate this same block of code between 1 and 20 times on the same page. I guess I could still use php inline and loop over the entire block of html to create another block of html for each selected option.
| Option 1 | | Option 20 |
| Title: Test1 | | Title: Test2 |
But I was wondering if there is an advantage to using a javascript templating engine for this purpose. I have javascript written to chart data, currently I have hidden html elements that store the php variables (15 of them from two arrays), which is then pulled by my jQuery. But I already feel like hiding variables in html at least feels like bad practice.
<div id="total-users" style="display:none;"><?php echo $total_users ?></div>
....
var totalUsers = $('#total-users').html();
This may be one of those, if you had to ask, it probably is bad practice type of questions. But, honestly, is this bad practice?
In the interest of writing higher quality code, would this be better done using json_encode after php grabs all of the data. Then to use a javascript template engine like handlebars.js with in a block of html that is cloned for each option that is selected?
One more thing, I may in the future want to be able to switch the data being displayed on-the-fly using a drop down in each block, does this change which route makes more sense?
Is there anything else obvious that i'm missing, or doing wrong?
Thank you!
I would absolutely recommend using a template for the data.
1- As the user selects an option (or submits their final choices from all available options), make an AJAX call to retrieve a JSON object (you can return one object or all option data in one JSON call, the latter preferred).
2- Use the template (handlebars, moustache, underscore, etc), to render the data in a success callback function.
This will make your code more efficient, and more flexible for future UI requests (your code would support many different implementations from a user experience standpoint).
If I understand you correctly, the information you're retrieving from the database is static (that is, it doesn't change between each checkbox click).
If the above is true, I would personally do it like this. (just my opinion though)
I would grab all information from the database (referring to all "checkboxes") just once, server-side (PHP). Then I would put them in hidden divs:
<div id="stuffFromDb1" class="hidden" style="display: none">blablabla</div>
Then, when the user clicks in a checkbox, I would show the correspondent div, by changing the display: none to display: block. (with jQuery it's even easier, see Toggle.
This seems to me the most efficient way instead of grabbing the information through AJAX or multiple "forms".
EDIT:
I prefer this method to AJAX and form post because it reduces the number of requests to the server. Unless the DB queries are very CPU intensive (complicated) it is usually faster to query the database once than several times and giving the user a better experience.
Edit2:
It's hard to give you an answer without seeing the code but for 100 or 200 or even 1000, I would bet it would be faster overall to load them all at once than loading them 1 by 1, Specially if you could achieve that doing only 1 query to the database.
Client side template system always relies on the speed of the client. In newer browsers / new PCs JS engine is fairly quick, but for older PCS / older browsers that is not true at all. Complex DOM manipulations + the time needed to complete the AJAX request may take quite a while, a time during which the user may not be able to interact with the page. Besides, other problems might arise (AJAX Race Condition pops into my mind).

jQuery and PHP suggested answers

Hey guys, there is a form where the user select some of his friends and I'm curious on how I can implement a list that searches simultaneously while the user is typing a friend's name and when he selects the name the name is written in the text box(jQuery). And if the user wants to select more than one friend, when I'm inserting the names in the database, how can I separate the names that are written in one input field?
You should take a look at the jquery auto-complete plugin:
http://docs.jquery.com/Plugins/autocomplete
Also, you could separate the names using commas.
Are you looking to write your own plugin or would you like to use an existing one?
If you want something ready made, here are a few examples
if you want something extremely light, only 6kb packed, this one would be the best choice
Autosuggest jQuery Plugin
Older one but still good
Tokenizing Autocomplete
This what already asked here on this site.
Facebook style JQuery autocomplete plugin
The accepted answer cited this jQuery code.
https://github.com/loopj/jQuery-Tokenizing-Autocomplete-Plugin
http://jqueryui.com/demos/autocomplete/
Although think twice about including the whole jquery ui library for this one plugin
I've implemented this a couple of times, it is not that difficult to achieve decent results and the basic idea that I used was...
1) create an input box.
2) create a div positioned directly underneath the input box.
3) create a jquery keypress handler. if there are more than x characters typed, ajax request.
4) loop through the results, and if they exist, append result divs to the result box.
5) show the result box.
I can dig up some example code if you would like. Not sure what you are talking about with the select multiple, but you could keep a variable of selected, and change the color of the result div when it is clicked on, this way many results can be selected and then processed later.

How to enable/create elements on the fly

I am using a combination of PHP, jQuery and Spry to serve a series of listboxes in which a user will select first the type of vehicle, then the make, then the model and finally the specific model.
All my listboxes (SELECT) are working fine, and they update properly using the Spry elements. Each listbox is populated from a different Spry XML Dataset, and this is my problem.
If I present all four listboxes to the user, the script has to go and fetch all four lots of XML to populate all four listboxes, taking several seconds. What I want to do is to create/enable the listboxes in order, so at the user selects from the first listbox, the second is created/enabled, when they select from the second, the third is created/enabled... and so on.
Setting the disabled attribute is no good because the script has already fetched the XML before this is processed.
Any ideas??
Si
UPDATE -- Sorry guys, don't think I made my problem quite clear.
At the top of my script I declare four Spry XML data set variables, each of which goes off (when required) and performs a complex SOAP query against a service, this service then returns a chunk of XML. Each query is dependant on the last, so once the user has selected the type of vehicle, the second data set is refreshed to give an accurate list of manufacturers. When they select the manufacturer, the third list is refreshed to give an accurate list of models for that manufacturer. When they select the model, the list of model derivatives is refreshed for that model (fourth list).
Further down my script I have four SELECT's, each of which is populated with the data from the spry queries. Now, the user must choose the desired option from each list in turn in order to get the right model in the final box. What I want to do is ONLY populate the first box when the page is generated, then populate (or create??) the second, third and fourth boxes when the user selects the desired value in each, much like happens in the Autotrader website (www.autotrader.co.uk).
As I said in the initial posting, I can't use the 'disabled' attr, or even the jQuery show() and hide() functions, as these do not fire until AFTER all four datasets have been fetched and populated into the SELECT's. I need something which ideally creates the elements from scratch as and when required, to stop the four lots of XML being fetched at the beginning...
Hope this clarifies
$('option').click( function() {
if($(this).val() != 'Select one...'){
$(this).next('select').attr('enabled', 'enabled');
$(this).next('select ~ select').attr('disabled', 'disabled');
/* or */
$(this).after('<!-- Generated select/option HTML -->').nextAll('select').remove();
}
}
This is wholly untested, but according to the API, may work. I'm not sure I understand your question completely, but if you're looking to enable the next option after selection and disable the options after that until the next option is clicked, this is would be your ticket if it works.
If it's a matter of adding (or removing) them dynamically, you can just use the .after and .nextAll methods to add and pinpoint select boxes for removal.
UPDATE: Whoopsie. Had the wrong selectors.
Instead of disabling them, why not just hide/show using jQuery? .hide() .show(),
I'm not sure I know what you're asking but it seems like you're looking for something like:
$("#select1").bind("change",function() {
var sel=$(this).attr("value");
$.ajax({
url:sel + ".xml",
dataType:"xml",
success:function(xml) {
$(xml).children("option").each(function() {
$("<option />",attr:{ value:$(this).attr("value") }).text($(this).text()).appendTo("#select2");
});
}
});
});
Am I way off base here? I mean, that's just a rudimentary way of going about it (and probably has a billion holes), but you want this updating live, right? You don't want it fetching all the XML on page load, right? You could also change $("#select1") to $("#formname select").each(function() { and then have it pick the .next("select") to append it to after fetching the XML.
I'll confess, I've never really used Spry. I've seen it in use a little and it seemed like I could do what I needed to using jQuery.

Categories