Displaying related data in jqGrid using foreign keys

My jqGrid is connected to a JSON datasource provided by a WCF web service. The WCF method retrieves a list of ids showing the relationship between a user, branch, and role. For instance, a user can have different roles in different branches.

[{"entityHashCode":null,"BranchId":25,"SysRoleId":1,"SysUserId":1},
{"entityHashCode":null,"BranchId":25,"SysRoleId":2,"SysUserId":1},
{"entityHashCode":null,"BranchId":26,"SysRoleId":1,"SysUserId":1]

While displaying this data in jqGrid is fine, I want to display the user the actual names of the branches and roles rather than their corresponding ids. However, unfortunately, modifying the WCF to return joined data is not an option since the WCF method cannot be altered.

Luckily, I do have access to two web service methods: GetBranches and GetRoles. Both methods return arrays with complete details, which I store in JavaScript arrays.

Is there any way for me to instruct jqGrid to utilize my original array but retrieve the branch and role names from separate datasources (GetBranches and GetRoles arrays)?

Answer №1

Based on my discussions with LeftyX, it appears that there is no built-in method in jqGrid to achieve this. As a result, I have developed a custom function for performing a "JOIN" operation between objects in an array. The function implementation is as follows:

function joinJSONFK(entities, fkProperties, fkLookupArrays) {

    function findValueInArray(array, idField, value) {
        for (var i = 0; i < array.length; i++) {
            if (value == array[i][idField]) {
                return array[i];
            }
        }
        return null;
    };

    function applyForeignKeys(entity, fkProperties, fkLookupArrays) {
        for (var i = 0; i < fkProperties.length; i++) {
            entity[fkProperties[i] + "Source"] = findValueInArray(fkLookupArrays[i], fkProperties[i], entity[fkProperties[i]]);
        }
        return entity;
    }

    var entityArray = [];
    if (!entities instanceof Array) {
        entities = applyForeignKeys(entities);
        return entities[0];
    } else {
        for (var i = 0; i < entities.length; i++) {
            entities[i] = applyForeignKeys(entities[i], fkProperties, fkLookupArrays);
        }
        return entities;
    }
}

The usage of this function would be as indicated below:

userRoleData = joinJSONFK(result, ["SysRoleId", "BranchId"], [GlobalRoles, GlobalBranches]); 

In the above example, "result" represents an array of JSON objects with the following format:

[{"entityHashCode":null,"BranchId":25,"SysRoleId":1,"SysUserId":1},
{"entityHashCode":null,"BranchId":25,"SysRoleId":2,"SysUserId":1},
{"entityHashCode":null,"BranchId":26,"SysRoleId":1,"SysUserId":1]

The array ["SysRoleId", "BranchId"] contains the foreign keys that require a "JOIN" operation, while [GlobalRoles, GlobalBranches] holds the corresponding data for these foreign keys.

For instance, the structure of GlobalRoles looks like this:

[{"Name":"Admin","SysRoleId":1,"Description":"Some description"},
{"Name":"Role 2","SysRoleId":2,"Description":"Some description"},
{"Name":"A new role","SysRoleId":3,"Description":"Some description"},
{"Name":"Another Role","SysRoleId":4,"Description":"Some description"}]

Similarly, GlobalBranches has the following structure:

[{"BranchName":"Branch 25","BranchId":25,"Description":"describe the branch"},
{"BranchName":"Branch 26","BranchId":26,"Description":"describe the branch"},
{"BranchName":"Branch 27","BranchId":27,"Description":"describe the branch"}]

Once the function is called, the resulting "userRoleData" will look similar to this:

[{"entityHashCode":null,"BranchId":25,"SysRoleId":1,"SysUserId":1,
"SysRoleIdSource":{"Name":"Admin","SysRoleId":1,"Description":"Some description"},
 "BranchIdSource":{"BranchName":"Branch 25","BranchId":25,"Description":"describe the branch"}},
{"entityHashCode":null,"BranchId":25,"SysRoleId":2,"SysUserId":1,
"SysRoleIdSource":{"Name":"Role 2","SysRoleId":2,"Description":"Some description"},
 "BranchIdSource":{"BranchName":"Branch 25","BranchId":25,"Description":"describe the branch"}},
{"entityHashCode":null,"BranchId":26,"SysRoleId":1,"SysUserId":1,
"SysRoleIdSource":{"Name":"Admin","SysRoleId":1,"Description":"Some description"},
 "BranchIdSource":{"BranchName":"Branch 26","BranchId":26,"Description":"describe the branch"}}]

As a result, you will have a well-organized collection of objects.

Answer №2

Why not simplify your WCF method by calling both GetBranches and GetRoles, and then constructing a new array (List of) object that includes

BranchId, BranchName, SysRoleId, SysRoleName, SysUserId
? This way, you can return the new List directly to jqGrid with just one call, making the implementation faster and more straightforward.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting MySQL to JSON leads to an issue where the Google visualization chart appears empty, showing no data

I have been experimenting with code to generate a pie chart using data retrieved from a database. Here's the snippet I am currently working with: <script type="text/javascript"> google.charts.load("current", {packages:["corechart"]}); googl ...

Issue with Google Maps functionality within the jQuery easytabs platform

Upon clicking the contact tab, the gmaps loads but unfortunately only shows the left corner of the map. Quite intriguing... Any thoughts on how to fix this? Here is the corresponding jsfiddle This is the structure of my HTML code: <div id="menu-contai ...

Performing conditional operations on a collection of dictionaries in Python

Is there a more efficient way to sum the ages of all males in this list of dictionaries? list_of_dicts= [ {"Name": "Ethan", "Gender": "male", "Age": 11}, {"Name": "Nathan", "Gender": "male", "Age": 6}, {"Name": ...

jQuery dialog box - Create customized dialog boxes with ease

I am facing an issue with my dialog code // function to display dialog for user signup function new_user_signup() { $.get("/actions/_new_user_account.php", function(data){ $("#dialog").html(data); }); $("#dialog").dialog({ width: 4 ...

What is the best way to access an Ajax response outside of its function using JQuery?

Just starting out with JQuery and wondering how to utilize the Ajax response ( HTTP GET ) outside of the function in my code snippet below: $.ajax ({ type: "GET", url: "/api", success: success, error: error ...

Show a div depending on user input

For those with more programming experience than myself, I have a simple question. In Rails, using coffescript, I want to show additional content based on a user's selection. Essentially, if they click on a checkbox, it should reveal an extra field for ...

Extracting Data from JSON Objects Using PHP

array(85) { [0]=> object(stdClass)#9 (18) { ["offer_id"]=> string(8) "12345678" ["offer_name"]=> string(39) "Offer Name" ["offer_desc"]=> string(209) "Offer Description" ["call_to_action"]=> string(57) "Of ...

Sending a request to a PHP script using AJAX to navigate to a different webpage

I'm currently working on developing a login script (still in the early stages, I plan to look into password encryption later). However, I'm facing an issue with redirecting to a specific page. Presently, I have two possibilities - an admin or a ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Determine the TR id when a button within a TD element is clicked using JavaScript/jQuery

Currently seeking a method to generate a unique identifier for use as a parameter in a JavaScript function. Specifically interested in extracting the id of the first td element if feasible. <tr id='it'><td id="#nameiron">Jason</td ...

Utilizing jQuery to Trigger a JavaScript Function in a Separate File

Here is my question: I currently have 2 files: //File1.js function TaskA() { //do something here } //File2.js function TaskB() { //do something here } $(function() { TaskA(); }); The issue I am facing is that the TaskB function in File2.js ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

Which is the preferred method: utilizing ajax calls from assets/javascript/*.js or *.js.erb views?

I am developing an admin service on Rails that communicates with a network communicator. Here is my challenge: When a user clicks a button, they are presented with network groups to choose from. Once the user selects a group, they should be able to see th ...

Custom scrollbar designed for optimal viewing on various devices

I'm currently using perfect-scrollbar to customize the scrollbar in my application. However, I've encountered a situation where I need to set the height of the scrollable section in terms of a percentage. When I tried to do this by setting the he ...

What is the best way to generate a JSON object in an Android project by merging data from various tables in a MySQL database?

I need help converting the results of my API to a JSON Object using JAVA. Can someone provide guidance on how to achieve this? $sql1="SELECT s.* , c.*,u.* FROM schedule_ s,course_t c, u user_t WHERE c.course_crn=p.course_crn and s.teache ...

Does a common function exist for a successful Ajax query?

One of my JavaScript functions is: function doWorkForJobCreate() { $.ajax({ url: '<%:ConfigurationManager.AppSettings["SiteRoot"]%>/Job/JobCreate', success: function (data, status, req) { if (!processFKErrorHeader(r ...

What could be causing the issue with sending data via Ajax when using the `type="password"` input?

Why does sending data using ajax with input type="password" not work? The main idea is that when I fill in a password less than 6 characters, it should display Password minimum 6 characters I tested this code and found that it was not working. So, I edit ...

"Encountering issue with $.ajax() not accepting PHP array as

I am currently utilizing ajax to fetch data from a table stored in a MySQL database. The ajax calls are being made using jQuery, with the databases being accessed through PDOs. PHP function fetchQuestions() { $database = "answerMe"; // n ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...