字段选项中的值== DisplayText,否则字段为空

时间:2013-06-14 17:27:59

标签: php javascript jquery sql jquery-jtable

我已经在jquery-jtable Github问题部分提出了这个问题:https://github.com/hikalkan/jtable/issues/703。目前似乎没有太多的知识在这里分享,这个问题严重阻碍了我的项目的进一步发展。

我几乎可以肯定我错过了一些比较简单的东西,因为基于这里的文档:http://www.jtable.org/ApiReference#fopt-options这应该是直截了当的,没有任何问题。

请注意,此简化版本的代码应该演示该问题,并不能准确表示代码的实现方式。也就是说,我正在严格地尝试解决可重复的问题,而不是如何在我更大的项目中最好地使用它。这是该问题的复制粘贴:

让我们创建SQL表:

--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

现在让我们制作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>

让我们创建personactions.php文件,该文件运行SQL查询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);
}

?>

最后,让我们创建DropdownSelectors.php文件来查询我们的下拉内容。根据我如何构建这个文件,我会得到2个不同的结果,但都不令人满意。

在第一个例子中,我要制作[DisplayText] == [Value]。这将在jtable视图中正确显示员工标题信息,并正确填充下拉列表以进行创建/编辑。但是,下拉列表中报告的[值]对于以后的查询几乎没有用,如果它实际上是有效的,而不仅仅是重复的雇员标题。两个示例中显示的代码生成了jtable所期望的数组类型的完美匹配,如下所示:http://www.jtable.org/apireference#fopt-options。这不应该引起争议,因为创建/编辑下拉列表可以在任何一个示例中使用。

示例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);
                                            }
?>

在第二个例子中,我将从employee_titles表中的不同列中提取[DisplayText]和[Value]。这将导致jtable的employee title列为空,但仍然正确填充create / edit的下拉列表。在这种情况下,下拉列表报告的[值]对于以后的查询非常有用,因为它实际上报告了employeeetitleid而不是仅仅重复了employeeetitle。两个示例中显示的代码生成了jtable所期望的数组类型的完美匹配,如下所示:http://www.jtable.org/apireference#fopt-options。这不应该有争议,因为创建/编辑下拉列表将在任一示例中起作用。然而,显示的jtable列显示为空白是完全不可接受的。

示例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);
                                            }
?>

现在你已经拥有了完全重现这个可重现的问题所需的所有代码,任何人都可以告诉我如何修复它,所以列出的字段显示DisplayText和下拉选项会发出等同于ID#的vlaue?我开始相信jtable本身存在显示错误,并且某处的小修复会导致信息出现在jtable视图中。

请参阅链接的github问题,了解我尝试过的一些解决方法以及它们无法正常工作的原因。

1 个答案:

答案 0 :(得分:2)

好!我解决了这个问题。神圣的牛我觉得愚蠢。我对Value与记录和字段名称的关系有一个错误的理解。我假设Value是严格按下选择时传递的信息。但是,正如我现在看到的,Value也对应于jtable字段中包含的记录。因此,fieldname必须与数据所在的列名对应,就像标准jtable字段一样。值必须与该列对应。因此,要修复提供的示例,我们执行以下操作:

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);
                                            }

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%'
                }

上面的例子还包括为级联下拉列表操作DepndsOn功能的逻辑,这就是我开始遇到这个问题的方法(让[Value] == [DisplayText]“在那之前运行良好)。在这个例子中jtable将显示列名称“Employee title”,字段将显示与标题ID号相关的文本字符串。但是,正在使用的实际数据是标题ID号,毫不奇怪,它会产生所有查询和现场配置必须更容易,更有效。