You need to sign in to do that
Don't have an account?
Creating objects dynamically by getting fields values from JSON string
Hello there,
I get a JSON string from Javascript remoting function like this: '{"Name":"abc", "City":"xyz", "SobjectType":"Contact", "RecordTypeId":"Ab162EqwQDS5"}';
Now, I want to create sObject according to the field values received into the above string. How can I do this?
I refered Serialize and Deserialize methods of Apex JSON, however, they need ApexType as destination Class. They does not convert values directly into sObjects.
Shall I use JSON Parser methods? If yes then how?
Thanks in advance.
I get a JSON string from Javascript remoting function like this: '{"Name":"abc", "City":"xyz", "SobjectType":"Contact", "RecordTypeId":"Ab162EqwQDS5"}';
Now, I want to create sObject according to the field values received into the above string. How can I do this?
I refered Serialize and Deserialize methods of Apex JSON, however, they need ApexType as destination Class. They does not convert values directly into sObjects.
Shall I use JSON Parser methods? If yes then how?
Thanks in advance.
public static Boolean InsertSOjects(String sObjectApiName, String jSONSObject)
{
Map<String, Object> fieldMap = (Map<String, Object>)JSON.deserializeUntyped(jSONSObject);
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(sObjectApiName);
SObject newSobject = targetType.newSObject();
Map<String, Schema.sObjectField> targetFields = targetType.getDescribe().fields.getMap();
for (String key : fieldMap.keySet())
{
Object value = fieldMap.get(key);
Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType();
if (value instanceof String && valueType != Schema.DisplayType.String)
{
String svalue = (String)value;
if (valueType == Schema.DisplayType.Date)
newSobject.put(key, Date.valueOf(svalue));
else if(valueType == Schema.DisplayType.DateTime)
newSobject.put(key, DateTime.valueOfGmt(svalue));
else if (valueType == Schema.DisplayType.Percent || valueType == Schema.DisplayType.Currency)
newSobject.put(key, svalue == '' ? null : Decimal.valueOf(svalue));
else if (valueType == Schema.DisplayType.Double)
newSobject.put(key, svalue == '' ? null : Double.valueOf(svalue));
else if (valueType == Schema.DisplayType.Integer)
newSobject.put(key, Integer.valueOf(svalue));
else if (valueType == Schema.DisplayType.Base64)
newSobject.put(key, Blob.valueOf(svalue));
else
newSobject.put(key, svalue);
}
else
newSobject.put(key, value);
}
insert newSobject;
}
All Answers
Regards,
- Harsha
public static Boolean InsertSOjects(String sObjectApiName, String jSONSObject)
{
Map<String, Object> fieldMap = (Map<String, Object>)JSON.deserializeUntyped(jSONSObject);
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(sObjectApiName);
SObject newSobject = targetType.newSObject();
Map<String, Schema.sObjectField> targetFields = targetType.getDescribe().fields.getMap();
for (String key : fieldMap.keySet())
{
Object value = fieldMap.get(key);
Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType();
if (value instanceof String && valueType != Schema.DisplayType.String)
{
String svalue = (String)value;
if (valueType == Schema.DisplayType.Date)
newSobject.put(key, Date.valueOf(svalue));
else if(valueType == Schema.DisplayType.DateTime)
newSobject.put(key, DateTime.valueOfGmt(svalue));
else if (valueType == Schema.DisplayType.Percent || valueType == Schema.DisplayType.Currency)
newSobject.put(key, svalue == '' ? null : Decimal.valueOf(svalue));
else if (valueType == Schema.DisplayType.Double)
newSobject.put(key, svalue == '' ? null : Double.valueOf(svalue));
else if (valueType == Schema.DisplayType.Integer)
newSobject.put(key, Integer.valueOf(svalue));
else if (valueType == Schema.DisplayType.Base64)
newSobject.put(key, Blob.valueOf(svalue));
else
newSobject.put(key, svalue);
}
else
newSobject.put(key, value);
}
insert newSobject;
}
I have one requirement,
Actually using below code i save object record in database dynamically.
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(strFieldName);
SObject myObj = targetType.newSObject();
insert myObj;
Note:using above code related object record only created.ButFields information is not saved.Here Fields add visualforce page Dynamically
but I gave some fields information here but those fields information is not saved in this record
How to save fields information also related object record Dynamically?
help me...............
Line 1: gets object type.
Line 2: creates sObject of the fetched object type.
Line 3: inserts record of that object type.
You no where are referncing fields here.
Tell me the exact scenario that what exactly you want to do.
I see the issue. On Save button, you are simply creating a blank record of some sObject. However, you are displaying all fields on your visualforce page. You need to bind those input fields on your visualforce page with the sObject that you are creating on Save button's action function.
Solution:
1. Create sObject record in Controller's constructor itself.
2. Bind that sObject recod's fields to input fields on your Visualforce page.
3. On Save button, just write code for insertion of that sObject record.
Using metadata api every time i will create fields.Those fields add to this visualforce page dynamically.With out adding fields to sobject every time tell me there is any solution.
Dynamically how to save thesfields in database?
Note:Here my object also Dynamically comming how i use controller's constructor
I try to this task from1 week
help me..............
public void doSave()
{
if( sObjectToBind != null )
insert sObjectToBind;
}
It's fine but some time i got this error
System.DmlException: Insert failed. First exception on row 0 with id a0D9000000BbcSQEAZ; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Like,
Contact.firstname =Right!
Contact.Accountid = Right!
Contact.Account.AccountName = Wrong!
Make sure you are not doing this.
Super sir .Thank you very much.In an visualforce page my owner text field will be visible .How to give owner field as read only in an visualforce page every time object comming time Here ?
How to add above page .
Your only my project finished sir......................
<apex:inputField value="{!Contact.name}"/> - displaying input field for Contact.Name
I want to Owner field automatically how to assign without using lookup Dynamically in an above page?
Note:I am a administrator
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'your.username@example.com' ];
2. Assign it to sObject owner:
if( lstUser != null && !lstUser.isEmpty() )
sObject.OwnerId = lstUser[0].Id;
This is my object
string strFieldName = 'rajesh__'+strtemp + '__c';
In above code only i am asking.How to fix owner name .
public void doSave()
{
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'your.username@example.com' ];
if( sObjectToBind != null && lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);
insert sObjectToBind;
}
Owner field Editable only not access my username at owner location.
I didn't understand the error. Can you please paste it here as it is?
When all field edit ,on that time Owner field Locaton I want my owner name.Don't use Lookup functionality how to fix my owner name owner field location everytime .
When enter Edit fields location means above code.I want My Owner name automatically how to add Owner location?
YES
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'your.username@example.com' ];
if( lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);
And remove same from doSave()
I added like this but my owner name is not came
DynamicBindingCls(){
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'rajesh k' ];
if( lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);
}
I will use like this means Got error
DynamicBindingCls(){
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'rajesh060708@gmail.com' ];
if( lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);
}
I got following error
System.NullPointerException: Attempt to de-reference a null object
Class.rajesh.DynamicBindingCls.<init>: line 62, column 1
line 62:sObjectToBind.put('OwnerId', lstUser[0].Id);
{
strtemp=ApexPages.currentPage().getParameters().get('DNF');
string objectname ='rajesh__'+strtemp+'__c';
listObjectFields = new List<String>();
Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
Schema.sObjectType sObjType = globalDescription.get(objectname);
//take care of the sequence of following 5 statements
sObjectToBind = sObjType.newSObject();
Schema.DescribeSObjectResult r1 = sObjType.getDescribe();
List<User> lstUser = [ SELECT Id FROM User WHERE Username = 'rajesh060708@gmail.com' ];
if( sObjectToBind != null && lstUser != null && !lstUser.isEmpty() )
sObjectToBind.put('OwnerId', lstUser[0].Id);
Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap();
Integer i = 0;
for(Schema.SObjectField field : mapFieldList.values())
{
Schema.DescribeFieldResult fieldResult = field.getDescribe();
if(fieldResult.isAccessible() && fieldResult.isUpdateable())
{
listObjectFields.add(fieldResult.getName());
}
}
}
Your super Sir.............................
Thank you very much............................
Hi,
I completed My MCA 2013 Batch.Now I have 8 months(Nov 2013 to present in chennai) of Experience.I completed Project on metadata api.There is any requirement please Inform me
My mail id:mahesh060708@gmail.com
Thanks!
Dynamically comming multipicklist fields how to find and display these fields as checkboxes Dynamically how?
please help me..........
How to display dynamically comming multiselectpicklistvalues as checkboxes in an visualforce page?