2

I’m having a requirement, where I guess I’ve to use Dynamic DML.But I’m new to Dynamic Apex as well as Dynamic DML.

When I will create a Folder in Box.com server by using API call, I will get a response with Folder ID. (Well I’m able to make the API call and able to get Folder ID)

I am having a custom field named “FolderID__c” in Account object.

So I have to write a method which will take 2 parameter .One is objecttype and other is folderID and it will do the insert operation in that particular objectType.(maybe it’s Account, maybe Contact , which should be dynamic).

What I have done so far:

String IdVar = ApexPages.CurrentPage().getparameters().get('id');  //It will fetch the record ID
String objecttype = IdVar.getSobjectType().getDescribe().getName(); //It will fetch object type from record ID
//By using API call I’m able to get folderID. So I’m having folder ID
//Below is the method, which will update FolderID in our sObject dynamically.
   public static updateFolderId(String folderID){
   Account acc=new Account();
   SObject s = new Account(); 
   s.put(FolderID__c,folderID);
   acc=(Account)s;
   update acc;                   
}

Here I know that I am working on Account object, so I can easily type cast the Account object. But in dynamic we don't know in which object we would be working on, so how to typecast it dynamically.

3 Answers 3

3

I would suggest instead of using concrete objects such as Account, Contact etc. you use the generic SObject type instead making it fully dynamic, for example:

// create instance of types dynamically
SObjectType accountType = Schema.getGlobalDescribe().get('Account');
SObject acc = accountType.newSObject();

// modify values using .put notation
acc.put('Name','Some Name');

insert acc;
id accId = acc.Id;

// read back dynamically and modify again using .put notation if necessary
acc = Database.query('Select Name From Account Where Id = :accId');

System.debug( acc.get('Name') );
1

You can use the below method which will use objtype and folderId as two arguments and dynamically create object modify the code for your requirement.

public dynamicSobject(String objtype,String folderId)
{
    SObjectType objectType  = Schema.getGlobalDescribe().get(objtype);
    SObject obj = objectType.newSObject();

    obj.put('Name','Some Name');

    insert obj;
    id accId = obj.Id;


}
0

Please refer the following link for Dynamic DML

2
  • Hey @codebandit, kudos for answering but can you add some more info to the answer? The thing with links is that they can get broken over time :)
    – Matt Lacey
    Nov 25, 2013 at 9:33
  • @codebandit: I have updated the code in my question. There I'm working on Account. But I want it to be worked dynamically. I'm totally new to dynamic thing, so it'd be great, if you could give some more information. Nov 25, 2013 at 10:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .