Select to view content in your preferred language

Query Related Records

1893
2
07-27-2011 06:29 PM
deleted-user-K_IRAXrpGKsG
Deactivated User
Hello,

I'm attempting to query related records for events. I'm using the query multiple records example provided link:http://help.arcgis.com/en/webapi/javascript/arcgis/demos/fl/fl_query_related_multiple.html

But so far I've have been unsuccessful. The code seems to be almost working correctly, however, when results should appear in the results box to the right of the map, an error comes up instead. The box is filled with "Sorry, an error occurred"

Please take a look at the code, and the mapserver layers to see if there is a fix.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9" />
    <title>Query RelatedRecords Example</title> 
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.4/js/dojo/dijit/themes/tundra/tundra.css"> 
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.4/js/dojo/dojox/grid/resources/Grid.css"> 
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.4/js/dojo/dojox/grid/resources/tundraGrid.css"> 
    <style>
        html, body {
          height: 100%;
          width: 100%;
          margin: 0; 
          padding: 0;
        }

        body {
          background-color:#777;
          overflow:hidden; 
          font-family: "Trebuchet MS";
        }

        #header {
          background-color:#444;
          color:orange;
          font-size:15pt;
          text-align:center;
          font-weight:bold;  
        }

        #footer {
          background-color:#444;
          color:orange;
          font-size:10pt;
          text-align:center;
        }
    </style>
    <script type="text/javascript">djConfig = { parseOnLoad:true };</script> 
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.1"></script> 
    <script type="text/javascript" language="Javascript"> 
      dojo.require("esri.map");
      dojo.require("esri.tasks.query");
      dojo.require("esri.toolbars.draw");
      dojo.require("dojox.color.Palette");
      dojo.require("esri.layers.FeatureLayer");
      dojo.require("dojox.grid.DataGrid");
      dojo.require("dojo.data.ItemFileReadStore");
      dojo.require("dijit.layout.BorderContainer");
      dojo.require("dijit.layout.ContentPane");
 
      var map, wellFeatureLayer, toolbar, grid, store, resizeTimer;
 
      function init() {
        var startExtent = new esri.geometry.Extent(-89.5328,40.4344,-89.2582,45.64041, new esri.SpatialReference({wkid:4326}) );
 
      
  //
   map = new esri.Map("mapDiv", {extent:esri.geometry.geographicToWebMercator(startExtent)});
        dojo.connect(map, "onLoad", initTopQueryFunctionality);
        var tiledLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer");
        map.addLayer(tiledLayer);
 
        //
  var imageParams = new esri.layers.ImageParameters();
        // 1 = Events Points 
  imageParams.layerIds = [1,2,3];
        imageParams.layerOption = esri.layers.ImageParameters.LAYER_OPTION_SHOW;
        
  
     
  //content for the info-window
  var content =  "<b>Object ID:</b>  ${ObjectID}<br>" +
       "<b>Event ID:</b>   ${ObjectID}<br>"+
       "<b>Fee:</b>   $${Cost}<br>"+
       "${Description}";
  
  
  //Adds the entire Map we've created and placed on the server
  var dynamicLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://studentgisserver.uww.edu/ArcGIS/rest/services/VirtualTraining1/MapServer", {imageParameters:imageParams});
        map.addLayer(dynamicLayer);
 
  // Adds icon over the point after clicked
        var selectionSymbol = new esri.symbol.SimpleMarkerSymbol().setColor("red");
        
  
  //Allows the Events point (layerIds = 1) to be used in query
  wellFeatureLayer = new esri.layers.FeatureLayer("http://studentgisserver.uww.edu/ArcGIS/rest/services/VirtualTraining1/MapServer/1", {
   mode: esri.layers.FeatureLayer.MODE_SELECTION,
        
  
   //The info in the Event pop-up window
   infoTemplate: new esri.InfoTemplate("Event: ${ObjectID}", content)
        });
        
 
  //Adds the selectionSymbol to the Events layer 
  wellFeatureLayer.setSelectionSymbol(selectionSymbol);
      
  //findsRelatedRecords for the Events layer
  dojo.connect(wellFeatureLayer, "onSelectionComplete", findRelatedRecords);
 
        map.addLayer(wellFeatureLayer);
 
        dojo.connect(map, "onClick", findWells);
      }
 
      function initTopQueryFunctionality(map) {
        dojo.connect(dijit.byId('mapDiv'), 'resize', function() {
          resizeMap();
        });
      }
 
      function findRelatedRecords(features) {
       // alert ('finding related records');
  var relatedTopsQuery = new esri.tasks.RelationshipQuery();
        relatedTopsQuery.outFields = ["*"];
       // alert('relationshipId');
  relatedTopsQuery.relationshipId = 3;
        //alert('features[1]');
    relatedTopsQuery.objectIds = [features[2].attributes.ObjectID];
        wellFeatureLayer.queryRelatedFeatures(relatedTopsQuery, function(relatedRecords) {
          var fset = relatedRecords[features[2].attributes.ObjectID];
          var items = dojo.map(fset.features, function(feature) {
            return feature.attributes;
          });
          //Create data object to be used in store
          var data = {
            identifier: "ObjectID",  //This field needs to have unique values
            label: "ObjectID", //Name field for display. Not pertinent to a grid but may be used elsewhere.
            items: items
          };
 
          //Create data store and bind to grid.
          store = new dojo.data.ItemFileReadStore({ data:data });
          grid.setStore(store);
          grid.setQuery({ ObjectID: '*' });
        });
      }
 
      function findWells(evt) {
        grid.setStore(null);
        var selectionQuery = new esri.tasks.Query();
        var tol = map.extent.getWidth()/map.width * 5;
        var x = evt.mapPoint.x;
        var y = evt.mapPoint.y;
        var queryExtent = new esri.geometry.Extent(x-tol,y-tol,x+tol,y+tol,evt.mapPoint.spatialReference);
        selectionQuery.geometry = queryExtent;
        wellFeatureLayer.selectFeatures(selectionQuery,esri.layers.FeatureLayer.SELECTION_NEW);
      }
 
      //Handle resize of browser
      function resizeMap(){
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function(){
          map.resize();
          map.reposition();
        }, 500);
      }
 
      dojo.addOnLoad(init);
    </script> 
  </head> 
  <body class="tundra"> 
    <!--TOPMOST LAYOUT CONTAINER--> 
    <div id="mainWindow" dojotype="dijit.layout.BorderContainer" design="headline" gutters="false" style="width:100%; height:100%;"> 
      <!--HEADER SECTION--> 
      <div id="header" dojotype="dijit.layout.ContentPane" region="top" style="height:75px;"> 
        Click on a well to select the well and select the related well log information for that well.
      </div> 
      <!--CENTER SECTION--> 
      <!--CENTER CONTAINER--> 
      <div id="mapDiv" dojotype="dijit.layout.ContentPane" region="center" style="margin:5px;"> 
      </div> 
      <!--RIGHT CONTAINER--> 
      <div dojotype="dijit.layout.ContentPane" region="right" style="width:500px;margin:5px;background-color:whitesmoke;"> 
        <table dojoType="dojox.grid.DataGrid" jsid="grid" id="grid" rowsPerPage="5" rowSelector="20px" style="height:300px; width:300px"> 
          <thead> 
            <tr> 
              <th field="ObjectID">Object ID</th> 
            </tr> 
          </thead> 
        </table> 
      </div> 
    </div> 
  </body> 
  <body class="tundra"> 
 
  </body> 
</html>



Thanks in advance!

-Patrick
0 Kudos
2 Replies
derekswingley1
Deactivated User
You were almost there. The problem was hardcoding the reference to the 3rd object(array index 2) in the features array that comes back from your query task. I changed your query related records callback quite a bit to get it working:

function findRelatedRecords(features) {
  console.log('finding related records', features, features.length);
  var relatedTopsQuery = new esri.tasks.RelationshipQuery();
  relatedTopsQuery.outFields = ["*"];
  relatedTopsQuery.relationshipId = 3;
  // Create array of objectIds
  var ids = dojo.map(features, function (f) {
    return f.attributes.ObjectID;
  });
  console.log('ids: ', ids);
  relatedTopsQuery.objectIds = ids;
  wellFeatureLayer.queryRelatedFeatures(relatedTopsQuery, function (recs) {
    console.log('related: ', recs);
    // Build an array for the grid
    var items = [];
    // Recs is an object where each property is the objectid for a feautre
    // with related records
    for (id in recs) {
      // For each related record, create an item which will correspond to
      // a row in the data grid
      dojo.forEach(recs[id].features, function (feat) {
        items.push(feat.attributes);
      });
    }
    //Create data object to be used in store
    var data = {
      // Identifier and label are case-sensitive
      identifier: "OBJECTID",
      //This field needs to have unique values
      label: "OBJECTID",
      items: items
    };

    //Create data store and bind to grid.
    store = new dojo.data.ItemFileReadStore({
      data: data
    });
    grid.setStore(store);
    grid.setQuery({
      OBJECTID: '*'
    });
  });
}


Also, the label, identifier and field (this part:  <th field="OBJECTID">Object ID</th>) names for data grids are case-sensitive.

Last thing would be to upgrade to version 2.4 of the API.
0 Kudos
deleted-user-K_IRAXrpGKsG
Deactivated User
That worked just fine, thanks for helping.

I do however have another issue. I'm trying to relate tables that hold information about events.
One event will hold the live site with the actual physical conference, and two or three other locations will hold video events and will broadcast the event via webcam.

If there are 3 events  (1 physical and 2 video) they all have the same "EventID" which was the reason for running the related query.

This would allow the user to see all three events when they click on just one, which is the same as the well example given by ESRI's JavaScript.

Here is a link the data on arcServer, if you have a chance, please look at the data on the server and compare it to my code. http://studentgisserver.uww.edu/ArcGIS/rest/services/VirtualTraining1/MapServer/1



Thanks so much for the help!
I'm a student and am brand new to this stuff!
0 Kudos