• swain 10
• NEWBIE
• 136 Points
• Member since 2017

• Chatter
Feed
• 0
Best Answers
• 0
Likes Received
• 0
Likes Given
• 51
Questions
• 33
Replies
Text Field(hours) = (a.StartDateTimeField.date().daysBetween(EndDateTimeField.date()) *24));

How to round off the value to nearest 0.5 example if the value is 24.3 then round to 24 if 24.6 then 25 if 24.5 then(24 or 25). How to do that?
My scenario , when a Parent account is added to a Child account then the value(sum of all child) of  one field should updated to the Parent Account Field.
Total_Lease_Area_SF_from_Children__c (Number Field) needs to get updated in parent account from the Total_Account_Child_Lease_Area_SF__c(Formula Field) of child Account.
Note:- Total_Account_Child_Lease_Area_SF__c(Formula Field) is the sum of all child till that heirrachy updated by Total_Lease_Area_SF_from_Children__c (Number Field). But When a new account is added to an existing Account parent account field is not geeting updated.

trigger AccLeaseUpdate on Account   (after update, after delete) {

set<id> ParentIds = new set<id>();
if(Trigger.isupdate){
For(Account acc: Trigger.new){
ParentIds.add(acc.ParentId);
}
}
if(Trigger.isDelete){
For(Account acc: Trigger.old){
ParentIds.add(acc.ParentId);
}
}
/*   List<account> accountToUpdate = new List<account>();

decimal sum = 0;
if(Trigger.isupdate || trigger.isdelete){

For(account q : [SELECT Total_Lease_Area_SF_from_Children__c ,ParentId ,(SELECT id,Total_Lease_Area_SF_from_Children__c,Total_Account_Child_Lease_Area_SF__c FROM  ChildAccounts) FROM account WHERE id =: ParentIds]){
if(q.ParentId!= null && q.Total_Lease_Area_SF__c!= null){
sum = 0;
for(Account p : q.ChildAccounts){
//    for(Account ap : trigger.new){
//      Account myParentAcc = aq.get(p.ParentId);

sum = sum +p.Total_Lease_Area_SF_from_Children__c;
q.Total_Lease_Area_SF_from_Children__c= sum  ;
//   myParentAcc.Total_Lease_Area_SF_from_Children__c = sum;
}
}
try{
update accountToUpdate ;
}Catch(Exception e){
System.debug('Exception :'+e.getMessage());
}

}

accountToUpdate.add(q);
}
}*/
I need is to override the default behavior of SFDC with regards to setting the Primary Campaign Source in Opportunities.  We want is the FIRST RESPONDED Campaign of the Primary contact to be the Primary Campaign Source. How can I do that for FIRST RESPONDED Campaign.

I need help for this.
global class EcommerceToUnitOfUseInShowingsBatchJob implements Database.Batchable<sObject> {

String query;
private List<Id> showingIds;
private List<Showing__c> showingObj;

global EcommerceToUnitOfUseInShowingsBatchJob() {

}

global EcommerceToUnitOfUseInShowingsBatchJob(List<Showing__c> parameter) {
showingObj=parameter;
}

global Database.QueryLocator start(Database.BatchableContext BC) {
query = 'SELECT Id, Account__c, Ecommerce__c, Use_of_Unit__c From Showing__c where Ecommerce__C !=null  and Unit__r.RecordType.Name=\'Active\'';
if (null != showingIds && !showingIds.isEmpty()) {
query += ' ANd Id IN :showingIds';
}
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<sObject> scope) {
Map<Id,Showing__c> showingsToUpdate = new Map<Id,Showing__c>();
List<Showing__c> showingsIds = (List<Showing__c>) scope;

for( Showing__c shwng : showingsIds)
{
List<Account> accounts = [SELECT Id from Account WHERE Id=:shwng.Account__c];
if (!accounts.isEmpty() || null == shwng.Account__c) {
if('Yes'.equals(shwng.Ecommerce__c)) {
shwng.Use_of_Unit__c='E-Commerce';
showingsToUpdate.put(shwng.Id,shwng);
} else if('No'.equals(shwng.Ecommerce__c) || 'Unknown'.equals(shwng.Ecommerce__c)) {
shwng.Use_of_Unit__c='';
showingsToUpdate.put(shwng.Id,shwng);
}
}
}

if (!showingsToUpdate.isEmpty()) {
update(showingsToUpdate.values());
}
}

global void finish(Database.BatchableContext BC) {

}

}
select Customer__r.Name,CDP_Asset__r.Deal__r.Name,CDP_Asset__r.Deal__r.Market__r.Name,CDP_Asset__r.Deal__r.Type__c,CDP_Asset__r.Deal__r.Stage__c from CDP_Asset_Customer_Account__c where Customer__r.Id IN ('001U000000SunAAIAZ')

I am getting [Object Object] in the querry result for the 2nd value in developer console and so in my component.
But its working fine in workbench . how to resolve?
Hi I am writting a Validation for restricting editing of some field and only giving access 3 user having Profile Admin , User name xyz and Record owner. But my logic is failing . I used different way but infortunate . Please help.
AND( ISCHANGED( BusinessStrategy__c ),ISCHANGED( BusinessStrategyComments__c ),ISCHANGED( DecisionDrivers__c ),ISCHANGED( DecisionDriversComments__c ),ISCHANGED( CustomerOwnerInsight1__c ),ISCHANGED( CustomerOwnerInsight1Comment__c ),ISCHANGED( CustomerOwnerInsight2__c ),ISCHANGED( CustomerOwnerInsight2Comment__c ),ISCHANGED( CustomerOwnerInsight3__c ),ISCHANGED( CustomerOwnerInsight3Comment__c ),AND(
\$Profile.Name <> 'System Administrator' ,
\$User.Email <> 'scallaway@prologis.com' ,
\$User.Id <> Owner.Id ))

I am getting this error while editing fields in the action publisher layout place in a tab using related record lightning component.
I am not getting , even this profile have read and write permission for this field in Object setting of profile.
I want to create a instance of account to update some field related to that accountRecord during lead conversion.
I am getting Illegal assignment from SObject to Account. How to resolve that?

Account ac = lc.getAccountRecord();
public class OV_Flw_SearchDNB {
public static String  FIELD_DELIMITER = ',';

public static String  generateURL(String baseURL,String[] searchFields) {
String url =baseURL+'/v1/match/cleanseMatch';
system.debug('url-----'+url);
system.debug('---baseURL---'+baseURL);
System.debug('--Searchfields---'+searchFields);
Integer count=0;
for(String field : searchFields){

String[] fieldPair=field.split('=');
System.debug('-----Search Conditions---------->'+fieldPair+'<----');
if(fieldPair[1]!=' ' && fieldPair[1]!=''&& fieldPair[1]!='  '){
if(fieldPair[0].trim()=='countryISOAlpha2Code'){
fieldPair[1]=getCountryCode(fieldPair[1].trim());
}
if(fieldPair[0].trim()=='addressRegion'){
fieldPair[1]=getStateCode(fieldPair[1].trim());
}
if(count==0){
url=url+'?'+fieldPair[0].trim()+'='+EncodingUtil.urlEncode(fieldPair[1].trim(), 'UTF-8');
}else{
url=url+'&'+fieldPair[0].trim()+'='+EncodingUtil.urlEncode(fieldPair[1].trim(), 'UTF-8');
}
count++;
}
}
url=url+'&'+getConfig();
System.debug('-----Search url---------->'+url);
return url;
}

public static String getConfig(){
String configuration='';
DNB_Configuration__mdt[]  conf = [SELECT candidateMaximumQuantity__c,confidenceLowerLevelThresholdValue__c
FROM DNB_Configuration__mdt  ];
configuration = 'candidateMaximumQuantity='+conf[0].
candidateMaximumQuantity__c+'&confidenceLowerLevelThresholdValue='+conf[0].confidenceLowerLevelThresholdValue__c;
return   configuration;
}

public static Ext_Authentication__c getAuth(){
Ext_Authentication__c[]  auth = [SELECT EndPoint_Test__c ,EndPoint__c,Username__C, Password__c,
Token__c,Token_Expiration_DT__c,Token_Creation_DT__c  FROM Ext_Authentication__c];

System.debug('************auth********** '+auth[0]);
return    auth[0];
}

public static Boolean isSandBox(){
Organization[]  org = [SELECT Id, IsSandbox FROM Organization];
return    org[0].IsSandbox;
}

public static void  updateAuth(String token){
Ext_Authentication__c authentication = getAuth();
authentication.Token__c=token;
authentication.Token_Creation_DT__c=system.now();
authentication.Token_Expiration_DT__c=system.now().addHours(24);
upsert(authentication);
}
/**
* This method return country code for the country
* @param country - country name
*/
public static String  getCountryCode(String country){
String cc='US';
Schema.DescribeFieldResult fieldResult = User.CountryCode.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
System.debug('Picklist::'+ple);
for( Schema.PicklistEntry f : ple){
if(country.trim()==f.getLabel()){
cc= f.getValue();
}
// System.debug(f.getLabel() +':---:'+ f.getValue());
}
return cc;
}
/**
* This method return State code for the State
* @param country - country name
*/
public static String  getStateCode(String state){
String SC='CO';
Schema.DescribeFieldResult fieldResult = User.StateCode.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
System.debug('Picklist::'+ple);
for( Schema.PicklistEntry f : ple){
if(state.trim()==f.getLabel()){
SC= f.getValue();
}
// System.debug(f.getLabel() +':---:'+ f.getValue());
}
return SC;
}
/**
* This method return the url ,which request to DNB

public static String  getDNBData(String baseURL,String[] searchFields,Ext_Authentication__c auth) {
String response;
String searchURL    =    generateURL(baseURL,searchFields);
String token =getAccessToken(baseURL,auth);
try{
HttpRequest req = new HttpRequest();
Http http = new Http();
req.setEndpoint(searchURL);
req.setMethod('GET');
String authorizationHeader = 'Bearer '+    token;
req.setHeader('Authorization',authorizationHeader);
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
HTTPResponse res = http.send(req);
//  System.debug('-------searchURL-------->'+searchURL+'---------');
//  System.debug('-------authorizationHeader-------->'+authorizationHeader);
//  System.debug('-------response-------->'+res);
response=res.getBody();
{"componentType":"National ID","componentValue":"98"},{"componentType":"URL","componentValue":"98"}],"nameMatchScore":100.0}}],"cleanseAndStandardizeInformation":{}}';
//  System.debug('-------vv-------->'+response);
if(isTokenExpired(auth.Token_Expiration_DT__c)){
updateAuth(token);
}

}catch(Exception e){
//  System.debug('--getDNBData--Error--:'+e.getCause());
//  System.debug('--getDNBData--Error--:'+e.getMessage());
//  System.debug('--getDNBData--Error--:'+e.getStackTraceString());
}
return response;
}
/**
* This method will check the Token is expired or not
* @param DateTime - date time available in Auth
* @return boolen - return the token is expired or not
*/
public static Boolean isTokenExpired(Datetime expDate){
Datetime myDate = system.now();
return expDate<=myDate;
}
/**
* This method check the access token if it valid it will use else it will create a new one
* @param baseURL - The base dnb url
* @param searchFields - The search condition
* @return url
*/
public static String getAccessToken(String url,Ext_Authentication__c auth) {
String accessToken='';
Boolean isTokenValid=false;
Boolean isTokenExpired=false;
try{
HttpRequest req = new HttpRequest();
Http http = new Http();
req.setEndpoint(url+'/v2/token');
req.setMethod('POST');
isTokenValid =    auth.Token__c != null?true:false;
isTokenExpired    =    isTokenExpired(auth.Token_Expiration_DT__c);
//  System.debug('--------isTokenValid------->'+isTokenValid);
//  System.debug('--------isTokenExpired------->'+isTokenExpired);
if(isTokenValid && !isTokenExpired){
accessToken =  auth.Token__c;
}else{
String username = auth.Username__C;
String password = auth.Password__c;
Blob headerValue = Blob.valueOf(username+':'+password);
String authorizationHeader = 'Basic '+EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization',authorizationHeader);
req.setHeader('Content-Type', 'application/json');
req.setHeader('Cache-Control', 'no-cache');
req.setBody('{ \"grant_type\" : \"client_credentials\" }');
HTTPResponse res = http.send(req);
Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
//   System.debug('-------vv-------->'+m);
//   System.debug('--------------->'+authorizationHeader);
accessToken =(String)m.get('access_token');
//   System.debug('-------accessToken-------->'+accessToken);

}
return accessToken;
}catch(Exception e){
//   System.debug('--getAccessToken--Error-:'+e.getCause());
//   System.debug('--getAccessToken--Error--:'+e.getMessage());
//   System.debug('--getAccessToken--Error--:'+e.getStackTraceString());
}
return null;
}
public static void search() {
List<List<String>> config = new List<List<String>>();
List<String> sconfig = new List<String>();
sconfig.add('Primary Name, Trade Style Name, Street, Region,City, Country');
//sconfig.add('matchCandidates.organization.primaryName, matchCandidates.organization.tradeStyleNames, matchCandidates.organization.primaryAddress.streetAddress.line1, matchCandidates.organization.primaryAddress.addressRegion.name, matchCandidates.organization.primaryAddress.addressLocality.name, matchCandidates.organization.primaryAddress.addressCountry.name');
// sconfig.add('{"matchCandidates":{"organization":["primaryName","tradeStyleNames.priority","primaryAddress:[streetAddress.line1,addressRegion.name,addressLocality.name,addressCountry.name]"]}}');
sconfig.add('primaryName, tradeStyleNames,addressLocality, addressCountry, streetAddress, addressLocality, abbreviatedName, addressCountry, websiteAddress' );
// sconfig.add('url= www.dnb.com, countryISOAlpha2Code= US, streetAddressLine1= street, addressRegion= NJ, addressCounty= Essex');
sconfig.add('name= GORMAN MANUFACTURING COMPANY,url= www.dnb.com, countryISOAlpha2Code= United States');
//sconfig.add('url= www.dnb.com, countryISOAlpha2Code= US');
// sconfig.add('url= www.dnb.com, countryISOAlpha2Code= US');
config.add(sconfig);
searchDNB(config);
}
/**
* This method will return trade style
* @param Map - JSON Map
* @return String - tradestylename
*/
public static String getTradeStyle(Map<String, Object> org) {
List<Object> traseStyleList =(List<Object>)org.get('tradeStyleNames');
if(traseStyleList.size()!=0){
Map<String, Object> traseStyleMap =(Map<String, Object>)traseStyleList.get(0);
return  (traseStyleMap.size()==0)?'':(String)traseStyleMap.get('name');
}
return '';
}
/**
* This method will return trade style
* @param Map - JSON Map
* @return String - tradestylename
*/
public static String getPhoneNumber(Map<String, Object> org) {
List<Object> phoneList =(List<Object>)org.get('telephone');
if(phoneList.size()!=0){
Map<String, Object> phoneMap =(Map<String, Object>)phoneList.get(0);
return  (phoneMap.size()==0)?'':(String)phoneMap.get('telephoneNumber');
}
return '';
}
/**
* This method will return trade style
* @param Map - JSON Map
* @return String - webaddress
*/
public static String getWebAddress(Map<String, Object> org) {
List<Object> urllist =( List<Object>)org.get('websiteAddress');
if(urllist.size()!=0){
Map<String,Object> urlMap =(Map<String,Object>)urllist.get(0);
return  (urlMap.size()==0)?'':(String)urlMap.get('url');
}
return '';
}
/**
* This method will return Address
* @param Map - JSON Map
* @return String - Address
*/
public static String getAddress(Map<String, Object> org,String Address,String subAddress,String name) {
Map<String,Object> addressMap =(Map<String,Object>)org.get(Address);
if(addressMap.size()!=0){
Map<String,Object> addressMap2 =(Map<String,Object>)addressMap.get(subAddress);
if(addressMap2.size()!=0){
return (String)addressMap2.get(name);
}
}
return '';
}
/**
* This method will connvert the string to JSON and do the data manupulation and finally return the required fields
* @param input - JSON response
* @return String - formated JSON
*/
public static String consolidateJSON(String input, String[] fectchfields) {
List<String> result= new List<String>();
try{
Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(input);
system.debug('---------map----------'+m);
List<Object>  matchCandidates = (List<Object>)m.get('matchCandidates');
if(matchCandidates==null){
return  '';
}
system.debug('---------matchCandidates----------'+matchCandidates);
for (Object mapcandidate: matchCandidates) {
Map<String,String> resultMap    =    new Map<String,String>();
Map<String, Object> m2 = (Map<String, Object>)mapcandidate;
Map<String, Object>  org = (Map<String, Object>)m2.get('organization');
resultMap.put('primaryName',(String)org.get('primaryName'));
resultMap.put('duns',(String)org.get('duns'));
resultMap.put('tradeStyleNames',getTradeStyle(org));
resultMap.put('phone',getPhoneNumber(org));
resultMap.put('streetAddress',getAddress(org,'primaryAddress','streetAddress','line1'));
resultMap.put('addressCountry',getAddress(org,'primaryAddress','addressCountry','name'));
resultMap.put('addressLocality',getAddress(org,'primaryAddress','addressLocality','name'));
resultMap.put('addressRegion',getAddress(org,'primaryAddress','addressRegion','name'));
resultMap.put('url',getWebAddress(org));
result.add(JSON.serialize(resultMap));
}
system.debug('------consolidateJSON---result----------'+result);
}catch(Exception ex){
system.debug('--consolidateJSON--Error--:'+ex.getStackTraceString());
system.debug('--consolidateJSON--Error--:'+ex.getMessage());
}
return JSON.serialize(result);
}
/**
* This method is the Main method
* @param Map - JSON Map
* @return String - webaddress
*/
@InvocableMethod(label='Saerch the DNB ' description='Give the configuration from Flow and search in DNB')
public static List<String> searchDNB(List<List<String>> config) {
List<String> finalResult = new List<String>();
Ext_Authentication__c auth =getAuth();
String dnbData = '';
String baseURL ='';
try{
String[] dispFields    =    config[0][0].split(FIELD_DELIMITER);
String[] fetchFields    =    config[0][1].split(FIELD_DELIMITER);
String[] searchFields    =    config[0][2].split(FIELD_DELIMITER);
if(!isSandBox()){
baseURL = auth.EndPoint__c;//'https://plus.dnb.com/';
}else{
baseURL = auth.EndPoint_Test__c;//'https://plus.dnb.com/';
}
system.debug('-------dispFields-----'+dispFields);
system.debug('-------fetchFields-----'+fetchFields);
system.debug('-------sources-----'+searchFields);
String JSONResponse =    getDNBData(baseURL,searchFields,auth);
if(JSONResponse==''){
return null;
}
dnbData = consolidateJSON(JSONResponse,fetchFields);
finalResult.add(dnbData);
if(finalResult.size()==0 || finalResult[0]=='[]'){
return null;
}
}catch(Exception ex){
system.debug('--searchDNB--Error--:'+ex.getStackTraceString());
system.debug('--searchDNB--Error--:'+ex.getMessage());
}
system.debug('--searchDNB---finalResult--:'+finalResult);
return finalResult;
}
}
Hi Everyone,
Please check below apex class  How to get code coverage currently  I am getting 32%

Class:
public class OV_FlwLeadConversion {
/**
* This method is used to Convert the Lead record to Account and contact
*/
@InvocableMethod(label=' ' description='')
public static List<String> convertLead(List<List<String>> configParams){
List<String> finalResult = new List<String>();
String status = 'Quick Entry Converted Successfully';
try{
String accountId=configParams[0][0];
String contactId=configParams[0][1];
String leadId=configParams[0][2];
String acctName=configParams[0][3];
String accountType=configParams[0][4];
String city=configParams[0][5];
String country=configParams[0][6];
String street=configParams[0][7];
String webSite=configParams[0][8];
String recordTypeId=configParams[0][9];

String firstName=configParams[0][10];
String lastName=configParams[0][11];
String title=configParams[0][12];
String email=configParams[0][13];
String role=configParams[0][15];
String accPhone=configParams[0][16];
String state=configParams[0][17];

system.debug('--accountId---'+accountId);
system.debug('--contactId---'+contactId);
system.debug('--leadId---'+leadId);
system.debug('--acctName---'+acctName);
system.debug('--accountType---'+accountType);
system.debug('--city---'+city);
system.debug('--country---'+country);
system.debug('--street---'+street);
system.debug('--webSite---'+webSite);
system.debug('--recordTypeId---'+recordTypeId);
system.debug('--firstName---'+firstName);
system.debug('--lastName---'+lastName);
system.debug('--title---'+title);
system.debug('--email---'+email);

String conRecordType;
Id conRecordTypeId;
system.debug('--accountType--:'+accountType);
system.debug('--configParams[0][4]--:'+configParams[0][4]);
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(leadId);
lc.setDoNotCreateOpportunity(true);
if(accountId != ''){
lc.setAccountId(accountId);
}
if(contactId != '' ){
lc.setContactId(contactId);
}
//LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
//lc.setConvertedStatus(convertStatus.MasterLabel);//Qualified
lc.setConvertedStatus('Qualified');
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.debug('--------``````----accountId------'+accountId);
System.debug('--------`````----contactId------'+contactId);
if(lcr.isSuccess()){
system.debug('-------isSuccess----------');
if((accountId == ''|| accountId==null) && (contactId=='' ||contactId == null)){
String recordTypeIds;
recordTypeIds = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get(accountType).getRecordTypeId();
system.debug('--recordTypeIdssssssssssssssssssssssssss---'+recordTypeIds);
Account acct = new Account();
acct.Id=lcr.getAccountId();
acct.name=acctName;
acct.BillingCountry=country;
acct.Website=webSite;
acct.BillingCity=city;
acct.BillingStreet=street;
acct.Type=accountType;
acct.RecordTypeId=recordTypeIds;
acct.Customer_Category__c='Unspecified';
acct.Phone=accPhone;
acct.BillingState=state;

upsert acct;
}
// This needs to be removed and put it in Config
if(accountType == 'Brokerage'){
conRecordType = 'Broker';
}else if(accountType == 'Prologis'){
conRecordType = 'Employee';
}else if(accountType == 'Venture Account'){
conRecordType = 'Venture Contact' ;
}else if(accountType == 'Other'){
conRecordType = 'Non Ventures' ;
}else{
conRecordType = accountType;
}
if(accountType!=null && accountType!=''){
conRecordTypeId = Schema.getGlobalDescribe().get('Contact').getDescribe().getRecordTypeInfosByName().get(conRecordType).getRecordTypeId();
system.debug('-------conRecordTypeId----------'+conRecordTypeId);
}

if(contactId == ''|| contactId == null){
Contact con = new Contact();
con.Id=lcr.getContactId();
con.FirstName = firstName;
con.LastName = lastName;
con.RecordTypeId=conRecordTypeId;
con.Title = title;
con.Email=email;
con.Role__c=role;
upsert con;
}
}else{
//if(!lcr.isSuccess()){
status='Quick Entry Conversion Failed';
}
finalResult.add(status);
}
catch(Exception ex){
status = ex.getMessage();
finalResult.add(status);
system.debug('-----Exception'+ex.getStackTraceString());
return finalResult;
}
return finalResult;
}

}

Test Class:
@isTest(SeeAllData=true)
private class OV_FlwLeadConversionTest {
@isTest static void testLeadConvert(){
Lead ld= new Lead();
ld.LastName = 'abc';
ld.Company = 'xyz';
ld.FirstName = 'fd';
ld.Email = 'ab@fr.com';
ld.Status='Qualified';
insert ld;
String status = 'Lead Converted Successfully';
String conRecordType;
Id conRecordTypeId;
List<List<String>> configParams = new List<List<String>>();
List<String> configParam = new List<String>();
configParam.add('');
configParam.add('');
configParam.add(ld.Id);
configParam.add('xyGroups');
configParam.add('Brokerage');
configParam.add('US');
configParam.add('India');
configParam.add('Aurora');
configParam.add('');
configParam.add('');
configParam.add(ld.FirstName);
configParam.add(ld.LastName);
configParam.add('Master');
configParam.add(ld.Email);
configParam.add('Broker');
configParam.add('368638');
configParam.add('Karnataka');
configParams.add(configParam);

List<String> finalResult = OV_FlwLeadConversion.convertLead(configParams);
system.assert(finalResult.size() > 0);

}

}

Thanks
Hey , this is the logic which I thought to fetch all child and grand child account(Multilevel) from a parent account page.

List<Account> acct= [Select Id , Name , Parentid from Account group by parentid];
Set<Id> Ids = new Set<Id>();
List<String> childAcctIds = [Select Id, (Select Id  from ChildAccounts) from Accounts where id:=apexpages.currentpage().getparameters().get(‘id’)];
Ids.addAll(childAcctIds);
for(Account acc: acct){
if(acc.parentid != null){
List<String> allChildIds = [Select id from Account where parentid IN : Ids];
Ids.addAll(allChildIds);
}
}
List<String> oppListOfAllChild = [Select Name ,(Select Id , Name from Opportunity) from Account where Id IN : Ids];
How to fetch all child account and frnd child account ids from a parent account Soql query?
Apex class:- I am getting only 30%code coverage, Please review what and where i am doing mistake?
public class OV_FlwLeadConversion {

@InvocableMethod(label=' ' description='')
public static List<String> convertLead(List<List<String>> configParams){
List<String> finalResult = new List<String>();
String status = 'Lead Converted Successfully';
try{
String accountId=configParams[0][0];
String contactId=configParams[0][1];
String leadId=configParams[0][2];
String acctName=configParams[0][3];
String accountType=configParams[0][4];
String city=configParams[0][5];
String country=configParams[0][6];
String street=configParams[0][7];
String webSite=configParams[0][8];
String recordTypeId=configParams[0][9];
String firstName=configParams[0][10];
String lastName=configParams[0][11];
String title=configParams[0][12];
String email=configParams[0][13];
String role=configParams[0][15];
String accPhone=configParams[0][16];
String state=configParams[0][17];
String conRecordType;
Id conRecordTypeId;
system.debug('--accountType--:'+accountType);
system.debug('--configParams[0][4]--:'+configParams[0][4]);
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(leadId);
lc.setDoNotCreateOpportunity(true);
if(accountId != ''){
lc.setAccountId(accountId);
}
if(contactId != '' ){
lc.setContactId(contactId);
}
//LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
//lc.setConvertedStatus(convertStatus.MasterLabel);//Qualified
lc.setConvertedStatus('Qualified');
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.debug('--------``````----accountId------'+accountId);
System.debug('--------`````----contactId------'+contactId);
if(lcr.isSuccess()){
system.debug('-------isSuccess----------');
if(accountId == ''&& contactId==''){

recordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get(accountType).getRecordTypeId();
Account acct = new Account();
acct.Id=lcr.getAccountId();
acct.name=acctName;
acct.BillingCountry=country;
acct.Website=webSite;
acct.BillingCity=city;
acct.BillingStreet=street;
acct.Type=accountType;
acct.RecordTypeId=recordTypeId;
acct.Customer_Category__c='Unspecified';
acct.Phone=accPhone;
acct.BillingState=state;

upsert acct;
}
// This needs to be removed and put it in Config
if(accountType == 'Brokerage'){
conRecordType = 'Broker';
}else if(accountType == 'Prologis'){
conRecordType = 'Employee';
}else if(accountType == 'Venture Account'){
conRecordType = 'Venture Contact' ;
}else if(accountType == 'Other'){
conRecordType = 'Non Ventures' ;
}else{
conRecordType = accountType;
}
if(accountType!=null && accountType!=''){
conRecordTypeId = Schema.getGlobalDescribe().get('Contact').getDescribe().getRecordTypeInfosByName().get(conRecordType).getRecordTypeId();
}
if(contactId == ''|| contactId == null){
Contact con = new Contact();
con.Id=lcr.getContactId();
con.FirstName = firstName;
con.LastName = lastName;
con.RecordTypeId=conRecordTypeId;
con.Title = title;
con.Email=email;
con.Role__c=role;
upsert con;
}else{
Contact con = new Contact();
con.Id=lcr.getContactId();
con.FirstName = firstName;
//con.AccountId = '001e0000018SOEMAA4';
con.LastName = lastName;
con.Title = title;
con.Email=email;
upsert con;
}
}
if(!lcr.isSuccess()){
status='Lead Conversion Failed';
}
finalResult.add(status);
}
catch(Exception ex){
status = ex.getMessage();
finalResult.add(status);
system.debug('-----Exception'+ex.getStackTraceString());
return finalResult;
}
return finalResult;
}

}
Test:-
@isTest(SeeAllData=true)
private class OV_FlwLeadConversionTest {
@isTest static void testLeadConvert(){
Lead ld= new Lead();
ld.LastName = 'test1';
ld.Company = 'test2';
ld.FirstName = 'test3';
ld.Email = 'ssn@gmail.com';
ld.Status='Qualified';
insert ld;
String status = 'Lead Converted Successfully';
String conRecordType;
Id conRecordTypeId;
List<List<String>> configParams = new List<List<String>>();
List<String> configParam = new List<String>();
configParam.add('');
configParam.add('');
configParam.add(ld.Id);
configParam.add('test');
configParam.add('Brokerage');
configParam.add('Bangalore');
configParam.add('India');
configParam.add('test');
configParam.add('');
configParam.add('');
configParam.add(ld.FirstName);
configParam.add(ld.LastName);
configParam.add('Master');
configParam.add(ld.Email);
configParam.add('Broker');
configParam.add('1234567890');
configParam.add('Karnataka');
configParams.add(configParam);

List<String> finalResult = OV_FlwLeadConversion.convertLead(configParams);
system.assert(finalResult.size() > 0);

/**   Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(ld.Id);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Qualified');

Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
//    ld = [Select Id , LastName , FirstName , Name , Email , Status from Lead where Id=: ld.Id];
//    System.assertEquals('Qualified', ld.Status); **/
}

}
How to write Test Class for dependent picklist methods?

@AuraEnabled
public static List<String> getDepStates(String objectType, String parentField, String childField,String search){
List<String> optionStates = new List<String>();
PicklistFieldController controller = new PicklistFieldController();
Map<String,List<String>> valueMap = PicklistFieldController.getDependentOptionsImpl(objectType,parentField,childField);
for(String contr : valueMap.keySet()){
// System.debug('CONTROLLING FIELD : ' + contr);
//System.debug('DEPENDENT VALUES ...  : ' + valueMap.get(contr));
if(search==contr){
optionStates=valueMap.get(contr);
}
}
return optionStates;
}
@AuraEnabled
public static List<String> getPickList(String field,String objectName){
List<String> lstPickvals=new List<String>();
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
Sobject Object_name = targetType.newSObject();
Schema.sObjectType sobject_type = Object_name.getSObjectType();
Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
List<Schema.PicklistEntry> pick_list_values = field_map.get(field).getDescribe().getPickListValues();
for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
lstPickvals.add(a.getValue());//add the value  to our final list
}
return lstPickvals;
}

}
I have written one validation that some particular fields can only be edited by system admin or user should be record owner or User should be steve.
Please review It.

AND( OR(ISCHANGED( BusinessStrategy__c ),ISCHANGED(  BusinessStrategyComments__c )), OR( \$Profile.Name  <> 'System Administrator'  &&   \$User.Id  <>  OwnerId  &&   \$User.Id  <> '005U0000001NqquIAC' ))

005U0000001NqquIAC is the user Id of steve because when I am giving \$User.UserName='Steve' its throwing validation error even after using User Id still that user not able to edit.
Hi,
How to pass Flow variables in hyperlink formula field.
This formula field

HYPERLINK("/flow/QuickEntry?firstname=" & FirstName , "Quick Entry")
Hi ,
How to get code coverage for this apex class.

public class OV_Flw_Searchcc360 {
@InvocableMethod(label='Saerch the CC360 ' description='This will get the configuration from Flow and search in cc360')
public static List<String> searchCC360(List<List<String>> config) {
try{
String dispFields=config[0][0];
String[] fetchFields=config[0][1].split(',');
String searchFields=config[0][2];
String objectType=config[0][3];
List<String> filterFields = searchFields.split(',');
Map<String, String> fields = new Map<String, String>();
Map<String, String> sources = new Map<String, String>();
sources.put('1',objectType);

for(String f : filterFields ){
List<String> fiterMap=f.split('=');
fields.put(fiterMap[0], fiterMap[1]);
}
system.debug('-------objectType-----'+objectType);
system.debug('-------fields-----'+fields);
system.debug('-------sources-----'+sources);
List<sObject> allResult= OV_Searchcc360.isDuplicate(objectType, fields, sources, null);
List<Map<String,String>> tblResule = new List<Map<String,String>>();

for(sObject result : allResult){
Map<String,Object> retObject =  (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(result));
Map<String,String> consolidatedMap = new Map<String,String>();
for(String f : fetchFields ){
f=f.trim();
consolidatedMap.put(f,(String)retObject.get(f));
}
system.debug('------result------'+consolidatedMap);
tblResule.add(consolidatedMap);
}

List<String> finalResult = new List<String>();
for(Map<String,String> fResult : tblResule){
finalResult.add(JSON.serialize(fResult));
}

system.debug('------finalResult------'+finalResult);
system.debug('------result------'+allResult);
system.debug('------tblResule------'+tblResule);
List<String> accountNames = new List<String>();
List<List<String>> stringList = new List<List<String>>();
stringList.add(finalResult);
List<String> cc360resultList = new List<String>();
String cc360result=JSON.serialize(finalResult);
cc360resultList.add(cc360result);

system.debug('-----------'+cc360result);

if(finalResult.size()==0){
return null;
}
return cc360resultList;
}catch(Exception ex){
system.debug('------Error-------'+ex.getLineNumber());
system.debug('------Error-------'+ex.getMessage());
}
return null;
}
}
Set<id> resultId = new Set<id>();

I need to send the resultId to another apex controller , so that i can use that in where ID IN condition
Map<Id,decimal> allResultMap = new Map<Id,decimal>();

I need to sort in descending order on the basis of the score field which is of type decimal.
List<sObject> allResult= OV_Searchcc360.isDuplicate(objectType, fields, sources, null);

So allResult is a List of array having multiple records of one object , each record having several fields. I need to use  id from this collection in a Set. so i written this below code to iterate.
Set<String> resultIds = new Set<String>();
for (String sourceId : allResult.keySet())
{
resultIds.add(sourceId .DSE__DS_Account__c);
system.debug('-------resultIds-----'+resultIds);
}

I need help getting error
My scenario , when a Parent account is added to a Child account then the value(sum of all child) of  one field should updated to the Parent Account Field.
Total_Lease_Area_SF_from_Children__c (Number Field) needs to get updated in parent account from the Total_Account_Child_Lease_Area_SF__c(Formula Field) of child Account.
Note:- Total_Account_Child_Lease_Area_SF__c(Formula Field) is the sum of all child till that heirrachy updated by Total_Lease_Area_SF_from_Children__c (Number Field). But When a new account is added to an existing Account parent account field is not geeting updated.

trigger AccLeaseUpdate on Account   (after update, after delete) {

set<id> ParentIds = new set<id>();
if(Trigger.isupdate){
For(Account acc: Trigger.new){
ParentIds.add(acc.ParentId);
}
}
if(Trigger.isDelete){
For(Account acc: Trigger.old){
ParentIds.add(acc.ParentId);
}
}
/*   List<account> accountToUpdate = new List<account>();

decimal sum = 0;
if(Trigger.isupdate || trigger.isdelete){

For(account q : [SELECT Total_Lease_Area_SF_from_Children__c ,ParentId ,(SELECT id,Total_Lease_Area_SF_from_Children__c,Total_Account_Child_Lease_Area_SF__c FROM  ChildAccounts) FROM account WHERE id =: ParentIds]){
if(q.ParentId!= null && q.Total_Lease_Area_SF__c!= null){
sum = 0;
for(Account p : q.ChildAccounts){
//    for(Account ap : trigger.new){
//      Account myParentAcc = aq.get(p.ParentId);

sum = sum +p.Total_Lease_Area_SF_from_Children__c;
q.Total_Lease_Area_SF_from_Children__c= sum  ;
//   myParentAcc.Total_Lease_Area_SF_from_Children__c = sum;
}
}
try{
update accountToUpdate ;
}Catch(Exception e){
System.debug('Exception :'+e.getMessage());
}

}

accountToUpdate.add(q);
}
}*/
Hey , this is the logic which I thought to fetch all child and grand child account(Multilevel) from a parent account page.

List<Account> acct= [Select Id , Name , Parentid from Account group by parentid];
Set<Id> Ids = new Set<Id>();
List<String> childAcctIds = [Select Id, (Select Id  from ChildAccounts) from Accounts where id:=apexpages.currentpage().getparameters().get(‘id’)];
Ids.addAll(childAcctIds);
for(Account acc: acct){
if(acc.parentid != null){
List<String> allChildIds = [Select id from Account where parentid IN : Ids];
Ids.addAll(allChildIds);
}
}
List<String> oppListOfAllChild = [Select Name ,(Select Id , Name from Opportunity) from Account where Id IN : Ids];
How to fetch all child account and frnd child account ids from a parent account Soql query?
How to write Test Class for dependent picklist methods?

@AuraEnabled
public static List<String> getDepStates(String objectType, String parentField, String childField,String search){
List<String> optionStates = new List<String>();
PicklistFieldController controller = new PicklistFieldController();
Map<String,List<String>> valueMap = PicklistFieldController.getDependentOptionsImpl(objectType,parentField,childField);
for(String contr : valueMap.keySet()){
// System.debug('CONTROLLING FIELD : ' + contr);
//System.debug('DEPENDENT VALUES ...  : ' + valueMap.get(contr));
if(search==contr){
optionStates=valueMap.get(contr);
}
}
return optionStates;
}
@AuraEnabled
public static List<String> getPickList(String field,String objectName){
List<String> lstPickvals=new List<String>();
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
Sobject Object_name = targetType.newSObject();
Schema.sObjectType sobject_type = Object_name.getSObjectType();
Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
List<Schema.PicklistEntry> pick_list_values = field_map.get(field).getDescribe().getPickListValues();
for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
lstPickvals.add(a.getValue());//add the value  to our final list
}
return lstPickvals;
}

}
Hi
I have to show error message on clicking contact new button on contact page and I can create without showing error message on new contact button in Account Related List.
Means I need to create contact only from account related list not from contact.

Can we create a tab to navigate to custom meta data type object on click?
Can we make the standard name field of custom meta type object to aunto number field like other custom object?
Rollup summary using flow to count child account record in parent account---Using Flow , no coding.
How can i update a check box in all parent account above the hierarchy from the child account check box?
public class OV_CountryList {
@AuraEnabled
public static List<String> getCountry(){
List<String> options = new List<String>();
Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
List<Schema.PicklistEntry> plist = fieldResult.getPicklistValues();
System.debug('Picklist::'+plist);
for (Schema.PicklistEntry p: pList) {
System.debug(p.getLabel() +'::'+ p.getValue());
options.add(p.getLabel());
}
return options;
}
}

In this we are fetching picklist from global picklist
One is a condition another one is Apex function, how to put them in one rendered:-
1. rendered="{!massEdit}"
2.rendered="{!IF(selectedProductLine.item.RecordTypeId = ICRecTypeId),true,false )}"

This Syntax not working:-
rendered="{!IF(((selectedProductLine.item.RecordTypeId = ICRecTypeId)&&(!massEdit)),true,false )}"
Even I tried with AND OR Operator not working. I need to render a section on picklist value change for the same, so i have to put the two condition in one rendered.
I am getting the above error. My requirement is to change the currency field data, if opportunity already having child quote records. So its not possible through standard . Thus I am working out for custom solution. Earlier its was working on clicking cancel it use to create clonned opportunity but now its not working now on create and on cancel both.

Apex:-

public with sharing class CloneOpportunityExtension {
//to get opp id from url
public String recId {get;set;}
// for new currency and name
public Opportunity cloneOpp {get;set;}

public CloneOpportunityExtension(ApexPages.StandardController stdCon) {
cloneOpp = new Opportunity();
recId = null;
recId = ApexPages.currentPage().getParameters().get('id');
System.debug('recId'+recId);
if(recId!=null) {
// setting the currency on page load
cloneOpp.CurrencyIsoCode = ((opportunity)stdCon.getRecord()).CurrencyIsoCode;
// setting Name
cloneOpp.Name = ((opportunity)stdCon.getRecord()).Name;

//setting Account Name
// cloneOpp.Account= ((opportunity)stdCon.getRecord()).Account;
} else {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ' '+Label.select_a_vaild_Opportunity));
}
}

/**
* to save the Clone Opportunity with New Currency
*
*/
public PageReference saveNewOpp(){
PageReference pRef = null;
if(recId!=null) {
if(cloneOpp!=null) {
try{
// calling clone class
String returnId = null;
returnId = Cls_CloneOptyRelated.CloneOpportunity(recId, cloneOpp.CurrencyIsoCode, cloneOpp.Name);
if(returnId!=null) {
pRef = new PageReference('/'+returnId);
pRef.setRedirect(true);
}
else {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ' '+Label.Issue_in_Cloning));
}
}
catch(Exception e) {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ' ' + Label.Issue_in_Cloning + ' ' + e.getMessage()));
}
}
}
return pRef;
}
}

Visualforce Page:-

<apex:page standardController="Opportunity" extensions="CloneOpportunityExtension" tabStyle="Opportunity" title="{!\$ObjectType.Opportunity.Label} {!\$Label.Clone}">
<apex:sectionHeader subtitle="{!Opportunity.Name}" title="{!Opportunity.Name} {!\$Label.Clone}" rendered="{!recId != null}"/>
<apex:form >
<apex:pageMessages >
</apex:pageMessages>
<apex:pageBlock title="{!\$ObjectType.Opportunity.Label} {!\$Label.Clone}">
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{!saveNewOpp}" value="{!\$Label.Clone}" rendered="{!recId != null}"/>
<apex:commandButton action="{!cancel}" value="{!\$Label.Cancel}" rendered="{!recId != null}"/>
<apex:outputPanel rendered="{!recId == null}"> <input type="button" name="{!\$Label.Back}" value="{!\$Label.Back}" class="btn" onclick="window.top.location='/006/o';"/>
</apex:outputPanel>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1">
<apex:inputField value="{!cloneOpp.Name}" label="{!\$ObjectType.Opportunity.fields.Name.Label}"/>
<apex:inputField value="{!cloneOpp.CurrencyIsoCode}" label="{!\$ObjectType.Opportunity.fields.CurrencyIsoCode.Label}"/>
<!--- <apex:inputField value="{!cloneOpp.Account.Name}" label="{!\$ObjectType.Opportunity.fields.Account.Name.Label}"/> ----> </apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Errorr Message:-

Errors

Parent Opportunity: Value does not exist or does not match filter criteria.
Issue in cloning Opportunity, Please Contact System Administrator Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [CBG_Parent_Opportunity__c]
Below code is working fine like dynamically adjust size of column :-
<apex:includeScript value="//cdn.jsdelivr.net/jquery/1.7/jquery.min.js"/>
<apex:includeScript value="//cdn.jsdelivr.net/jquery.colresizable/1.3/colResizable.min.js"/>

<apex:form >
<apex:pageBlock title="Accounts" mode="edit">
<apex:pageBlockTable id="tbl" value="{!accounts}" var="Con"> <apex:column value="{!Con.Name}" >
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column value="{!Con.Industry}"/>
<apex:column value="{!Con.Type}"/>
<apex:column value="{!Con.Phone}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
<script type="text/javascript">
var j= \$("[id\$=tbl]").colResizable({ liveDrag: true, draggingClass: "dragging" });
</script>
</apex:page>

But how to apply same logic here . You can see the below code is different and complex unlike the above one . Please help:--

<apex:pageBlock id="PLPageBlock" title="{!\$Label.Main_Title}">
<apex:pageMessages id="errorMessages"></apex:pageMessages>
<div id="plitablediv" style="flex-direction: column; overflow-x:scroll; max-height: 300px;">
<apex:pageBlockTable id="p" value="{!productLines}" var="pl" onRowClick="fixInlineEditBug(); productLineSelected(this);">
<apex:column style="width:1%;" >
<apex:facet name="header">
</apex:facet>
<span style="display:none;" id="plid">{!pl.ident}</span> </apex:column> <apex:column styleClass="{!IF((LEN(pl.ident) < 10), 'highlightedRow', '')}">
<apex:commandLink rendered="{!pl.item.Id != null}" value="Detail" onclick="window.open('/{!pl.item.Id}'); return false;" /> <br /> <apex:commandLink value="{!\$Label.Delete_Item}" onclick="if(confirm('{!\$Label.Delete_Confirmation}')){delProductLine('{!pl.ident}');} return false;" />
<apex:facet name="header">{!\$Label.Action}</apex:facet>
</apex:column>
<apex:column id="d" styleClass="{!IF((LEN(pl.ident) < 10), 'highlightedRow', '')}"> <div id="draggable1" class="ui-widget-content"> <p>Drag me around 1</p> </div>
<apex:facet name="header">Satya </apex:facet> <span style="display:none;" id="plid">{!pl.ident}</span>
</apex:column>
<apex:column styleClass="{!IF((LEN(pl.ident) < 10), 'highlightedRow', '')}">
<apex:outputField value="{!pl.item.CBG_ItemLine__c}" rendered="{!!massEdit}"/>
<apex:inputField value="{!pl.item.CBG_ItemLine__c}" rendered="{!massEdit}" onkeypress="return fireSave(event);"/>
<apex:facet name="header">{!\$ObjectType.ProductLineItem__c.fields.CBG_ItemLine__c.Label}</apex:facet>
</apex:column>
<apex:column styleClass="{!IF((LEN(pl.ident) < 10), 'highlightedRow', '')}">
<apex:outputField value="{!pl.item.RecordTypeId}" >
<apex:inlineEditSupport disabled="true"/>
</apex:outputField> <apex:facet name="header">{!\$Label.Record_Type}</apex:facet>
</apex:column>
public with sharing class expensesLineItem{
public final Expense_Line_Item__c el;

public expensesLineItem(ApexPages.StandardController stdController){
this.el = (Expense_Line_Item__c)stdController.getRecord();
}
public PageReference Dismiss(){
el.Display_Alert__c=false;
update el;
PageReference page = ApexPages.currentPage();
page.setRedirect(true);
return page;
}
}

Test class:

@isTest
public class expensesLineItem_Test{
@testSetup
static void setupTestData()
{
Expense__c exp = new Expense__c();
exp.Period_From__c = system.today();
exp.Period_To__c =system.today();
insert exp;
System.assertNotEquals(null, exp.Id);

Expense_Line_Item__c expLine = new Expense_Line_Item__c();
expLine.Name = exp.Id;
expLine.Expense_Head__c='Food' ;
expLine.Cost_Head__c= 'Campaign' ;
expLine.Amount__c= 10000;
System.assertNotEquals(null, expLine.Id);
insert expLine;
}

@isTest
static void testCall()
{
Expense_Line_Item__c expLine  =  [SELECT Id,Name,Amount__c,Bill_Available__c,Cost_Head__c,Expense_Head__c,Expense__c from Expense_Line_Item__c][0];
// System.assertEquals(true,expense_line_item_Obj.size()>0);
// List<Expense__c> expense_Obj  =  [SELECT Id from Expense__c];
//System.assertEquals(true,expense_Obj.size()>0);
ApexPages.StandardController stdCon = new ApexPages.StandardController(expLine);
expensesLineItem obj01 = new  expensesLineItem(stdCon);

//expensesLineItem obj01 = new expensesLineItem(new ApexPages.StandardController(expense_line_item_Obj[0]));
obj01.Dismiss();
}
}
Use Case whenever we will select a particular travel request(through lookup) from expense then data
from that travel request (Name + account, related to that travel request) concatenately should
populate Claim purpose field in expense.

Datapopulate:-

public with sharing class DataPopulate {
public Travel_Request__c trq {
get;
set;
}

private ApexPages.StandardController stdCtrl;

public DataPopulate(ApexPages.StandardController std) {
stdCtrl = std;
}

public void doInsert() {
Expense__c exp = (Expense__c) stdCtrl.getRecord();
if (exp.Travel_Request__c == null) {
return;
} else {
trq = [select Name , Proposed_Client_to_Visit__r.Name, Status__c from Travel_Request__c where Id =
: exp.Travel_Request__c LIMIT 1];
System.debug('The record fetched '+trq);

//exp.Branch__c = trq.Branch__c;
//exp.Period_To__c = trq.Travel_Start_Date__c;
// exp.Period_From__c = trq.Travel_End_Date__c;
//exp.Department__c=trq.Department__c;

exp.Claim_Purpose__c= trq.Name +''+ ' -- '+''+ trq.Proposed_Client_to_Visit__r.Name ;
upsert exp;
System.debug('The record insert '+exp);
}
}
}

test class:

//Test class for DataPopulate

@isTest
public class DataPopulateTest
{
//setup test data for Class
@testSetup  static void testSetDate()
{
Travel_Request__c trq = new Travel_Request__c();
trq.Name='TestTravel' ;
trq.Proposed_Client_to_Visit__c='T-System';
insert trq;

Expense__c expObj = new Expense__c();
expObj.Travel_Request__c='TestTravel';
// expObj.Period_To__c= system.today();
//expObj.Period_From__c= system.today();
insert expObj;
}
@isTest static void testPopulate()
{
Travel_Request__c trq = [SELECT id from Travel_Request__c where Name = 'TestTravel' ][0];

Test.setCurrentPage(page.Expense);

Apexpages.currentPage().getParameters().put('Id',trq.Id);

ApexPages.StandardController stdCon = new ApexPages.StandardController(trq);
DataPopulate dClassObj = new  DataPopulate(stdCon);

dClassObj.doInsert();
// List<Expense__c> expObj=[SELECT Claim_Purpose__c from Expense__c WHERE
Travel_Request__c=:trq.id Limit 1];
// Boolean result = expObj.equals('TestTravelT-System');
// System.assertEquals(result,false);
}

}
public class SaveAndNew
{
ApexPages.StandardController con;
public String queryString {get;set;}
public  SaveAndNew(ApexPages.StandardController controller)
{
con = controller;
PageReference thisPage = ApexPages.currentPage();
List<String> url = thisPage.getUrl().split('\\?');
queryString = url[1];
System.debug('----->>'+queryString);

}
public PageReference saveNew()
{
try
{
con.save();
Schema.DescribeSObjectResult describeResult = con.getRecord().getSObjectType().getDescribe();
PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e?'+ queryString);
pr.setRedirect(true);
return pr;
}catch(System.DMLException e) {
return null;
}
}
}