Changing source data in a layer within an mxd using arcpy.mapping

251
1
01-19-2012 10:37 AM
JoshuaChan
New Contributor III
I want to change the source data of a layer within my mxd using arcpy.mapping

I found something promsing here and here.

My template layerfile points to "T:\temp_data.gdb\DimensionsFC" and I want to redirect the source to be "T:\temp_data_userid.gdb\DimensionsFC"

I've tried lyr.findAndReplaceWorkspacePaths but it didn't seem to do anything. Here's my code snippet:

    upLyr = arcpy.mapping.ListLayers(mxd, "Dimensions", df)[0]
    
    gp.AddMessage("Dimensions data original : ")
    gp.AddMessage(upLyr.dataSource)
    # this is the source layer that has the symbology in it
    srcLyr = arcpy.mapping.Layer(r"W:\srm\sry\Workarea\land_officers\map_robot\TechieStuff\template_dimensions.lyr")
      
    arcpy.AddMessage("updating the Dimensions layer")
    # doing the actual layer update here
    arcpy.mapping.UpdateLayer(df, upLyr, srcLyr, False)
    
    oldsrc = upLyr.workspacePath  # the old (current) data source

    lyr.findAndReplaceWorkspacePath(oldsrc, tmpfgdb)  # changing to the user's fgdb

    gp.AddMessage(tmpfgdb + ' is my temp fgdb name')
    gp.AddMessage("Dimensions data source changed: ")
    gp.AddMessage(upLyr.dataSource)
    gp.AddMessage(DimFC + ' is my dimensions FC')



after doing all that and looking at the "add message" statements it looks like nothing has changed. The mxd's lyr called "Dimensions" still has the original source.

Any help please?


P.S.: I think there's typo in the example in the first link. probably should not have an "s" at the end of "findAndReplaceWorkspacePaths".
When I tried it with the "s" it bombed. But if I used it without the "S" as it's printed in the other help page it seemed to execute without the error.
0 Kudos
1 Reply
JoshuaChan
New Contributor III
One of my genius co-workers discovered the fix for this.

I had the wrong impression of how UpdateLayer works. The UpdateLayer seems to plunk the "source_layer" into your mxd. 

I was trying to change the update layer but it no longer exists in the mxd. So I have to change the source_layer (my .lyr file) with
srcLyr.replaceDataSource(tmpfgdb, "FILEGDB_WORKSPACE", "DimensionsFC")


then the one visible in my mxd will have the correct data source. As long as i don't save, I won't overwrite my original .lyr file (i hope)

overall, the updateLayer works opposite from what I thought.
0 Kudos