How to do condition drop-down's that link to a database

Status
Not open for further replies.
I don't have time to totally rebuild the first post right nowm I have to leave town in about an hour. But here's a real life example, using the same towns and cities stuff:

First, the user_ajax.php.

NOTE you need to make one edit here, to change the table name in the $ok_tables() array. This is a security measure, to prevent people from using this as a backdoor to grab any data form any of your J! tables.

PHP:
<?php

/* MOS Intruder Alerts */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

class userAjax {
    
    // Add any tables you want to access using getFields() here!
    // (remember to add a comma after all but the last one)
    var $ok_tables = array(
        'jos_fabrik_formdata_3'
    );
    

    function getFields(){
        global $database;
        //get all the variables passed in by the ajax objects url
        $table = mosGetParam($_REQUEST, 'table');
        $key = mosGetParam($_REQUEST, 'key', 'id');
        $label = mosGetParam($_REQUEST, 'label', 'label');
        $foreignKey = mosGetParam($_REQUEST, 'foreignkey', 'country_id');
        $val = mosGetParam($_REQUEST, 'val', '1');
        
        // make sure table is in our allowed list, if not don't do anything.
        if (in_array($table,$this->ok_tables))
        {
            //run a query on the database to get the matching fields
            $sql = "SELECT $key AS value, $label AS label FROM $table WHERE $foreignKey = '$val'";
            //echo $sql;
            $database->setQuery($sql);
            $rows = $database->loadObjectList();
        
            //write the results of the query back to the browser - the javascript code will then assign
            //the text to the second drop down
            if (!empty($rows))
            {
                foreach($rows as $row){
                    //echo "<option value=\"$row->value\">$row->label</option>\n";
                    echo "$row->value//..*..//$row->label\n";
                }
            }
            else
            {
                echo "0//..*..//Nada!";
            }
        }
        else
        {
            echo "$table//..*..//Bad table!";
        }
    }
}

?>
Now, an X.js file, where X is your form ID, needs to be in ./components/com_fabrik/js/X.js.

Code:
var please_select = 'Seleccionar...';

function getValues(cid,table,key,label,foreignkey,dropdown)
{
    var url = 'index2.php?option=com_fabrik&no_html=1&task=userPluginAjax&method=getFields';
    url += '&table=' + table;
    url += '&val='+cid;
    url += '&key='+key;
    url += '&label='+label;
    url += '&foreignkey='+foreignkey;

    new Ajax(url, {
        method: 'get',
        onComplete: function(response) {
            var newelement = new Element(
                'select',
                {
                    'id': dropdown,
                    'class': 'inputbox',
                    'name': dropdown
                }
            );
            $(dropdown).replaceWith(newelement);
            var newopts = response.split('\n');
            var newopt = new Element('option',{'value': 0}).setHTML(please_select);
            newopt.inject($(dropdown));
            for (i=0; i<newopts.length; i++) {
                if (newopts[i] != '') {
                    var vals = newopts[i].split('//..*..//');
                    var newopt = new Element(
                        'option',
                        {
                            'value': vals[0]
                        }
                    ).setHTML(vals[1]);
                    newopt.inject($(dropdown));
                }
            }
            
        }
    }).request();
}

window.addEvent('domready', function() {
    var country_id = $('jos_fabrik_formdata_4___country').value;
    if (country_id) {
        getValues(country_id,'jos_fabrik_formdata_3','fabrik_internal_id','label','country_id','jos_fabrik_formdata_4___town');
    }
});
You'll need to change that getValues() call at the bottom (which is the one that initially sets up the Town menu when the form is loaded), so it represents your table/element names ... the arglist is getValues(<country_form_menu_value>,<town_table>,<town_table_primary_key>,<town_name_element_in_town_table>,<country_id_element_in_town_table>,<town_element_on_form>);

Then add a 'onblur' on 'onchange' to your Country element in Fabrik, which makes (almost) the same getValues() call as the onload event above:

Code:
getValues(this.getValue(),'jos_fabrik_formdata_3','fabrik_internal_id','label','country_id','jos_fabrik_formdata_4___town');
The only difference being that it uses this.getValue() as the first argument. This line handles changing the Town menu when you select a different Country.

Oh, and change the "please_select" var at the top to suit your language.

I'll come back and redo all this as a neater example when I can, just wanted to get some working IE compatible code out there.

-- hugh
 
it works fine! but the table saves the values not..? i changed all my entries and then i saw it saved nothing...
 
Please bump this thread tomorrow. I have to go out now, won't be back till about 2am, so I won't get round to it tomorrow. But you've been so patient ... so bump it tomorrow and I promise I'll take a look.

-- hugh
 
Do I have login details for your site? If not, PM me the usual details and include a link back to this thread. And if its not immediately obvious, let me know which form/table/elements I need to be looking at.

However, I can't promise I can get to it this week, as I have a truckload of Subscriber requests ahead of you in the queue.

-- hugh
 
and this comes out in my email notification...

.
.
Reederei: (5)Carnival Cruise Lines
Schiff: 62
.
.
.
.
 
OK, both elements need to be database joins. Your second (cascading) element is a dropdown. And because there are no values defined for it, Fabrik doesn't know how to 'label' it.

I started changing your Schiff element to a join, but I started getting confused about which table was which and didn't want to blow your site up!

Anyway, make that Schiff element a database join element. To avoid having a huge default dropdown for new forms, just create a WHERE statement that won't return any results.

Now when you save it, Fabrik will know how to relate the numeric ID to the label.

-- hugh
 
Rob, I am not sure that I am asking a question that, even if/when I get an answer, I will be able to understand and implement, but here goes...

I now have a table of 237 countries each with an ISO ID which my Incident Report form opens with a database join. Since I want users on my site to be able to enter reports and identify the nearest main city in their report, after they have selected the country from a pull-down list, the form invites them to enter the their nearest main city.

So thats 237 countries times erm, quite a few cities per county I would imagine, which comes to, oh, um, quite alot.

So, my idea was, instead of sitting here with an atlas and trying to enter as many major cities around the world as I can (which sods law dictates will be the wrong ones anyway), was to let the users enter the city names, and have Fabrik pick them up from the form and migrate them to the table for use by the next user. In other words, to have a conditional table which grows as it is used and added to by the user's reports.

Can that be done within Fabrik2 and if so (for the comrehension of bears of very little brain), what's the best way?

RTB.

P.S. If anybody wants a 237 country/ISO code list I have one in the form of text file which can simply be imported into your Joomla! database. PM me with your email address and I'll send it to you.
 
Bump...

Like a fool I already wrote my glowing report on Fabrik on Joomla so now I can't blackmail you with that one to get an answer about having Fabrik pick up user entered city names from a form and migrate them to a table for use in a drop down list by the next user.... :(

RTB.
 
i found my answer but....

Hello
I know that this thread was publish a lot of time ago, but i just found it yesterday, this Thread is just was i looking for to solved my problem, i did all the steps that rob told us to do, but im having problems displaying the information on the towns dropdown, went i select a country my town dropdown doesn't show nothing, is blank, the only thing that does is that the dropdown makes him self smaller with out nothing to show, is empty

can some one help me PLISSSSSSSS :(

------------------------------------------------------------
THIS IS THE JAVASCRIPT THAT I PUT IN THE DATABASE JOIN
------------------------------------------------------------
var cid = this.getValue();
var table = 'towns';
var key = 'id';
var label = 'label';
var foreignkey = 'country_id';
var dropdown = '___freseologia_y_objeciones';
var url = 'index2.php?option=com_fabrik&no_html=1&task=userPluginAjax&method=getFields';

url += '&table=' + table;
url += '&val='+cid;

url += '&key='+key;
url += '&label='+label;
url += '&foreignkey='+foreignkey;

new Ajax(url, {method: 'get',update: $(dropdown)}).request();

-------------------------------------------
THIS IS THE USER_AJAX.PHP FILE
-------------------------------------------

class userAjax {
function getFields(){
global $database;
$table = mosGetParam($_REQUEST, 'table');
$key = mosGetParam($_REQUEST, 'key', 'id');
$label = mosGetParam($_REQUEST, 'label', 'label');
$foreignKey = mosGetParam($_REQUEST, 'foreignkey', 'country_id');
$val = mosGetParam($_REQUEST, 'val', '1');

$sql = "SELECT $key AS value, $label AS label FROM $table WHERE $foreignKey = '$val'";
$database->setQuery($sql);
$rows = $database->loadObjectList();

foreach($rows as $row){
echo "<option value=\"$row->value\">$row->label</option>";
}
}
}


--------------------------------
MY TABLES
--------------------------------
countries
-label
-id

towns
-label
-country_id
-id

*in that order


Can some one help me plis
Saludos From Mexico
 
Did you read thru the whole thread? The above looks like the first cut at the code, and later on I posted a newer, working version.

BTW, what browser do you use? If you use IE, try FF, see if that works with your code as-is.

Either way, suggest you work backwards thru this thread and find my most recent post with code in it.

-- hugh
 
Sorry this form is not published

Hello all

Whenever I try to repeat this example, I get an empty drop-down. When I read the Response using Firebug, it reads "Sorry this form is not published".

Could you please tell me why?

Kind regards /FaBa
 
You are probably sending it the wrong table ID.

Try putting this just before the AJAX call:

alert(url);

It should then popup an alert with the URL the AJAX is about to call. Make sure it looks like it should.

-- hugh
 
Thanx for the response! As a matter of fact, I am just about to renew my supscription. What you guys are doing is great!

My Ajax-call reads: index2.php?option=com_fabrik&no_html=1&task=userPluginAjax&method=getFields&table=towns&val=1&key=id&label=label&foreignkey=country_id

So the table name is correct i assume. But as a matter of fact, I just noticed that this thread is in the 1.x forum. My Fabrik installation is from the 2.x branch. Can the problem be due to versions? In that case, how can I do the same thing in Fabrik 2.x? I've already tried the cascading drop-down, but it doesn't seem to do it for me. What I want to land in is something like this: drop-down 2 populates based on selection in drop-down 1. But it selects its data based on a condition that looks in two tables, something like:

SELECT building_id AS value, building_facility_code AS label FROM buildings WHERE building_id NOT IN (SELECT buildings_building_id FROM operator_has_building WHERE operators_operator_id = operator_id_from_dropdown_1)

The operator_has_building is a N:N relational table to store relations between building operators (operators table) and buildings (building table).

Any help on this would be highly appreciated!

Kind regards /FaBa
 
I just noticed that this thread is in the 1.x forum. My Fabrik installation is from the 2.x branch.
ahhhh :) in that case you should use the cascading drop down element, which does all this for you. Its in the SVN and needs to be installed before you can access it - there's a FAQ that Hugh wrote somewhere regarding how to do that

cheers
Rob
 
Status
Not open for further replies.
We are in need of some funding.
More details.

Thank you.

Members online

No members online now.
Back
Top