Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Team ,

I am trying to make dependent drop down in perl script not able to make it , Can you please help me on same ?

I have populated the first drop down value from database and able show them, but when I am changing any value from first drop down the second drop down value should auto get populated depending on selection in 1st drop down

  • Comment on how to make dependent drop down in perl script

Replies are listed 'Best First'.
Re: how to make dependent drop down in perl script
by choroba (Cardinal) on Mar 10, 2023 at 16:11 UTC
    #! /usr/bin/perl use strict; use warnings; use DBI; use Tk; use Tk::Optionmenu; my $db = 'DBI'->connect('dbi:SQLite:dbname=:memory:', "", "", {RaiseError => 1}); $db->do('CREATE TABLE countries (id INT PRIMARY KEY, name TEXT)'); my $insert_countries = $db->prepare( 'INSERT INTO countries(id, name) VALUES (?, ?)'); $insert_countries->execute(@$_) for [qw[ 1 USA ]], [qw[ 2 Palau ]]; $db->do(<< '__SQL__'); CREATE TABLE states (id INT PRIMARY KEY, name TEXT, country_id INT, FOREIGN KEY(country_id) REFERENCES countries(id)) __SQL__ my $insert_states = $db->prepare( 'INSERT INTO states (id, name, country_id) VALUES (?, ?, ?)'); $insert_states->execute(@$_) for [qw[ 1 Alabama 1 ]], [qw[ 2 Alaska 1 ]], [qw[ 3 Arizona 1 ]], [qw[ 4 Koror 2 ]], [qw[ 5 Melekeok 2 ]]; my %countries; my $fetch_countries = $db->prepare('SELECT id, name FROM countries'); $fetch_countries->execute; while (my @row = $fetch_countries->fetchrow_array) { $countries{ $row[0] } = $row[1]; } my $fetch_states = $db->prepare( 'SELECT id, name FROM states WHERE country_id = ?'); my $mw = 'MainWindow'->new; my $submenu = $mw->Optionmenu( -options => [])->pack; my $menu = $mw->Optionmenu( -options => [map [$countries{$_} => $_], sort keys %countries], -command => sub { my ($country) = @_; $fetch_states->execute($country); my %states; while (my @row = $fetch_states->fetchrow_array) { $states{ $row[0] } = $row[1]; } $submenu->configure( -options => [map [$states{$_} => $_], sort keys %states]); }, )->pack(-side => 'left'); MainLoop();

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: how to make dependent drop down in perl script
by choroba (Cardinal) on Mar 10, 2023 at 15:30 UTC
    What module are you using to create the UI? Tk, Prima, Curses, Termbox, or something else? Or is it running on a server using CGI, Mojolicious, Dancer2, or Catalyst?

    How do you populate the dropdown? Please, show some code so we can help you.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      The below is my perl code to populate the first drop down <Folder Name >
      sub create_view_report { my $dbslave; my $self = shift; my $html; my $res = write_to_report(); my $q = new CGI; my $fId = $q->param ('fId'); if ( $fId=='' | $fId==' ' ){ print STDERR "--**IF BLOCK----------FOLDER ID IS BLANK :$fId \ +n"; #$fId=1005; }else{ print STDERR "------****ELSE BLOCK ------FOLDER ID IS BLANK :$ +fId \n"; #$fId=1005; } my $sql2 = "Select ID, link_name from dbo.equitytradereportsign +off_category"; my $result = &select_sql( $gDbh, $sql2 ); my ($soff, $m); my @foldernameval; push (@foldernameval, 'None'); my @foldernameid; push (@foldernameid, '0'); my %folderhash =('0' => 'None'); foreach ( @{$result} ) { ( $soff, $m ) = @{$_}; #print STDERR "ID--> $soff , Value -->$m\n"; $folderhash{$soff} = $m; } my $foldersize = keys %folderhash; #print STDERR "FOLDER SIZE : $foldersize\n"; my @reportnameval; push (@foldernameval, 'None'); my @foldernameid; push (@foldernameid, '0'); my %reporthash =('0' => 'None'); #1122 my $q = new CGI; my $fId ; $fId = $q->param ('fId'); if ( $fId=='' | $fId==' ' ){ print STDERR "*****===IF BLOCK----------FOLDER ID IS BLANK :$f +Id \n"; #$fId=1005; }else{ print STDERR "******===========****ELSE BLOCK ------FOLDER ID IS +NOT BLANK :$fId \n"; #$fId=1005; } #print STDERR "VIEW REPORT START and FOLDER ID :$fId \n"; my $reportsql ; my %reportHash =('0' => 'None'); if($fId !=0 ){ print STDERR "INSIDE IF BLOCK THE VALUE OF fId = $fId\n"; $reportsql = "SELECT report_type_id, sub_link_name FROM dbo. +equitytradereportsignoff_sub_category where Cat_ID = $fId"; print STDERR "REPOERT NAME SQL : $reportsql\n"; my $reportResult = &select_sql( $gDbh, $reportsql ); my ($reportId, $reportName); my @reportVal; push (@reportVal, 'None'); my @reportnameid; push (@reportnameid, '0'); %reportHash =('0' => 'None'); foreach ( @{$reportResult} ) { ( $reportId, $reportName ) = @{$_}; print STDERR "REPORT-ID--> $reportId , REPORT-NAME -->$ +reportName\n"; $reportHash{$reportId} = $reportName; } } open( HTML, '>', \$html ) || die "could not open HTML in memory f +ile handle: $!\n"; my $q = $self->query(); print_header( self_obj => $self, access_entitle => 'no' ); print HTML $q->startform( -method => 'GET' ), $q->br, $q->start_div( { -class => "column-module" } ), $q->start_div( { -class => "title-bar" } ), $q->div( { -class => "text" }, "View Report", ),$q->end_div, $q->br, $q->br, $q->div( { -class => "text" }, "Folder Name : ", #my $defaultVal ='0'; $q->popup_menu( -name=>'foldernameval', -id=> 'folder_name_id', -onchange => 'getReportName()', -type=>'dropdown', -values=> \%folderhash, #-default=>$defaultVal, -default=>['0'], ), $q->hidden( -name => ('folder_name', -id=> 'h_folder_name_id', -va +lue => '' )), ),$q->end_div, $q->br, $q->br, $q->div( { -class => "text" }, "Report Name : ", $q->popup_menu( -name=>'reportnameval', -id=> 'report_name_id', #-onchange => 'getReportName()', -type=>'dropdown', -values=> \%reportHash, -default=>['0'], ), $q->hidden( -name => ('report_name', -id=> 'h_report_name_id', -va +lue => '' )), #$q->a( { -href => "signoff.cgi?rm=view_report&fId=\'$fId\'", -on +Click => 'setFolderNameId()', -title => "Populate Report Name" }, "P +opulate Report Name" ), $q->a( { -href => "signoff.cgi?rm=view_report&flag=1&fId='$fId'", +-onClick => 'setFolderNameId()', -title => "Populate Report Name" }, + "Populate Report Name" ), #$q->a( { -href => "signoff.cgi?rm=view_report&fId=$fId", -title +=> "Populate Report Name" }, "Populate Report Name" ), ),$q->end_div, $q->br, $q->br, #2233 working code print STDERR "BEFORE REPORT NAME : \n"; #$q->div( { -class => "text" }, "Report Name : ", $q->popup_menu(- +name=>'dropdown',-id=> 'report_name_id', -values=>['None','One','Two' +,'Three','Four','Five']), ), #$q->end_div, $q->br, $q->br, $q->div( { -class => "text" }, "From Date : ", $q->td("<input name +='fdate' type='date'>"), "\t\tTo Date : ", $q->td("<input name='tda +te' type='date'>"),),$q->end_div, $q->br, $q->br, $q->submit(-value => 'Search'); #table added by ajay start #my %labels = ('value1'=>'label1', 'value2'=>'label2', 'value3 +'=>'label3'); #my %attributes = ('value1'=>{'id'=>'1'},'value2'=>{'id'=>'2'} +,'value3'=>{'id'=>'3'}); #print $q->popup_menu('menu_name', ['value1','value2','value3' +], 'value2',\%labels,\%attributes); #table added by ajay end $q->end_div, $q->br, $q->br, $q->br, $q->br, $q->endform, $q->br, $q->br, $q->end_html; close(HTML); return $html; }

      2023-03-11 Athanasius added code tags.

Re: how to make dependent drop down in perl script
by Anonymous Monk on Mar 10, 2023 at 15:33 UTC
    Example :
     1st drop down : Country Name :
     2nd Drop down : State Name

    so by selecting Country name from 1st drop down , the State name get populated .

    Both value (Country name and State name) are populated from database .

      Since you want to do this with HTML, this will require some Javascript as well. I rather suspect that somthing like

      <select id="country" onchange="changestatelist()"> .... <script> function changestatelist() { ...

      will be involved.

      w3schools has a tutorial.

      What it boils down to: If you make a website, you'll need to learn HTML, Javescript and CSS in addition to your backend language (perl, php, python or nodejs).

      Edit: As a sidenote, especially for my friends in th USA: Not all countries have states or regions, especially the smaller ones. Monaco and Liechtenstein are small enough for a single postal worker to know all the adresses. And is Sealand ever gets recognized, you can tour the whole country in about 15 minutes flat.

      PerlMonks XP is useless? Not anymore: XPD - Do more with your PerlMonks XP
        Thanks for responding and support. FYI : I have added OnChange method in first dropdown and defined the method in javascript which get called appropialy onchange. Now when the value get change in first dropdown , we get the selected value in javascript method , now I want to pass this value in perl method to retrive 2nd dropdwon value . but her I am unable to call the perl method from javascript/ Ajax . Please help me how to call perl method from javascript/Ajax ?
Re: how to make dependent drop down in perl script
by Anonymous Monk on Apr 28, 2023 at 13:53 UTC

    Hi Team,

    Need your help on perl script:

    I tried to short perl hash value based on Kay. Its work perfactly in separate file but when I integrate same code in my perl project it doesn't work.

    please find the code in separate file and its output :

    #!/usr/bin/perl use strict; use warnings; #use 5.010; my %folderhash2 = ( '1005' => 'SG', '1007' => 'NA', '1010' => 'Global', '0' => 'None', '1006' => 'Link', ); foreach my $folderMap2 (sort keys %folderhash2) { printf "%-8s %s\n", $folderMap2, $folderhash2{$folderMap2}; }

    OUT PUT :

    vmias62409 /v/region/na/appl/msim/imasg_env/data/imasgdev/bin/notify/s +ignOffPageOnDev 23$ ./temp.pm 0 None 1005 SG 1006 Link 1007 NA 1010 Global

    in above the perl hash get shorted based on it's Id but when I added the same below code in my perl projet , it's gives us error

    The below code I pasted in my project :

    my %folderhash2 = ( '1005' => 'SG', '1007' => 'NA', '1010' => 'Global', '0' => 'None', '1006' => 'Link', ); foreach my $folderMap2 (sort keys %folderhash2) { printf "%-8s %s\n", $folderMap2, $folderhash2{$folderMap2}; }

    Error :

    [Fri Apr 28 07:13:49.446884 2023] [cgid:error] [pid 17180:tid 47883746 +555648] [client 138.20.34.173:26768] malformed header from script 'si +gnoff.cgi': Bad header: 0 None, referer:

      Best guess is that you forgot to print the Content-Type header before the loop you have shown us. Working SSCCE:

      #!/usr/bin/env perl use strict; use warnings; print "Content-type: text/plain\n\n"; my %folderhash2 = ( '1005' => 'SG', '1007' => 'NA', '1010' => 'Global', '0' => 'None', '1006' => 'Link', ); foreach my $folderMap2 (sort keys %folderhash2) { printf "%-8s %s\n", $folderMap2, $folderhash2{$folderMap2}; }

      🦛

        Thanks so much for quick reply : I have added the print "Content-type: text/plain\n\n"; but still the output is not as expected :
        0 None 1005 SG Desk Reports 1006 LN Desk Reports 1007 NA Desk Reports 1008 Saudi Desk Reports 1010 Global Reports
        Content-Type: text/html; charset=ISO-8859-1
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-U +S"> <head> <title>MSIM Equity</title> <link rel="stylesheet" type="text/css" href="../css/master.css" /> <link rel="stylesheet" type="text/css" href="../css/basic.css" /> <link rel="stylesheet" type="text/css" href="../css/imasg-onelook.css" + /> <link rel="stylesheet" type="text/css" href="../css/imasg-eod.css" /> <script src="../js/signoff.js" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1 +" /> </head> <body id="ctl00_Body"> <div id="header"><h1 class="logo"><img src="../images/ms-logo.gif" alt +="Morgan Stanley" /></h1><h1 class="logo-print"><img src="../images/m +s_logo_grey.gif" alt="" /></h1><h1 id="site-title">MSIM Equity Report +s Signoff</h1><div id="utility-nav"><ul><li style="color:#ccffff">Wel +come: Ajay Kumar Srivastava&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</ +li><br /><br /><li style="color:#ccffff">Contact Us: 212-762-0194 </l +i></ul></div></div><div id="navigation"><div id="primary-nav"><ul><li +><a title="Home" href="signoff.cgi?rm=main">Home</a></li><li><a title +="Delinquency Report" href="signoff.cgi?rm=delinq_report">Delinquency + Report</a></li><li><a title="View Report" href="signoff.cgi?rm=view_ +report&amp;fId=0&amp;rId=0">View Report</a></li></ul></div></div><br +/><br /><form method="post" action="/signOffPageOnDev/cgi/signoff.cgi +?rm=view_report&amp;fId=0&amp;rId=0" enctype="multipart/form-data" on +load="setDefaultFolderName()" name="reportDetails" id="reportDetails" +> <br /><div class="column-module"><div class="title-bar"><div class="te +xt">View Report</div></div><br /><br />1
      Bad header: 0

      Are you printing a header before printing your data?

        No , I am not printing header . I tried to print header but it doesn't allow me . giving error
Re: how to make dependent drop down in perl script
by Anonymous Monk on Mar 10, 2023 at 15:37 UTC
    Hi Team , I am trying to make dependent drop down in perl script not able to make it , Can you please help me on same ? I have populated the first drop down value from database and able show them, but when I am changing any value from first drop down the second drop down value should auto get populated depending on selection in 1st drop down Example : 1st drop down : Country Name : 2nd Drop down : State Name so by selecting Country name from 1st drop down , the State name get populated . Both value (Country name and State name) are populated from database . this has to done in perl script
        My perl file :
        $q->div( { -class => "text" }, "Folder Name : ", #my $defaultVal ='0'; $q->popup_menu( -name=>'foldernameval', -id=> 'folder_name_id', -onchange => 'getReportName()', -type=>'dropdown', -values=> \%folderhash, #-default=>$defaultVal, -default=>['0'], ), $q->hidden( -name => ('folder_name', -id=> 'h_folder_name_id', -va +lue => '' )), #q->a( { -href => "javascript:void(0)", -onClick => 'setFolderName +Id()', -title => "Populate Report Name" }, "Populate Report Name" ), #$q->a( { -href => "signoff.cgi?rm=view_report&fId=3", -onClick => + 'setFolderNameId()', -title => "Populate Report Name" }, "Populate +Report Name" ), ),$q->end_div, $q->br, $q->br, $q->div( { -class => "text" }, "Report Name : ", $q->popup_menu( -name=>'reportnameval', -id=> 'report_name_id', #-onchange => 'getReportName()', -type=>'dropdown', -values=> \%reportHash, -default=>['0'], ), $q->hidden( -name => ('report_name', -id=> 'h_report_name_id', -va +lue => '' )), #$q->a( { -href => "signoff.cgi?rm=view_report&fId=\'$fId\'", -onC +lick => 'setFolderNameId()', -title => "Populate Report Name" }, "Po +pulate Report Name" ), $q->a( { -href => "signoff.cgi?rm=view_report&flag=1&fId='$fId'", +-onClick => 'setFolderNameId()', -title => "Populate Report Name" }, + "Populate Report Name" ), #$q->a( { -href => "signoff.cgi?rm=view_report&fId=$fId", -title +=> "Populate Report Name" }, "Populate Report Name" ), ),$q->end_div, $q->br, $q->br,
        my Java script method :
        function getReportName(){ var folder_name_id = document.getElementById('folder_name_id') +.value; alert('FOLDER NAME :'+folder_name_id); #document.getElementById('h_folder_name_id').value=folder_name +_id; perlExecute(folderId); } function perlExecute(url){ alert('PERLEXECUTE METHOD GET CALLED AND FOLDER NAME ID :'+url); function perlExecute(url){ $.ajax({ url: '/signOffPageOnDev/js/reportList.pm', type: 'get', data: { 'id' : '1234' } }); }; };
        Issue , from above Ajax method , my perl file is not getting invoked. this is biggest issue

        2023-03-11 Athanasius added code tags.