Question

I've already posed this question on the jquery-jtable Github issues section here: https://github.com/hikalkan/jtable/issues/703 . There doesn't seem to be much knowledge being shared there at this time and this issue is significantly hamstringing further development of my project.

I am practically certain I am missing something relatively simple because based on the documentation here: http://www.jtable.org/ApiReference#fopt-options this really should be straightforward with no issues.

Note, this simplified version of code should demonstrate the issue and is not representative of exactly how the code is being implemented. that is, I am strictly trying to solve the reproducible issue not how best to use it in my much larger project.Here's a copy paste of the issue:

Let's make the SQL table:

--Create "employee titles" table
create table employee_titles (employeetitleid int not null IDENTITY, employeetitle varchar(50) not null,
constraint PK_employee_titles_employeetitleid
primary key clustered (employeetitleid))
go

Now let's make the jtable:

<html>
  <head>

    <link href="/jtabphp/themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
    <link href="/jtabphp/scripts/jtable/themes/lightcolor/blue/jtable.css" rel="stylesheet" type="text/css" />

    <script src="/jtabphp/scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="/jtabphp/scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
    <script src="/jtabphp/scripts/jtable/jquery2.3.0.jtable.js" type="text/javascript"></script>

  </head>
  <body>
    <div id="EmployeeTitles" style="width: 600px;"></div>
    <script type="text/javascript">

        $(document).ready(function () {

            //Prepare jTable
            $('#EmployeeTitles').jtable({
                title: 'Employee Titles',
                actions: {
                    listAction: 'PersonActions.php?action=list',
                    },
                fields: {
                    employeetitleid: {
                        key: true,
                        create: false,
                        edit: false,
                        title: 'Title ID',
                        width: '10%'
                    },
                    employeetitle: {
                        title: 'Employee Title',
                        options: 'DropdownSelectors.php?Selector=employeetitle',
                        optionsSorting: 'text',
                        width: '45%'
                    }
                }
            });

            //Load person list from server
            $('#EmployeeTitles').jtable('load');

        });

    </script>

  </body>
</html>

Let's create the personactions.php file which runs the SQL queries for action==list:

<?php

// Connect to SQL Server
include '../../phpconfig/connectstrings.php';

try
{
    $conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}

catch ( PDOException $e )
{
    print( "Error connecting to SQL Server." );
    die(print_r($e));
}

catch(Exception $e)
{
    die(var_dump($e));
}

try {
    //Getting records (listAction)
    if($_GET["action"] == "list")
    {

    //Get records from database
    $sql_select = "SELECT employeetitleid, employeetitle FROM employee_titles";
    $stmt = $conn->query($sql_select);

    //Add all records to an array
    $rows = $stmt->fetchall(PDO::FETCH_ASSOC);

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['Records'] = $rows;
    print json_encode($jTableResult);
    }
    //Creating a new record (createAction)
    else if($_GET["action"] == "create")
    {
    //Insert record into database
    $sql_insert = "INSERT INTO employee_titles (employeetitle) VALUES (?)";
    $stmt = $conn->prepare($sql_insert);
    $stmt->bindValue(1, $_POST['employeetitle']);
    $stmt->execute();

    //Get last inserted record (to return to jTable)
    $sql_select = "SELECT employeetitleid, employeetitle FROM employee_titles WHERE employeetitleid = @@IDENTITY";
    $stmt = $conn->prepare($sql_select);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['Record'] = $row;
    print json_encode($jTableResult);
    }

    //Updating a record (updateAction)
    else if($_GET["action"] == "update")
    {
    //Update record in database
    $sql_update = "UPDATE employee_titles SET employeetitle = ? WHERE employeetitleid = ?;";
    $stmt = $conn->prepare($sql_update);
    $stmt->bindValue(1, $_POST['employeetitle']);
    $stmt->bindValue(2, $_POST['employeetitleid']);
    $stmt->execute();

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    print json_encode($jTableResult);
    }
    //Deleting a record (deleteAction)
    else if($_GET["action"] == "delete")
    {
    //Delete from database
    $sql_delete = "DELETE FROM employee_titles WHERE employeetitleid = ?;";
    $stmt = $conn->prepare($sql_delete);
    $stmt->bindValue(1, $_POST['employeetitleid']);
    $stmt->execute();

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    print json_encode($jTableResult);
    }

//Close database connection
$conn = null;

}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
print json_encode($jTableResult);
}

?>

Finally, let's make the DropdownSelectors.php file that is going to query our dropdown contents. depending on how I construct this file I will get 2 different results with neither being satisfactory.

In this 1st example I am going to make [DisplayText] == [Value]. This will correctly display the employee title information in the jtable view and correctly populate the dropdown for create/edit. However, the [Value] reported by the dropdown is not nearly as useful for later queries as it would be if it were actually the employeetitleid as opposed to just a repeat of the employeetitle. The code as shown in both examples produces a perfect match of the type of array expected by jtable as referenced here: http://www.jtable.org/apireference#fopt-options . This should not be in dispute since the create/edit dropdown will work in either example.

Example DropdownSelectors.php #1:

<?php
// Connect to SQL Server
include '../../../phpconfig/connectstrings.php';

try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}

catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
    die(var_dump($e));
}
if ($_GET['Selector'] == "employeetitle") {
    $sql_select = "SELECT employeetitle [DisplayText], employeetitle [Value] FROM employee_titles";
    $stmt = $conn->prepare($sql_select);
    $stmt->execute();

    $rows= $stmt->fetchAll(PDO::FETCH_ASSOC);

    $options[Result] = 'OK';
    $options[Options] = $rows;

    print json_encode($options);
                                            }
?>

In this 2nd example I am going to make [DisplayText] and [Value] pull from different columns in the employee_titles table. This will cause the employee title column of the jtable to be blank but still correctly populate the dropdown for create/edit. In this case, the [Value] reported by the dropdown is very useful for later queries as it actually reports the employeetitleid as opposed to just a repeat of the employeetitle. The code as shown in both examples produces a perfect match of the type of array expected by jtable as referenced here: http://www.jtable.org/apireference#fopt-options . This should not be in dispute since the create/edit dropdown will work in either example. It is completely unacceptable that the displayed jtable column appear blank, however.

Example DropdownSelectors.php #2:

<?php
// Connect to SQL Server
include '../../../phpconfig/connectstrings.php';

try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}

catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}

catch(Exception $e)
{
    die(var_dump($e));
}
if ($_GET['Selector'] == "employeetitle") {
    $sql_select = "SELECT employeetitle [DisplayText], employeetitleid [Value] FROM employee_titles";
    $stmt = $conn->prepare($sql_select);
    $stmt->execute();

    $rows= $stmt->fetchAll(PDO::FETCH_ASSOC);

    $options[Result] = 'OK';
    $options[Options] = $rows;

    print json_encode($options);
                                            }
?>

Now that you have all of the code necessary to completely reproduce this very reproducible issue can anyone tell me how to fix it so htat the listed fields display the DisplayText and the dropdown options issue the vlaue that equates to an ID #? I am beginning to believe there is a display bug in jtable itself and that a small fix somewhere would cause the information to appear in the jtable view.

See the linked github issue for some of the workarounds I have attempted and why they do not work.

Était-ce utile?

La solution

Okay! I solved this one. Holy cow do I feel dumb. I had a faulty understanding of how Value relates to the record and field name. I had assumed Value was strictly the information passed when a dropdown selection was made. However, as I see now, Value also corresponds to the the record that is contained in the jtable field. Thus, the fieldname will have to correspond to the column name the data comes under just like a standard jtable field does. Value must correspond to that column. So, to fix the provided example we do the following:

if ($_GET['Selector'] == "employeetitleid") {
    $sql_select = "SELECT employeetitle [DisplayText], employeetitleid [Value] FROM employee_titles";
    $stmt = $conn->prepare($sql_select);
    $stmt->execute();

    $rows= $stmt->fetchAll(PDO::FETCH_ASSOC);

    $options[Result] = 'OK';
    $options[Options] = $rows;

    print json_encode($options);
                                            }

and

employeetitleid: {
                    title: 'Employee Title',
                    dependsOn: 'anotherfield',
                    options: function (data) { if (data.source == 'list') { return  'DropdownSelectors.php?Selector=employeetitleid&filter=>0'; }
                    return './../DropdownSelectors.php?Selector=employeetitleid&filter==' + data.dependedValues.anotherfield },
                    optionsSorting: 'text',
                    width: '45%'
                }

The above example also includes the logic to operate the DepndsOn feature for cascaded dropdowns which is how I ran into this issue to begin with (having [Value]==[DisplayText] "worked well until then). In this example the jtable will show a column name of "Employee title" and the fields will show the text strings that correlate to the title id number. However the actual data being worked with is the title id number which, not surprisingly, makes all of the queries and the field configurations must easier and more efficient.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top