Can we Cast SObject dynamically in Salesforce(apex)? - salesforce

Is it possible to Cast SObject dynamically?
Example :
I know we can do this :
(Account) Sobject
But I want to do this as the return type of sObject changes based on certain parameters.
(Dynamically Passing the Name) SObject
Any Kind of way around will be helpful... Thanks in advance :)

Yes, you can do it. For example -
Class ABC {
public static List<Object> method1(String sObjectType){
List<Object> records = new List<Object>();
if(sObjectType == 'Account'){
records = [SELECT Id, Name FROM Account];
} else if(sObjectType == 'Account'){
records = [SELECT Id, Name FROM Contact];
}
return records;
}
}
You can check the sObject Type of List -
if(records instanceof List<Account>){
// your code here
} else if(records instanceof List<Contact>){
// your code here
}

Unfortunately, no. I ran into this recently while writing a TestFactory class. The best I could do was cast the responses back into the expected type in the code that was calling the TestFactory's methods.

Related

Salesforce : Apex test class for the getting trending articles of Knowledge from Community

I need to get trending articles from the community. I created a apex class for that by using ConnectApi.Knowledge.getTrendingArticles(communityId, maxResult).
I need to create a test class for that. I am using test class method provided by Salesforce for that. setTestGetTrendingArticles(communityId, maxResults, result) but I am getting this error "System.AssertException: Assertion Failed: No matching test result found for Knowledge.getTrendingArticles(String communityId, Integer maxResults). Before calling this, call Knowledge.setTestGetTrendingArticles(String communityId, Integer maxResults, ConnectApi.KnowledgeArticleVersionCollection result) to set the expected test result."
public without sharing class ConnectTopicCatalogController {
#AuraEnabled(cacheable=true)
public static List<ConnectApi.KnowledgeArticleVersion> getAllTrendingArticles(){
string commId = [Select Id from Network where Name = 'Customer Community v5'].Id;
ConnectApi.KnowledgeArticleVersionCollection mtCollection = ConnectApi.Knowledge.getTrendingArticles(commId, 12);
System.debug('getAllTrendingTopics '+JSON.serializePretty(mtCollection.items));
List<ConnectApi.KnowledgeArticleVersion> topicList = new List<ConnectApi.KnowledgeArticleVersion>();
for(ConnectApi.KnowledgeArticleVersion mtopic : mtCollection.items)
{
topicList.add(mtopic);
}
return topicList;
}
}
Test class that I am using for this
public class ConnectTopicCatalogControllerTest {
public static final string communityId = [Select Id from Network where Name = 'Customer Community v5'].Id;
#isTest
static void getTrendingArticles(){
ConnectApi.KnowledgeArticleVersionCollection knowledgeResult = new ConnectApi.KnowledgeArticleVersionCollection();
List<ConnectApi.KnowledgeArticleVersion> know = new List<ConnectApi.KnowledgeArticleVersion>();
know.add(new ConnectApi.KnowledgeArticleVersion());
know.add(new ConnectApi.KnowledgeArticleVersion());
system.debug('know '+know);
knowledgeResult.items = know;
// Set the test data
ConnectApi.Knowledge.setTestGetTrendingArticles(null, 12, knowledgeResult);
List<ConnectApi.KnowledgeArticleVersion> res = ConnectTopicCatalogController.getAllTrendingArticles();
// The method returns the test page, which we know has two items in it.
Test.startTest();
System.assertEquals(12, res.size());
Test.stopTest();
}
}
I need help to solve the test class
Thanks.
Your controller expects the articles to be inside the 'Customer Community v5' community, but you are passing the communityId parameter as null to the setTestGetTrendingArticles method.

Get a field value from a SObject List (Apex)

I'm facing with the current problem.
I have the following code which is a list of SObject and I want to get "CreatedDate" field.
I really appreciate ur time and comments, thanks.
public static Object testMeth() {
List<SObject> leadsAndOpps = new List<SObject>();
List<Lead> lstLead = [Select Id, Name, CreatedDate FROM Lead];
List<Opportunity> lstOpp = [Select Id, Name, CreatedDate FROM Opportunity];
//Assign first and second List to Sobject List
leadsAndOpps.addAll(lstLead);
leadsAndOpps.addAll(lstOpp);
for(SObject lstExa : leadsAndOpps) {
String getName = (String)lstExa.get('Name'); = This example works cool
DateTime getDateVal = (DateTime)lstExa.get(CreatedDate); = Variable doesn't exists
}
return leadsAndOpps;
}
The SObject.get() method is expecting a string representing the field API Name. If you put 'CreatedDate' in quotes, it should be fine. What you are passing in now is perceived as an undeclared variable named CreatedDate.

Merge field value is not showing in email template when it send by apex

I have an email template which I want to send by apex class.I am getting an Email notification but merge field's value is not showing.I tried many solutions but not getting the result.Please, can anyone help me?
Here is the snap of my email template
Email template
And apex code:-
global class sampleBatch implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext bc) {
String query = 'Select id,Name from book__c;
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc, List<book__c> books){
Map<Id, List<Case>> associatedCases = CaseHelperClass.getCase(new Map<Id,book__c>(books).keySet());
Map<Id,book__c> bookMap= new Map<Id,book__c>(books);
EmailTemplate emailTemplate = [SELECT Id,Subject,Description,HtmlValue,DeveloperName,Body FROM EmailTemplate WHERE DeveloperName =: 'sameple_template'];
if(associatedCases <> null){
for(Id bookId : associatedCases.keySet()){
String headerAndAssociatedCases = 'CaseNumber,Type,Status,Subject,Description,CreatedDate\n';
for(Case c : associatedCases.get(bookId)){
headerAndAssociatedCases += c.CaseNumber+','+c.Type+','+c.Status+','+c.Subject+','+c.Description+','+c.CreatedDate+'\n';
}
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(headerAndAssociatedCases);
csvAttachment.setFileName('Case.csv');
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
list<string> toAddresses = new list<string>{name#test.com};
email.setSubject(emailTemplate.Subject);
email.setTemplateId(emailTemplate.Id);
email.setPlainTextBody(emailTemplate.Body);
email.setToAddresses(toAddresses);
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
}
global void finish(Database.BatchableContext bc){
system.debug('Apex Job Done');
}}
Any help will be highly appreciable.
Thank you!
Please refer to the requirements of the SingleEmail method:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm
Specifically refer to the below:
setTargetObjectId(targetObjectId)
Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.
setWhatId(whatId)
If you specify a contact for the targetObjectId field, you can specify an optional whatId as well. This helps to further ensure that merge fields in the template contain the correct data.
I don't see either of these methods in your code.

create a new Apex Class to update field with Active or inactive

This is my fist time with Apex so Im fumbling around. What I am trying to do is read a date field Contract_Expiration__c and then set pdate_active_status_text__c to null, active, or void.
Any help would be great. Thanks in advance.
public class update_active_status {
public static String saveData(){
for (Account a : [SELECT Id FROM Account WHERE CreatedDate > 2000-01-16T10:00:00-08:00]){
if (a.Contract_Expiration__c == null ){
a.update_active_status_text__c = null;
update a;
} else if (a.Contract_Expiration__c >= Date.today().addDays(60)) {
a.update_active_status_text__c = 'Active';
update a;
} else {
a.update_active_status_text__c = 'Void';
update a;
}
}
}
}
You need to add the fields to modify/check to your query in order for that method to work:
[SELECT Id, Contract_Expiration__c, update_active_status_text__c FROM Account WHERE CreatedDate > 2000-01-16T10:00:00-08:00]
Also that method needs to return a String (but the compiler should have complained about it already).
And finally, the approach of selecting all accounts created from a given date does not seem nice on the long run.

pass list<string> as parameter to webservice

Please help!!
What is the correct way to send List of String as a parameter to webservice ?
List < SObject > ObjectContents; // {get; set;} contains records of selected object
List str3 = new List ();
String FormattedValue;
for (SObject a : for (SObject a : ObjectContents)) // for (SObject a : ObjectContents)
{
for(String field:fieldApis){ // fieldApis contains list of fieldnames
FormattedValue = '\'' + a.get(field) + '\'' ; //fetches value of each field
}
str3.add(FormattedValue );
}
//sending data to webservice
sqlArray19.ArrayOfstring a= new sqlArray19.ArrayOfstring();
SQLServerConnector9.BasicHttpBinding_IService1 stub = new SQLServerConnector9.BasicHttpBinding_IService1();
//sqlArray19 and SQLServerConnector9 classes were formed while importing wsdl into Salesforce
List<String> insertMsg = stub.InsertQuery(str3); // getting error in this line
"Compile Error: Method does not exist or incorrect signature: [SQLServerConnector9.BasicHttpBinding_IService1].InsertQuery(LIST<String>)"
.net webservice which will fetch values from Salesforce and return those values
public List<String> InsertQuery(List<String> Values)
{
return Values ;
}
Collections can be troublesome data types when working across platforms with web services. Try converting your List into a string[] (and changing your method, of course).

Resources