-
ChatterFeed
-
180Best Answers
-
0Likes Received
-
0Likes Given
-
3Questions
-
900Replies
Generate WDSL button is disabled in my Apex class
I have the apex class exposed as webservice, but I am not able to generate the WSDL for my Apex class.
Please help me out.
Please help me out.
- Neethu u
- February 07, 2019
- Like
- 0
- Continue reading or reply
how to write a test code
trigger RollUpOppAmt on Opportunity (after insert) {
Set<Id> setOpportunityIds=new Set<Id>();
for(Opportunity o:Trigger.new)
setOpportunityIds.add(o.id);
List<Account> ListOfAmt = [select id, Amount__c from Account];
List<Account> lstAmtToUpdate=new List<Account>();
for(AggregateResult result:[SELECT AccountId, SUM(Amount) FROM Opportunity
WHERE Id IN :setOpportunityIds GROUP BY AccountId]) {
for(Account acc : ListOfAmt) {
if(result.get('AccountId') == acc.Id) {
if(acc.Amount__c == null) {
acc.Amount__c = 0;
}
acc.Amount__c = acc.Amount__c + Decimal.ValueOf(String.ValueOf(result.get('expr0')));
lstAmtToUpdate.add(acc);
}
}
}
if(lstAmtToUpdate.size()>0) {
UPDATE lstAmtToUpdate;
}
}
Set<Id> setOpportunityIds=new Set<Id>();
for(Opportunity o:Trigger.new)
setOpportunityIds.add(o.id);
List<Account> ListOfAmt = [select id, Amount__c from Account];
List<Account> lstAmtToUpdate=new List<Account>();
for(AggregateResult result:[SELECT AccountId, SUM(Amount) FROM Opportunity
WHERE Id IN :setOpportunityIds GROUP BY AccountId]) {
for(Account acc : ListOfAmt) {
if(result.get('AccountId') == acc.Id) {
if(acc.Amount__c == null) {
acc.Amount__c = 0;
}
acc.Amount__c = acc.Amount__c + Decimal.ValueOf(String.ValueOf(result.get('expr0')));
lstAmtToUpdate.add(acc);
}
}
}
if(lstAmtToUpdate.size()>0) {
UPDATE lstAmtToUpdate;
}
}
- Chiyan
- January 31, 2019
- Like
- 0
- Continue reading or reply
list has more than 1 row for assignment
Hi all,
May I have some assistance with the below code , this works perfectly if one record is being created but when i create multiple records at the same time I get an error that the List has more than 1 row for assignment to SObject.
Can someone take a look at what I may be doing wrong. This is the line where the error is originating.
newSOWrappers.Add(new SOWrapper(shipmentOrder));
May I have some assistance with the below code , this works perfectly if one record is being created but when i create multiple records at the same time I get an error that the List has more than 1 row for assignment to SObject.
Can someone take a look at what I may be doing wrong. This is the line where the error is originating.
newSOWrappers.Add(new SOWrapper(shipmentOrder));
public class SOWrapper { public SOWrapper(Shipment_Order__c so, boolean recalculateCosts) { this.SO = so; this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c]; this.Client = so.Account__r; if (recalculateCosts ) recalculateCostings(); else buildCostings(); } public SOWrapper(Shipment_Order__c so) { this.SO = so; this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c]; this.Client = so.Account__r; if (so.CPA_v2_0__c != null) buildCostings(); } public Shipment_Order__c SO { set; get; } public CPA_v2_0__c CAP { set; get; } public Account Client { set; get; } private List<CPA_Costing__c> relatedCostings; private List<CPA_Costing__c> relatedCostingsIOR; private List<CPA_Costing__c> relatedCostingsEOR; private List<CPA_Costing__c> addedCostings; private List<CPA_Costing__c> updatedCostings; private Id recordTypeId = Schema.SObjectType.CPA_Costing__c.getRecordTypeInfosByName() .get('Display').getRecordTypeId(); public void buildCostings() { relatedCostingsIOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'IOR' ]; relatedCostingsEOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'EOR']; If(SO.Service_Type__c == 'IOR') { List<CPA_Costing__c> SOCPAcostingsIOR = relatedCostingsIOR.deepClone(); for(CPA_Costing__c cost : SOCPAcostingsIOR) { cost.Shipment_Order_Old__c = SO.ID; cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c; cost.recordTypeID = recordTypeId; cost.VAT_Rate__c = CAP.VAT_Rate__c; if (SO.Shipment_Value_USD__c != null) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, cost, false); } } addedCostings = SOCPAcostingsIOR; } Else If(SO.Service_Type__c == 'EOR') { List<CPA_Costing__c> SOCPAcostingsEOR = relatedCostingsEOR.deepClone(); for(CPA_Costing__c cost : SOCPAcostingsEOR) { cost.Shipment_Order_Old__c = SO.ID; cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c; cost.recordTypeID = recordTypeId; cost.VAT_Rate__c = CAP.VAT_Rate__c; if (SO.Shipment_Value_USD__c != null && (SO.FC_Total__c == null || SO.FC_Total__c == 0)) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, cost, false); } } addedCostings = SOCPAcostingsEOR; } } public void recalculateCostings() { relatedCostings = [SELECT Name, Shipment_Order_Old__c, IOR_EOR__c,Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE Shipment_Order_Old__c =: SO.ID]; System.debug('relatedCostings --- '+relatedCostings.size()); List<CPA_Costing__c> delList = new List<CPA_Costing__c>(); for(CPA_Costing__c var: relatedCostings ) { if(var.Cost_Type__c == 'Variable'){ CPA_Costing__c del = new CPA_Costing__c(); del.id =var.id; delList.add(del); } } updatedCostings = new List<CPA_Costing__c>(); System.debug('updatedCostings --- '+updatedCostings.size()); List<CPA_Costing__c> relatedTemplateCPAcostings = [SELECT Name, IOR_EOR__c,Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, CPA_v2_0__r.VAT_Rate__c, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id ]; List<CPA_Costing__c> updateCosting = new List<CPA_Costing__c >(); Set<Id> ids = new Set<id>(); for (CPA_Costing__c templateCost : relatedTemplateCPAcostings) { SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false); System.debug('The cost id; ----------# '+templateCost.Id+' Amount:- '+templateCost.Amount__c); for(CPA_Costing__c cost : relatedCostings){ if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name != cost.Name && templateCost.Cost_Type__c == cost.Cost_Type__c && templateCost.Applied_to__c == cost.Applied_to__c && templateCost.IOR_EOR__c == cost.IOR_EOR__c){ System.debug(' Do update: '+cost.Id+' the amount '+templateCost.Amount__c+' --- name '+ templateCost.Name); if(!ids.contains(cost.id) && templateCost.Amount__c > -1){ cost.Id = cost.Id; cost.Name = templateCost.Name; cost.Amount__c = templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c; cost.Ceiling__c = templateCost.Ceiling__c; cost.Conditional_value__c = templateCost.Conditional_value__c; cost.Condition__c = templateCost.Condition__c; cost.Cost_Type__c = templateCost.Cost_Type__c; cost.Floor__c = templateCost.Floor__c; cost.Max__c = templateCost.Max__c; cost.Min__c = templateCost.Min__c; cost.Rate__c = templateCost.Rate__c; cost.Variable_threshold__c = templateCost.Variable_threshold__c; cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c; cost.Cost_Category__c = templateCost.Cost_Category__c ; cost.IOR_EOR__c = templateCost.IOR_EOR__c; updateCosting.add(cost); ids.add(cost.id); } } } } if(!updateCosting.IsEmpty()){ update updateCosting; } List<CPA_Costing__c> updateCostList = new List<CPA_Costing__c>(); for(CPA_Costing__c cost : relatedCostings) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, cost, false); System.debug('The cost id; --------'+cost.Id+' Amount:- '+cost.Amount__c); IF(cost.Amount__c == -1){ } System.debug(' --- cost '+cost.Amount__c); if (cost.Amount__c >= 0) { System.debug(' --- amount '+relatedTemplateCPAcostings); for (CPA_Costing__c templateCost : relatedTemplateCPAcostings) { System.debug(' --- templateCost '); if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name == cost.Name) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false); System.debug(' --- templateCost2 '+templateCost.Amount__c); if (templateCost.Amount__c > 0) { System.debug(' ---inside '+templateCost.Amount__c); cost.Amount__c = templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c; cost.Ceiling__c = templateCost.Ceiling__c; cost.Conditional_value__c = templateCost.Conditional_value__c; cost.Condition__c = templateCost.Condition__c; cost.Cost_Type__c = templateCost.Cost_Type__c; cost.Floor__c = templateCost.Floor__c; cost.Max__c = templateCost.Max__c; cost.Min__c = templateCost.Min__c; cost.Rate__c = templateCost.Rate__c; cost.Variable_threshold__c = templateCost.Variable_threshold__c; cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c; system.debug('THE COST ' + cost.ID+' '+cost.Name); } } } } updatedCostings.Add(cost); } if(!updateCostList.IsEmpty()){ insert updateCostList; } } public List<CPA_Costing__c> getApplicableCostings() { List<CPA_Costing__c> applicableCostings = new List<CPA_Costing__c>(); if (addedCostings != null) for (CPA_Costing__c cost : addedCostings) if (cost.Amount__c > -1 && cost.Shipment_Order_Old__c != null) applicableCostings.Add(cost); if (updatedCostings != null) for (CPA_Costing__c cost : updatedCostings) if (cost.Amount__c > -1) applicableCostings.Add(cost); return applicableCostings; } }
public class CalculateCosts { @InvocableMethod public static void createSOCosts(List<Id> SOIds) { List<SOWrapper> newSOWrappers = new List<SOWrapper>(); List<ID> SOsToUpdate = new List<Id>(); List<Shipment_Order__c> shipmentOrder = [Select Id, Name, Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c, FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c, TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c, Account__c, Service_Type__c, Total_Taxes__c FROM Shipment_Order__c where id IN :SOIds]; List<Shipment_Order__c> SOs = new List<Shipment_Order__c>(); List<CPA_Costing__c> costingsToAddUpdate = new List<CPA_Costing__c>(); List<Shipment_Order__c> updatedSOs = [SELECt Id, Name, Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c, FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c, TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c FROM Shipment_Order__c WHERE ID in: SOsToUpdate]; newSOWrappers.Add(new SOWrapper(shipmentOrder)); if (newSOWrappers.size() > 0 && shipmentOrder.size() > 0 ) { for (SOWrapper wrp : newSOWrappers) { Shipment_Order__c SO; for (Shipment_Order__c SOToUpdate : updatedSOs) if (SOToUpdate.ID == wrp.SO.ID) { SO = SOToUpdate; break; } costingsToAddUpdate.AddAll(wrp.getApplicableCostings()); } } Upsert costingsToAddUpdate; update SOs; } }
- Masechaba Maseli 8
- December 19, 2018
- Like
- 0
- Continue reading or reply
My test class is not giving any error & running successfully but while checking code coverage it is giving none
I mentioned my class with respective test class. please let me know where I am doing wrong.
My class is calling in a trigger which fires when my support Request(object) Record is approved by the approver through the standard approval process. when the record is approved the trigger automatically create an Event record. below is the class with test class .
Public class AutoCreateEvent
{
Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
{
List<Event> EventRec = new List<Event>();
RecordType SuppReqRecordType = [SELECT Id
FROM RecordType
WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
LIMIT 1];
for(DealSupportRequest__c ds:dsreq)
{
if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c != oldDsreqMap.get(ds.Id).Is_approved__c) )
{
Event e = new Event();
e.WhatId = ds.Account__c;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = ds.Ownerid;
e.Subject_Custom__c =ds.Purpose__c;
e.Description = ds.OtherPurpose__c;
e.StartDateTime =ds.StartDateTime__c;
e.EndDateTime = ds.EndDateTime__c;
e.LocationCallInInfo__c = ds.CampusLocation__c;
e.Support_Request__c = ds.Id;
EventRec.add(e);
}
}
If(EventRec.size()>0)
Insert EventRec;
}
}
Test class:
@IsTest
public class AutoCreateEvent_Test {
static testmethod void CreateEvent(){
Test.startTest();
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000@amamama.com',
Username = 'puser000@amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
EmployeeNumber='1'
);
insert u;
List<Event> EventRec = new List<Event>();
Account a = new Account(Name='1st Community CU',Membership_Defined__c='Member',Type='Client', ownerid=u.id );
Insert a;
DealSupportRequest__c dsr = new DealSupportRequest__c(Account__c=a.Id,StartDateTime__c=system.now(),EndDateTime__c=system.now().addDays(1),ownerid=a.Ownerid);
Insert dsr;
Event e = new Event();
e.WhatId=a.Id;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = dsr.Ownerid;
// e.Support_Request__c=dsr.Id;
e.StartDateTime =dsr.StartDateTime__c;
e.EndDateTime = dsr.EndDateTime__c;
EventRec.add(e);
insert EventRec;
Test.stopTest() ;
}
}
My class is calling in a trigger which fires when my support Request(object) Record is approved by the approver through the standard approval process. when the record is approved the trigger automatically create an Event record. below is the class with test class .
Public class AutoCreateEvent
{
Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
{
List<Event> EventRec = new List<Event>();
RecordType SuppReqRecordType = [SELECT Id
FROM RecordType
WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
LIMIT 1];
for(DealSupportRequest__c ds:dsreq)
{
if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c != oldDsreqMap.get(ds.Id).Is_approved__c) )
{
Event e = new Event();
e.WhatId = ds.Account__c;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = ds.Ownerid;
e.Subject_Custom__c =ds.Purpose__c;
e.Description = ds.OtherPurpose__c;
e.StartDateTime =ds.StartDateTime__c;
e.EndDateTime = ds.EndDateTime__c;
e.LocationCallInInfo__c = ds.CampusLocation__c;
e.Support_Request__c = ds.Id;
EventRec.add(e);
}
}
If(EventRec.size()>0)
Insert EventRec;
}
}
Test class:
@IsTest
public class AutoCreateEvent_Test {
static testmethod void CreateEvent(){
Test.startTest();
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000@amamama.com',
Username = 'puser000@amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
EmployeeNumber='1'
);
insert u;
List<Event> EventRec = new List<Event>();
Account a = new Account(Name='1st Community CU',Membership_Defined__c='Member',Type='Client', ownerid=u.id );
Insert a;
DealSupportRequest__c dsr = new DealSupportRequest__c(Account__c=a.Id,StartDateTime__c=system.now(),EndDateTime__c=system.now().addDays(1),ownerid=a.Ownerid);
Insert dsr;
Event e = new Event();
e.WhatId=a.Id;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = dsr.Ownerid;
// e.Support_Request__c=dsr.Id;
e.StartDateTime =dsr.StartDateTime__c;
e.EndDateTime = dsr.EndDateTime__c;
EventRec.add(e);
insert EventRec;
Test.stopTest() ;
}
}
- subodh chaturvedi 17
- November 29, 2018
- Like
- 0
- Continue reading or reply
Invalid loop variable type expected Approver__c was list
I'm struggling with finishing off this piece of code, anyone have a suggestion? Its returning an error at line 22: invalid loop variable type expected Approver__c was List
public class Invocable_eG_ProductSBUSearch { @InvocableMethod(label='Find Valid Approvers' description ='Searchs the database for matches in SEA Approvers') //productSBUSearch comes from the flow and contains the eGreensheet ID and Tier selected concatenated public static List<List<Approver__c>> approverIds (List<String> productSBUSearch){ // One sObject per search eGreensheet record (bulkify) List<List<SObject>> wrapsApprovers = new List<List<SObject>>(); for (String searchTerm : productSBUSearch) { wrapsApprovers.add(new List<SObject>()); } //Pull eGreensheet Product SBU into a list List<Workflow_Details__c> eGs = [SELECT Product_SBU_List__c FROM Workflow_Details__c where Id in :productSBUSearch]; //Pull all possible approvers List<Approver__c> possibleApprovers = [SELECT Product_SBU__c, Tier__c FROM Approver__c WHERE Active__c = true and Approver_type__c = 'Product Approver' and Product_SBU__c != null and Tier__c in :productSBUSearch]; system.debug('wwwwwwwwwwwww' + possibleApprovers); //Add all approvers who qualify to the final list //WFList[0].Product_SBU__c.contains(Alist[j].Product_SBU__c) for (List<SObject> listOfApprovers : possibleApprovers){ for (SObject returnList : listOfApprovers) { //Query for matches if(eGs[0].Product_SBU_List__c.contains(possibleApprovers[0].Product_SBU__c)){ //Return fields to the flow wrapsApprovers[0].add(returnList); } } } return wrapsApprovers; } }
- Kelsey Shannon
- October 24, 2018
- Like
- 0
- Continue reading or reply
Test class error data type. please help me!!
Hello!
I developed an apex class for read cases and send email if meet the criteria. It has 100% code coverage, but when I send the test class to production I have the following error:
"Invalid type: NotifCasosSchedule"
This is the test class:
@isTest
public class NotifCasosScheduleTest {
public static testmethod void test1(){
Test.startTest();
ID Owner = '00540000004ADl6';
Case ccs = new Case();
ccs.Area__c = 'Sistemas';
ccs.Tipo_de_Caso__c = 'Soporte Salesforce';
ccs.OwnerId = Owner;
ccs.Subject = 'test';
ccs.Description = 'Testeo';
ccs.CreatedDate__c = System.Date.today()-3;
insert ccs;
String CRON_EXP = '0 0 0 3 9 ? 2022';
String jobId = System.schedule('NotifCasosScheduleTest', CRON_EXP, new NotifCasosSchedule());
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
System.assertEquals(0, ct.TimesTriggered);
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
Test.stopTest();
}
}
any help serves
Thanks!!
Best Regards!!
I developed an apex class for read cases and send email if meet the criteria. It has 100% code coverage, but when I send the test class to production I have the following error:
"Invalid type: NotifCasosSchedule"
This is the test class:
@isTest
public class NotifCasosScheduleTest {
public static testmethod void test1(){
Test.startTest();
ID Owner = '00540000004ADl6';
Case ccs = new Case();
ccs.Area__c = 'Sistemas';
ccs.Tipo_de_Caso__c = 'Soporte Salesforce';
ccs.OwnerId = Owner;
ccs.Subject = 'test';
ccs.Description = 'Testeo';
ccs.CreatedDate__c = System.Date.today()-3;
insert ccs;
String CRON_EXP = '0 0 0 3 9 ? 2022';
String jobId = System.schedule('NotifCasosScheduleTest', CRON_EXP, new NotifCasosSchedule());
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
System.assertEquals(0, ct.TimesTriggered);
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
Test.stopTest();
}
}
any help serves
Thanks!!
Best Regards!!
- Lujan Galvano
- October 23, 2018
- Like
- 0
- Continue reading or reply
Compile Error: Unexpected token 'public'. at line 91 column 5
Below is the code:
public without sharing class AryaPortalUserCreationTriggerHandler{
private static Map<Id, String> emailMap = null;
private static List<Contact> conListToInsert = null;
public static void beforeUpdate(Self_Register_User_Request__c[] srs) {
String DUMMY_ACCOUNT = 'Dummy Account' ;
List<Contact> conListToInsert = new List<Contact>();
Map<Id, String> emailMap = new Map<Id, String>();
Map<Id, Self_Register_User_Request__c> dummyMap = new Map<Id, Self_Register_User_Request__c>();
for(Self_Register_User_Request__c sr :(List<Self_Register_User_Request__c>) trigger.new) {
System.debug('here is FN: '+sr.FirstName__c);
System.debug('here is FN: '+sr.LastName__c);
System.debug('here is FN: '+sr.Email__c);
System.debug('here is FN: '+sr.AccountName__c);
if(sr.FirstName__c == null || sr.LastName__c == null || sr.Email__c == null)
continue;
if(sr.Is_it_Approved__c = TRUE){
if(sr.AccountName__c != null ){
Contact conRecord = new Contact(
FirstName = sr.FirstName__c,
LastName = sr.LastName__c,
Email = sr.Email__c,
AccountId = sr.AccountName__c
);
System.debug('adding contact from line 36');
conListToInsert.add(conRecord);
}
if(sr.Email__c != null){
emailMap.put(sr.Id, sr.Email__c);
}
dummyMap.put(sr.Id, sr);
}
}
//create Portal User
if(conListToInsert != null && conListToInsert.size() > 0) {
insert conListToInsert;
List<Profile> pList = [select id from Profile where Name = 'Partner Community Login User - Custom'];
if(!pList.isEmpty()){
Profile p = pList[0];
List<User> userListToInsert = new List<User>();
for(Contact con :conListToInsert) {
String alias1 = '';
if(con.FirstName.length() >= 0)
alias1 = con.FirstName.substring(0,1);
String alias2 = '';
if(con.LastName.length() >= 4){
alias2 = con.LastName.substring(0, 4);
}else{
alias2 = con.LastName;
}
String alias = alias1 + alias2;
User u = new User(
Alias = alias,
Email = con.Email,
EmailEncodingKey = 'UTF-8',
FirstName = con.FirstName,
LastName = con.LastName,
LanguageLocaleKey = 'en_US',
LocalesIdKey = 'en_US',
ProfileId = p.Id,
ContactId = con.id,
TimeZonesIdKey = 'America/Los_Angeles',
UserName = con.Email
);
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.EmailHeader.triggerUserEmail = true;
u.setOptions(dmo);
userListToInsert.add(u);
}
Database.SaveResult[] results = database.insert(userListToInsert, false);
for(Database.SaveResult sr :results){
if(!sr.isSuccess()){
Database.Error err = sr.getErrors()[0];
throw new CustomException(err.getMessage());
/* break;*/
}
}
}
}
//define your custom exception
public class CustomException extends Exception{}
}
}
public without sharing class AryaPortalUserCreationTriggerHandler{
private static Map<Id, String> emailMap = null;
private static List<Contact> conListToInsert = null;
public static void beforeUpdate(Self_Register_User_Request__c[] srs) {
String DUMMY_ACCOUNT = 'Dummy Account' ;
List<Contact> conListToInsert = new List<Contact>();
Map<Id, String> emailMap = new Map<Id, String>();
Map<Id, Self_Register_User_Request__c> dummyMap = new Map<Id, Self_Register_User_Request__c>();
for(Self_Register_User_Request__c sr :(List<Self_Register_User_Request__c>) trigger.new) {
System.debug('here is FN: '+sr.FirstName__c);
System.debug('here is FN: '+sr.LastName__c);
System.debug('here is FN: '+sr.Email__c);
System.debug('here is FN: '+sr.AccountName__c);
if(sr.FirstName__c == null || sr.LastName__c == null || sr.Email__c == null)
continue;
if(sr.Is_it_Approved__c = TRUE){
if(sr.AccountName__c != null ){
Contact conRecord = new Contact(
FirstName = sr.FirstName__c,
LastName = sr.LastName__c,
Email = sr.Email__c,
AccountId = sr.AccountName__c
);
System.debug('adding contact from line 36');
conListToInsert.add(conRecord);
}
if(sr.Email__c != null){
emailMap.put(sr.Id, sr.Email__c);
}
dummyMap.put(sr.Id, sr);
}
}
//create Portal User
if(conListToInsert != null && conListToInsert.size() > 0) {
insert conListToInsert;
List<Profile> pList = [select id from Profile where Name = 'Partner Community Login User - Custom'];
if(!pList.isEmpty()){
Profile p = pList[0];
List<User> userListToInsert = new List<User>();
for(Contact con :conListToInsert) {
String alias1 = '';
if(con.FirstName.length() >= 0)
alias1 = con.FirstName.substring(0,1);
String alias2 = '';
if(con.LastName.length() >= 4){
alias2 = con.LastName.substring(0, 4);
}else{
alias2 = con.LastName;
}
String alias = alias1 + alias2;
User u = new User(
Alias = alias,
Email = con.Email,
EmailEncodingKey = 'UTF-8',
FirstName = con.FirstName,
LastName = con.LastName,
LanguageLocaleKey = 'en_US',
LocalesIdKey = 'en_US',
ProfileId = p.Id,
ContactId = con.id,
TimeZonesIdKey = 'America/Los_Angeles',
UserName = con.Email
);
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.EmailHeader.triggerUserEmail = true;
u.setOptions(dmo);
userListToInsert.add(u);
}
Database.SaveResult[] results = database.insert(userListToInsert, false);
for(Database.SaveResult sr :results){
if(!sr.isSuccess()){
Database.Error err = sr.getErrors()[0];
throw new CustomException(err.getMessage());
/* break;*/
}
}
}
}
//define your custom exception
public class CustomException extends Exception{}
}
}
- Swaroopa Akula 1
- October 22, 2018
- Like
- 0
- Continue reading or reply
Trigger to count Tasks with unique subject line.
Hello Friends.
I am hoping someone can help me with this method. I have been working on it all afternoon with no luck. My requirement is to get to a count of tasks that are related to contacts and place a value on a custom object. The custom object relationship_owner__C is the parent in a look up a relationship with the Contact object.
When a relationship_owner__C is updated then look for all contacts owned by the relationship owner with tasks that begin with the phrase "Pardot List" Evaluate the text that comes after Pardot list to determine how many unique subject lines there are.
If the relationship owner Test Owner has 5 contacts and Each Contact has Two Tasks with the Subject Line Pardot List 1 and Pardot List 2. The relationship owner would be updated with a total unique value of 2. When I test in the UI I get a value of 1 no matter how many tasks I create. And my test class for a single email fails its assertions and says 0 emails.
Here is my method. It is called from a trigger handler on before update.
I am hoping someone can help me with this method. I have been working on it all afternoon with no luck. My requirement is to get to a count of tasks that are related to contacts and place a value on a custom object. The custom object relationship_owner__C is the parent in a look up a relationship with the Contact object.
When a relationship_owner__C is updated then look for all contacts owned by the relationship owner with tasks that begin with the phrase "Pardot List" Evaluate the text that comes after Pardot list to determine how many unique subject lines there are.
If the relationship owner Test Owner has 5 contacts and Each Contact has Two Tasks with the Subject Line Pardot List 1 and Pardot List 2. The relationship owner would be updated with a total unique value of 2. When I test in the UI I get a value of 1 no matter how many tasks I create. And my test class for a single email fails its assertions and says 0 emails.
Here is my method. It is called from a trigger handler on before update.
public static void uniqueRelationshipOwnerEmails(List<relationship_owner__c> roList){ //count the unique emails that have been sent by a relationship owner // add all contacts associated with relationship owner to map. Map<id, Contact> contactMap = new Map<Id, Contact>([SELECT Id, New_Relationship_Owner1__c FROM Contact WHERE New_Relationship_owner1__c IN : roList]); system.debug('Number of relationship owners in trigger = ' + roList.size()); system.debug('Contacts found = ' + contactMap.size()); //put tasks where whoId is in the contact map into a new map List<Task> taskList = [SELECT Id, WhoId,Subject FROM Task WHERE WhoId IN :contactMap.keySet() AND Subject LIKE '%Pardot List %']; system.debug('Tasks Found and added to map = ' + taskList.size()); //use set to dedupe the list Map<Id, Set<String>> subjectLineMap = new Map<Id, Set<String>>(); for(task t : taskList){ Id ownerId = contactMap.get(t.WhoId).New_Relationship_Owner1__c; if(!subjectLineMap.containsKey(ownerId)){ subjectLineMap.put(ownerId, new Set<String>()); system.debug('Subect Line found ' + t.Subject); }
- Brooks Johnson 6
- October 22, 2018
- Like
- 0
- Continue reading or reply
validation rule missing ')'
Can someone tell me where I'm missing the ')' ? This is a validation rule on a custom object. I'm adding the line with OMTOA but getting a syntex error that I'm missing a ')' - help!
AND(
OR(
ISPICKVAL( Interview_Model__r.Interview_Type__c , "1"),
ISPICKVAL( Interview_Model__r.Interview_Type__c , "2"),
ISPICKVAL( Interview_Model__r.Interview_Type__c , "3"),
ISPICKVAL( Interview_Model__r.Interview_Type__c , "4")),
OR(
NOT(ISBLANK( Profiles__c )),
NOT(ISBLANK( External_Predictions__c )),
NOT(ISBLANK( Internal_Predictions__c ))),
OR(NOT( Interview_Model__r.Name , "OMTOA")),
$User.Bypass_Validation_Rules__c =false)
Thank you!
AND(
OR(
ISPICKVAL( Interview_Model__r.Interview_Type__c , "1"),
ISPICKVAL( Interview_Model__r.Interview_Type__c , "2"),
ISPICKVAL( Interview_Model__r.Interview_Type__c , "3"),
ISPICKVAL( Interview_Model__r.Interview_Type__c , "4")),
OR(
NOT(ISBLANK( Profiles__c )),
NOT(ISBLANK( External_Predictions__c )),
NOT(ISBLANK( Internal_Predictions__c ))),
OR(NOT( Interview_Model__r.Name , "OMTOA")),
$User.Bypass_Validation_Rules__c =false)
Thank you!
- Marilyn Buresh
- October 16, 2018
- Like
- 0
- Continue reading or reply
test class for metadata
I am working on Custom Metadata and I wrote the below trigger.
trigger userSignature on User (before insert,after insert){ if(trigger.isBefore && Trigger.isInsert){ Org_Email_Signature__mdt[] signature = [SELECT MasterLabel,Email_Signature__c FROM Org_Email_Signature__mdt]; if(signature!=nulll & !signature.isEmpty()){ for(user usr : Trigger.new){ usr.Signature = signature[0].Email_Signature__c; } } } }Can anyone help me out in writing a test class for the above trigger please.
- Sainath Venkat
- October 10, 2018
- Like
- 0
- Continue reading or reply
Test Class "Constructor not defined"
Hey Gurus,
I am trying to create a test class for a non-static method in a class. The class is as follows:
and test class:
I am getting an error message that "Error 1 Constructor not defined: [ServiceDeskCreateOpp].<Constructor>() C:\Users\gagnihotri\Documents\The Welkin Suite\Projects\FullSand-New\FullSand-New\src\classes\ServiceDeskCreateOpp_Test.cls 36 1 "
Not sure what am I doing wrong
I am trying to create a test class for a non-static method in a class. The class is as follows:
public class ServiceDeskCreateOpp { public string oppRecordType { get; set; } public string oppName { get; set; } public date OppCloseDate { get; set; } public Id serviceDeskId; public Id OppAccountId; public List<account> SDAccount; //private final ServiceDesk__c serviceDesk; public ServiceDeskCreateOpp(ApexPages.StandardController stdController) { //this.serviceDesk = (ServiceDesk__c) stdController.getRecord(); id serviceDeskId = apexpages.currentpage().getparameters().get('id'); System.debug('serviceDeskId='+serviceDeskId); List<ServiceDesk__c> newServiceDesk = [select Client_Company_Name_Organization__c from ServiceDesk__c where Id = :serviceDeskId]; if (newServiceDesk.size() > 0) { OppAccountId = newServiceDesk[0].Client_Company_Name_Organization__c; } SDAccount = [select id, name from Account where id = :OppAccountId]; if (SDAccount.size()>0 ) { oppName = SDAccount[0].Name; } System.debug('OppAccountId='+OppAccountId); System.debug('newServiceDesk='+newServiceDesk); System.debug('oppName='+oppName); } Public PageReference OppCreate() { Opportunity op = new opportunity(); op.Name = oppName; System.debug(oppName); op.z_Date_Last_non_USD_Hist_Rate_Check__c = System.today(); op.StageName = 'Suspect'; op.CloseDate = OppCloseDate; System.debug(OppCloseDate); System.debug(SDAccount[0].Id); op.AccountId = SDAccount[0].Id; op.recordTypeId = [SELECT Id, Name, SobjectType FROM RecordType WHERE SobjectType = 'Opportunity' AND Name = :oppRecordType].Id; op.Service_Desk_Requests__c = serviceDeskId; insert op; System.debug(System.Label.Opportunity_URL); PageReference pageRef = new PageReference(System.Label.Opportunity_URL + '?id=' + Op.id + '&sfdc.override=1'); System.debug(pageRef); return pageRef; } public List<SelectOption> getSelectOpptyRecordType() { List<SelectOption> options = new List<SelectOption> (); options.add(new SelectOption('Client Renewal', 'Client Renewal')); options.add(new SelectOption('Default', 'Default')); options.add(new SelectOption('Partner Services', 'Partner Services')); options.add(new SelectOption('SMB', 'SMB')); options.add(new SelectOption('SMB Client Renewal', 'SMB Client Renewal')); options.add(new SelectOption('Sub-Contracted Services', 'Sub-Contracted Services')); options.add(new SelectOption('Technical Project', 'Technical Project')); return options; } }
and test class:
@isTest private class ServiceDeskCreateOpp_Test { @TestSetup static void setup() { Account testAccount = TestDataFactory_Account.Execute(); insert testAccount; ServiceDesk__c testServiceDesk = TestDataFactory_ServiceDesk.Execute(); testServiceDesk.Client_Company_Name_Organization__c= testAccount.id; insert testServiceDesk; Opportunity testOpporutnity = TestDataFactory_Opportunity.Execute(); testOpporutnity.AccountId =testAccount.Id; insert testOpporutnity; system.debug('testing class:Account' + testAccount); system.debug('testing class:Service Desk' + testServiceDesk); system.debug('testing class:Opportunity' + testOpporutnity); } static testMethod void testServiceDeskCreateOppy() { Account newAcc = [Select Id, Name from Account]; ServiceDesk__c newSD = [select id from ServiceDesk__c]; Opportunity newOpp = [select id,Name from Opportunity]; PageReference pageRef = Page.ServiceDeskCreateOpp; Test.setCurrentPage(pageRef); ApexPages.currentPage().getParameters().put('id', newSD.id); ServiceDeskCreateOpp newSDOppty = new ServiceDeskCreateOpp(); newSDOppty.OppCreate(); //ServiceDeskCreateOpp newOppty = new ServiceDeskCreateOpp(); //newOppty.OppCreate(); //OppCreate.OppCreate(newSD.id); // ServiceDeskCreateOpp } }
I am getting an error message that "Error 1 Constructor not defined: [ServiceDeskCreateOpp].<Constructor>() C:\Users\gagnihotri\Documents\The Welkin Suite\Projects\FullSand-New\FullSand-New\src\classes\ServiceDeskCreateOpp_Test.cls 36 1 "
Not sure what am I doing wrong
- Gaurav Agnihotri 11
- October 09, 2018
- Like
- 0
- Continue reading or reply
Profile Roles and Sharing Setting
Hi Expert,
How would sharing rule work in the below scenario
Suppose i create a new object called "XXXX". Now profile called "AAAA" doesn't have read, create, edit permission on it.
Q1: What would happen if I create a record of object "XXX" and share it with user which has profile "AAAA" and give him "Edit" permission on the record? Would user be able to see the record or edit the record? please qualify your answer.
Q2: Can anybody explain in what order access on record or object is granted in terms of OWD, Sharing rule, Role and profile?
Q3: If i set OWD setting as Public Read/Edit on Object "XXXX" but profile "AAAA" don't have read, create and edit permission on Object "XXXX" then the user who owns profile "AAAA" would be able to see and edit the records of object "XXXX"?
Q4: What would happen if profile "AAAA" has only Read permission on Object "XXXX" then user who owns profile "AAAA" would be able to see and edit ALL the records of object "XXXX"?
Q5: In order to work out OWD setting, at least profile must have Read permission on that particular object?
Q6: The user who is higher role in hierarchy would get owner permission on the records created by user who are lower in the roles means he can edit and delete the record as well. Is that correct?
Please share your best
Regards
Mukesh
How would sharing rule work in the below scenario
Suppose i create a new object called "XXXX". Now profile called "AAAA" doesn't have read, create, edit permission on it.
Q1: What would happen if I create a record of object "XXX" and share it with user which has profile "AAAA" and give him "Edit" permission on the record? Would user be able to see the record or edit the record? please qualify your answer.
Q2: Can anybody explain in what order access on record or object is granted in terms of OWD, Sharing rule, Role and profile?
Q3: If i set OWD setting as Public Read/Edit on Object "XXXX" but profile "AAAA" don't have read, create and edit permission on Object "XXXX" then the user who owns profile "AAAA" would be able to see and edit the records of object "XXXX"?
Q4: What would happen if profile "AAAA" has only Read permission on Object "XXXX" then user who owns profile "AAAA" would be able to see and edit ALL the records of object "XXXX"?
Q5: In order to work out OWD setting, at least profile must have Read permission on that particular object?
Q6: The user who is higher role in hierarchy would get owner permission on the records created by user who are lower in the roles means he can edit and delete the record as well. Is that correct?
Please share your best
Regards
Mukesh
- mukesh gupta
- September 29, 2018
- Like
- 0
- Continue reading or reply
Trigger not updating account
I hav ethis trigger that should update the parent account with the sum of number of documents from the child AC_Trial object. It is not updating the account.
trigger ACTrialRollup on AC_Trial__c (after insert, after update, after delete) {
List<Account> list_Account= new List<Account>();
set<Id> set_ACTrial = new set<Id>();
for(AC_Trial__c objACT: trigger.new){
set_ACTrial.add(objACT.Account__c);
}
Decimal Sum;
for(Account objAccount : [SELECT Id,Name,(SELECT Id,Name,Number_Of_Documents__c FROM AC_Trial__r) FROM Account WHERE Id IN: set_ACTrial]){
Sum=0;
for(AC_Trial__c objACT01: objAccount.AC_Trial__r ){
Sum+=objACT01.Number_Of_Documents__c ;
}
objAccount.AC_Trial_Documents__c=Sum;
list_Account.add(objAccount);
}
update list_Account;
}
trigger ACTrialRollup on AC_Trial__c (after insert, after update, after delete) {
List<Account> list_Account= new List<Account>();
set<Id> set_ACTrial = new set<Id>();
for(AC_Trial__c objACT: trigger.new){
set_ACTrial.add(objACT.Account__c);
}
Decimal Sum;
for(Account objAccount : [SELECT Id,Name,(SELECT Id,Name,Number_Of_Documents__c FROM AC_Trial__r) FROM Account WHERE Id IN: set_ACTrial]){
Sum=0;
for(AC_Trial__c objACT01: objAccount.AC_Trial__r ){
Sum+=objACT01.Number_Of_Documents__c ;
}
objAccount.AC_Trial_Documents__c=Sum;
list_Account.add(objAccount);
}
update list_Account;
}
- Jim Montgomery
- September 28, 2018
- Like
- 0
- Continue reading or reply
Controller Extension Test Class
Please help me with the Test Class for the below Controller :
public class ActivitySearchController {
Public List<Task> TaskList {get;set;}
String currentId =ApexPages.CurrentPage().getparameters().get('id');
public ActivitySearchController(ApexPages.StandardController controller) {
//Lead ID
if (currentId.startsWith('00Q')) {
try{
List <Lead> leadList = [SELECT id, Email, Alternate_Email__c FROM Lead WHERE ID=:currentId];
String ldEmail = leadList[0].Email;
String ldAltEmail = leadList[0].Alternate_Email__c;
Set<String> emailIds = new Set<string>();
if(ldEmail!=null){
emailIds.add(ldEmail);
}
if(ldAltEmail!=null){
emailIds.add(ldAltEmail);
}
List <Lead> rldLead = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
List <Account> accLst = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
Set<Id> leadID = new Set<Id>();
Set<Id> accIds = new Set<Id>();
for(Lead lE : rldLead){
leadID.add(lE.id);
}
for(Account acc : accLst){
accIds.add(acc.id);
}
TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task
WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC];
if(TaskList.size() == 0)
{
Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
}
}
catch(Exception e){
system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
}
}
//Account ID
else if (currentId.startsWith('001p')) {
try{
List <Account> accList = [SELECT id, PersonEmail, Alternate_Email__c FROM Account WHERE ID=:currentId];
String ldEmail = accList[0].PersonEmail;
String ldAltEmail = accList[0].Alternate_Email__c;
Set<String> emailIds = new Set<string>();
if(ldEmail!=null){
emailIds.add(ldEmail);
}
if(ldAltEmail!=null){
emailIds.add(ldAltEmail);
}
List <Lead> rldLead = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
List <Account> accLst = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
Set<Id> leadID = new Set<Id>();
Set<Id> accIds = new Set<Id>();
for(Lead lE : rldLead){
leadID.add(lE.id);
}
for(Account acc : accLst){
accIds.add(acc.id);
}
TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task
WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC LIMIT 10];
if(TaskList.size() == 0)
{
Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
}
}
catch(Exception e){
system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
}
}
//Opportunity ID
else if (currentId.startsWith('006p')) {
try{
List <Opportunity> oppList = [SELECT id, AccountId FROM Opportunity WHERE ID=:currentId];
String oppID = oppList[0].Accountid;
List <Account> oppAccList = [SELECT id, PersonEmail, Alternate_Email__c FROM Account WHERE ID =: oppID];
String ldEmail = oppAccList[0].PersonEmail;
String ldAltEmail = oppAccList[0].Alternate_Email__c;
Set<String> emailIds = new Set<string>();
if(ldEmail!=null){
emailIds.add(ldEmail);
}
if(ldAltEmail!=null){
emailIds.add(ldAltEmail);
}
List <Lead> rldLead = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
List <Account> accLst = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
Set<Id> leadID = new Set<Id>();
Set<Id> accIds = new Set<Id>();
for(Lead lE : rldLead){
leadID.add(lE.id);
}
for(Account acc : accLst){
accIds.add(acc.id);
}
TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task
WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC LIMIT 10];
if(TaskList.size() == 0)
{
Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
}
}
catch(Exception e){
system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
}
}
}
}
public class ActivitySearchController {
Public List<Task> TaskList {get;set;}
String currentId =ApexPages.CurrentPage().getparameters().get('id');
public ActivitySearchController(ApexPages.StandardController controller) {
//Lead ID
if (currentId.startsWith('00Q')) {
try{
List <Lead> leadList = [SELECT id, Email, Alternate_Email__c FROM Lead WHERE ID=:currentId];
String ldEmail = leadList[0].Email;
String ldAltEmail = leadList[0].Alternate_Email__c;
Set<String> emailIds = new Set<string>();
if(ldEmail!=null){
emailIds.add(ldEmail);
}
if(ldAltEmail!=null){
emailIds.add(ldAltEmail);
}
List <Lead> rldLead = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
List <Account> accLst = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
Set<Id> leadID = new Set<Id>();
Set<Id> accIds = new Set<Id>();
for(Lead lE : rldLead){
leadID.add(lE.id);
}
for(Account acc : accLst){
accIds.add(acc.id);
}
TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task
WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC];
if(TaskList.size() == 0)
{
Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
}
}
catch(Exception e){
system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
}
}
//Account ID
else if (currentId.startsWith('001p')) {
try{
List <Account> accList = [SELECT id, PersonEmail, Alternate_Email__c FROM Account WHERE ID=:currentId];
String ldEmail = accList[0].PersonEmail;
String ldAltEmail = accList[0].Alternate_Email__c;
Set<String> emailIds = new Set<string>();
if(ldEmail!=null){
emailIds.add(ldEmail);
}
if(ldAltEmail!=null){
emailIds.add(ldAltEmail);
}
List <Lead> rldLead = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
List <Account> accLst = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
Set<Id> leadID = new Set<Id>();
Set<Id> accIds = new Set<Id>();
for(Lead lE : rldLead){
leadID.add(lE.id);
}
for(Account acc : accLst){
accIds.add(acc.id);
}
TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task
WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC LIMIT 10];
if(TaskList.size() == 0)
{
Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
}
}
catch(Exception e){
system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
}
}
//Opportunity ID
else if (currentId.startsWith('006p')) {
try{
List <Opportunity> oppList = [SELECT id, AccountId FROM Opportunity WHERE ID=:currentId];
String oppID = oppList[0].Accountid;
List <Account> oppAccList = [SELECT id, PersonEmail, Alternate_Email__c FROM Account WHERE ID =: oppID];
String ldEmail = oppAccList[0].PersonEmail;
String ldAltEmail = oppAccList[0].Alternate_Email__c;
Set<String> emailIds = new Set<string>();
if(ldEmail!=null){
emailIds.add(ldEmail);
}
if(ldAltEmail!=null){
emailIds.add(ldAltEmail);
}
List <Lead> rldLead = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
List <Account> accLst = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
Set<Id> leadID = new Set<Id>();
Set<Id> accIds = new Set<Id>();
for(Lead lE : rldLead){
leadID.add(lE.id);
}
for(Account acc : accLst){
accIds.add(acc.id);
}
TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task
WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC LIMIT 10];
if(TaskList.size() == 0)
{
Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
}
}
catch(Exception e){
system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
}
}
}
}
- Shravan Kumar 71
- September 27, 2018
- Like
- 0
- Continue reading or reply
Code coverage error 71% need 75%
I've been trying to add more criteria to pass the code coverage to move a trigger to production but my test class doesn't pass the the coverage test. I don't know how much more criteria I can add. Any help with this would be greatly appreciated.
@IsTest public class TestAfterPOLogUpdateTest { static testMethod void myUnitTest() { // TO DO: implement unit test test.startTest(); Map<String, Schema.RecordTypeInfo> recordTypes = Schema.SObjectType.Yushin_Product__c.getRecordTypeInfosByName(); List<String> recordTypeNames = new List<String>(recordTypes.keyset()); PageReference pageRef = Page.OppTabDetailinsidesales2; Contact c= new Contact(); c.FirstName ='Bob'; c.LastName = 'Poliquin'; c.Email = 'Acme@aol.com'; c.Phone = '5088084748'; insert c; Account a = new Account(); a.Name = 'Test'; a.Industry = 'Retail'; a.Territory_Code__c='KY'; a.Sales_Agency__c='Five Nines - Plastics Division'; insert a; Opportunity o = new Opportunity(); o.name = 'Test'; o.AccountId = a.Id; o.StageName = 'Closed Won'; o.CloseDate = date.today(); o.Type = 'New Customers'; o.Product_Type__c = 'Robot'; insert o; Product2 prod = new Product2(Name = 'HOP Five 900X', Robot_Category__c = 'Hardware',Standard_Price__c=12345); insert prod; Id pricebookId = Test.getStandardPricebookId(); PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId, Product2Id = prod.Id, UnitPrice = 10000, IsActive = true); insert standardPrice; Request_for_Special_Payment__c rsp = new Request_for_Special_Payment__c (); rsp.Opportunity_Name__c = o.Id; rsp.Account__c = a.Id; rsp.Requestor_Submit_for_Approval__c = true; rsp.Request_Submitted_By__c = 'Bob Poliquin'; rsp.Requestor_Date_Submitted__c=date.today(); insert rsp; rsp.Opportunity_Name__c = o.Id; rsp.Supervisor_Approved__c = true; rsp.Rejected_By__c='Chris Parillo'; rsp.Supervisor_Approval_Date__c=date.today(); update rsp; PO_Log__c p = new PO_Log__c(); p.Customer__c=a.Id; p.Opportunity__c=o.Id; p.Order_Type__c='EOAT'; insert p; p.Opportunity__c= o.Id; p.PO__c = '1223'; p.Sales_Order_Number__c = '12453'; p.Order_Type__c = 'Robot'; p.Notes__c= 'text'; p.Order_Configuration__c = 'ATC'; p.Sales_Order_Number__c = '189345'; p.AddPLogOpps__c = true; update p; Yushin_Product__c ypd = new Yushin_Product__c(Discharge_Direction__c='Clamp Traverse'); ypd.Opportunity__c=o.id; ypd.Account__c =a.Id; ypd.Discharge_Direction__c='Clamp Traverse'; ypd.IMM_Mfr__c='Arburg'; ypd.IMM_Model__c='NT450'; ypd.Plant_Voltage__c='110'; ypd.Interface_Voltage__c='110 VDC'; ypd.Equipment_Type__c = 'Robot'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); insert ypd; ypd.Account__c =a.Id ; ypd.Discharge_Direction__c='Clamp Traverse'; ypd.IMM_Mfr__c='Engel'; ypd.IMM_Model__c='110t'; ypd.Plant_Voltage__c='110'; ypd.Interface_Voltage__c='110 VDC'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Equipment_Type__c = 'Other'; ypd.Product_Detail_Report__c = 'Misc. Item'; ypd.SPI_Reported__c=false; ypd.Date_Booked__c = Date.newInstance(2016, 12, 9); ypd.Date_Entered__c = Date.newInstance(2016, 12, 8); ypd.Sales_Order_Number__c = '1910678'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Equipment_Type__c = 'Installation'; ypd.Product_Detail_Report__c = 'Installation'; ypd.SPI_Reported__c=false; ypd.Date_Booked__c = Date.newInstance(2016, 12, 9); ypd.Date_Entered__c = Date.newInstance(2016, 12, 8); ypd.Sales_Order_Number__c = '1910678'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Equipment_Type__c = 'EOAT'; ypd.Price__c = 499; ypd.Model__c='HOP 750'; ypd.Status__c ='Quoted'; ypd.Date_Booked__c = Date.newInstance(2016, 12, 9); ypd.Date_Entered__c = Date.newInstance(2016, 12, 8); update ypd; ypd.Equipment_Type__c = 'Safety Guarding'; ypd.Product_Detail_Report__c = 'AUTO-SM'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Equipment_Type__c = 'Conveyor'; ypd.Price__c =45080; ypd.Status__c ='Sold'; ypd.Date_Booked__c = Date.newInstance(2016, 12, 9); ypd.Date_Entered__c = Date.newInstance(2016, 12, 8); ypd.Quantity__c= 1; ypd.Product_Detail_Report__c = 'AUTO-SM'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Price__c =45080; ypd.Equipment_Type__c = 'Servo Trav over 600'; ypd.Model__c='FRA-1530S-22-11-C1 '; ypd.Status__c ='Sold'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Price__c =45080; ypd.Equipment_Type__c = 'Adapter Plate'; ypd.Product_Detail_Report__c='Misc. Item'; ypd.Status__c ='Sold'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); update ypd; ypd.Price__c =45080; ypd.Equipment_Type__c = 'A-Axis'; ypd.Product_Detail_Report__c='EOAT-SM'; ypd.RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId(); ypd.Status__c ='Sold'; update ypd; ypd.Price__c =45080; ypd.Equipment_Type__c = 'B-Axis'; ypd.Status__c ='Sold'; update ypd; ypd.Price__c =45080; ypd.Equipment_Type__c = 'Freight'; ypd.Product_Detail_Report__c='Freight'; update ypd; ypd.Price__c =45080; ypd.Equipment_Type__c = 'Degating Station'; ypd.Product_Detail_Report__c='AUTO-SM'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Installation'; ypd.Product_Detail_Report__c='Installation'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Hybrid'; ypd.Product_Detail_Report__c='SM-Hybrid'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Software'; ypd.Product_Detail_Report__c='Software'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Servo Traverse Super Large 1300 and greater'; ypd.Model__c='RAII-a-3000SL'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Spacer'; ypd.Product_Detail_Report__c='Misc. Item'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Stanchion'; ypd.Status__c ='Quoted'; update ypd; ypd.Equipment_Type__c = 'Servo Trav over 600'; ypd.Model__c='YCII-800D-30-18'; ypd.Product_Detail_Report__c='LG-YC'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'System - SMALL'; ypd.Product_Detail_Report__c='AUTO-SM'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Collaborative robot'; ypd.Model__c='OB7'; ypd.Product_Detail_Report__c='SPECIAL'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Side-entry (horz)'; ypd.Model__c='SVR B50'; ypd.Product_Detail_Report__c='SM-SE'; update ypd; ypd.Equipment_Type__c = 'Side-entry (Vert)'; ypd.Product_Detail_Report__c='SM-SE'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Parts'; ypd.Product_Detail_Report__c='Misc. Item'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'Safety Guarding'; ypd.Product_Detail_Report__c='AUTO-SM'; ypd.Status__c ='Sold'; update ypd; ypd.Equipment_Type__c = 'System - MEDIUM'; ypd.Product_Detail_Report__c='AUTO-SM'; ypd.Status__c ='Quoted'; ypd.Order_Config__c = 'Systems'; ypd.Order_Type__c = 'Systems'; update ypd; test.stopTest(); } }
- BobP
- September 24, 2018
- Like
- 0
- Continue reading or reply
Process Automation Specialist Step 3
I am getting the following error on Step 3
Challenge Not yet complete... here's what's wrong:
The 'Name' field on the 'Robot_Setup__c' object does not appear to be an auto number data type.
The data type is correct. I've deleted and readded the field and gotten the same error each time.
Challenge Not yet complete... here's what's wrong:
The 'Name' field on the 'Robot_Setup__c' object does not appear to be an auto number data type.
The data type is correct. I've deleted and readded the field and gotten the same error each time.
- Richard Bottorff 18
- September 19, 2018
- Like
- 0
- Continue reading or reply
need to exclude weekends using validation rule
Hi, I want to exclude validation rule to fire when users enter any weekend date for a date field.
Any suggestions would help.
Thanks in advance.
Any suggestions would help.
Thanks in advance.
- S b 25
- September 19, 2018
- Like
- 0
- Continue reading or reply
How to avoid updating records with a trigger.
Hi Guys !
I want to avoid with a trigger that a user who is not a system administrator can change the status of a case.
I want to avoid with a trigger that a user who is not a system administrator can change the status of a case.
- Assaltu RD
- September 18, 2018
- Like
- 0
- Continue reading or reply
Test class to check user profile and page reference
I am working on a apex class for the opportunity object to display a visualforce page if the current user has a specific profile i.e. System Administrator. I'm not sure how to write a test class to check user profiles and page references. Any help on this would be greatly appreciated.
Apex Class:
Apex Class:
public class overrideOpp { String recordId; public overrideOpp(ApexPages.StandardController controller) {recordId = controller.getId();} public PageReference redirect() { Profile p = [select name from Profile where id = :UserInfo.getProfileId()]; if ('System Administrator'.equals(p.name) || 'Inside Standard User'.equals(p.name)) { PageReference customPage = Page.OppTabDetailinsidesales2; customPage.setRedirect(true); customPage.getParameters().put('id', recordId); return customPage; } else { return null; //otherwise stay on the same page } } }
- BobP
- September 18, 2018
- Like
- 0
- Continue reading or reply
Retrieving data in a Map from 1 of 2 records retrieved from a SOQL query
Hello - I have an object called Agent. Every sales rep has 2 agent records. One record represents an Outbound record and the other is Inbound. The field that identifies inbound/outbound is Rep_Type__c. For outbound it's SLO. For inbound it's SLI.
Below is the query I'm using to get both records.
List<Agent__c> salesAgentList = [SELECT Id, SOB_Code__c, Name, Rep_Type__c, Agent_Performance__c, User__c FROM Agent__c
WHERE SOB_Code__c IN :mapNewSalesAgntSOB.keySet() OR User__c IN :mapOfNewLeadOwner.keySet()];
The problem is, my map is grabbing the inbound record (SLI) and I need to grab the outbound record (SLO).
Map<Id, String> mapOfSalesRepType = new Map<Id, String>();
for(Agent__c agt : salesAgentList) {
mapOfSalesRepType.put(agt.User__c, agt.Rep_Type__c);
}
System.debug('Agent Rep type ' + mapOfSalesRepType);
How can I do this?
Below is the query I'm using to get both records.
List<Agent__c> salesAgentList = [SELECT Id, SOB_Code__c, Name, Rep_Type__c, Agent_Performance__c, User__c FROM Agent__c
WHERE SOB_Code__c IN :mapNewSalesAgntSOB.keySet() OR User__c IN :mapOfNewLeadOwner.keySet()];
The problem is, my map is grabbing the inbound record (SLI) and I need to grab the outbound record (SLO).
Map<Id, String> mapOfSalesRepType = new Map<Id, String>();
for(Agent__c agt : salesAgentList) {
mapOfSalesRepType.put(agt.User__c, agt.Rep_Type__c);
}
System.debug('Agent Rep type ' + mapOfSalesRepType);
How can I do this?
- Dbjensen
- September 13, 2018
- Like
- 0
- Continue reading or reply
Elastic Search scroll_id
I need to get data from a web service that only returns 10 records at a time. Even when I set the size parameter to a higher number, I still only get 10 records. The web service owners tell me I must use the scroll_id from elastic search.
Below is my code
The last class is used to parse the json and in there I am able to access the scroll id parameter.
I need help setting up the code to run continuously/recursively until all the records are returned. Anyone willing to help me on this? I do not want to keep
Below is my code
HttpRequest req = new HttpRequest(); req.setEndpoint('https://aa.bb.org/bdo/2.3.0/-eligible-for-af'); req.setMethod('POST'); req.setHeader('Authorization', 'Bearer eeee-gggg-hhhh-ijkl'); System.JSONGenerator gen = System.JSON.createGenerator(true); gen.writeStartObject(); gen.writeFieldName('query'); gen.writeStartObject(); gen.writeFieldName('match_all'); gen.writeStartObject(); gen.writeEndObject(); gen.writeNumberField('size', 500); gen.writeEndObject(); String pretty = gen.getAsString(); req.setBody(pretty); Http httpReq = new Http(); HttpResponse res = httpReq.send(req); json = res.getBody(); AfJSON2Apex afWithFinance = AfJSON2Apex.parse(json);
The last class is used to parse the json and in there I am able to access the scroll id parameter.
I need help setting up the code to run continuously/recursively until all the records are returned. Anyone willing to help me on this? I do not want to keep
- Steven Nsubuga
- May 05, 2021
- Like
- 0
- Continue reading or reply
Custom Button created in Classic not working well with Lightning
A few years ago I created a Custom button on Account to create an Opportunity for that Account. On clicking the button, a visualforce page would load, showing some info and then when the user clicked ok, it would load the list of Opportunity record types, and after that would load the new opportunity detail page with the Account field prefilled. I used Apex and some URL hacking to prefill the Account field.
When we switched from Classic to Lightning, the Account field was no longer prefilled. It seems like way too much work to redo this feature from scratch using LWC which I am still learning. Any thoughts on how I can fix this? Everything else works but the Account field is no longer prefilled as before and this is a huge inconvenience to say the least.
When we switched from Classic to Lightning, the Account field was no longer prefilled. It seems like way too much work to redo this feature from scratch using LWC which I am still learning. Any thoughts on how I can fix this? Everything else works but the Account field is no longer prefilled as before and this is a huge inconvenience to say the least.
- Steven Nsubuga
- August 04, 2020
- Like
- 0
- Continue reading or reply
Can Salesforce access a web service on a company Intranet?
I have a client who has a system that is only accessible via the company's Intranet. I have a web service that I am calling from Salesforce. I got the following error:
CALLOUT_RESPONSE </head><body id=ERR_ACCESS_DENIED>
CALLOUT_RESPONSE <h2>The requested URL could not be retrieved</h2>
CALLOUT_RESPONSE <p>Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect.</p>
CALLOUT_RESPONSE <p>Generated Mon, 15 Oct 2018 by proxy-dfw.net.salesforce.com (squid)</p>
EXCEPTION_THROWN [280]|System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':html'
I got that far by using a developer org. Sandbox and Production only gave me the Exception: System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':html'
Any advice/tips?
CALLOUT_RESPONSE </head><body id=ERR_ACCESS_DENIED>
CALLOUT_RESPONSE <h2>The requested URL could not be retrieved</h2>
CALLOUT_RESPONSE <p>Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect.</p>
CALLOUT_RESPONSE <p>Generated Mon, 15 Oct 2018 by proxy-dfw.net.salesforce.com (squid)</p>
EXCEPTION_THROWN [280]|System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':html'
I got that far by using a developer org. Sandbox and Production only gave me the Exception: System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':html'
Any advice/tips?
- Steven Nsubuga
- October 15, 2018
- Like
- 0
- Continue reading or reply
RelationShip Query with custom field on standard object
My Object Acount has a custom field ProfessionalReference__c
When i execute in developer : select id, type, what.name from task : It's work
When I execute : select id, type, what.ProfessionalReference__c from task.
It doesn't work. Could you please explain ?
Thanks
When i execute in developer : select id, type, what.name from task : It's work
When I execute : select id, type, what.ProfessionalReference__c from task.
It doesn't work. Could you please explain ?
Thanks
- Philippe Coste 2
- August 04, 2020
- Like
- 0
- Continue reading or reply
Syntax Error in Visualforce with no Details
I'm building a visualforce page for the first time, it's not complete and I'm just playing around with layouts but I'm getting a Syntax Error with no information telling me what the error is, screenshot of the data below. Please help!
- Sammy Wessel
- August 04, 2020
- Like
- 0
- Continue reading or reply
Generate WDSL button is disabled in my Apex class
I have the apex class exposed as webservice, but I am not able to generate the WSDL for my Apex class.
Please help me out.
Please help me out.
- Neethu u
- February 07, 2019
- Like
- 0
- Continue reading or reply
Apex Code to refresh child items error " Attempt to de-reference a null object An unexpected error has occurred. Your development organization has been notified."
Hi all. i'm trying to create a button that refreshes the child opportunity products when discounts are changed on a opportunity.
The Apex code ges a list of the child opportunity products and updates them.
The Visual Force button runs the method. howveer i get an error saying:
Attempt to de-reference a null object
An unexpected error has occurred. Your development organization has been notified.
Any idea what I am doing wrong?
Apex Class
VF Page
The Apex code ges a list of the child opportunity products and updates them.
The Visual Force button runs the method. howveer i get an error saying:
Attempt to de-reference a null object
An unexpected error has occurred. Your development organization has been notified.
Any idea what I am doing wrong?
Apex Class
PUBLIC CLASS OpportunityProductCostRefreshController { //add an instance variable for the standard controller private ApexPages.StandardController controller {get; set;} // add the instance for the variables being passed by id on the url public opportunity OP {get;set;} // set the id of the record that is created -- ONLY USED BY THE TEST CLASS public ID newRecordId {get;set;} //Add the variable for the list being queried PUBLIC LIST <OpportunityLineItem> GetItemsList {get;set;} // Initialize the controller PUBLIC OpportunityProductCostRefreshController(ApexPages.StandardController ctrl) { //initialize the standard controller this.controller = controller; // load the current record OP = (Opportunity)controller.getRecord(); } // method called from the VF's action attribute to refreshing the op lines public PageReference RefreshOpLines() { // setup the save point for rollback Savepoint sp = Database.setSavepoint(); TRY { // Get the list of opportunity line items we want to refresh costs for GetItemsList = [ SELECT Id,OpportunityId, productcode, Quantity, unitprice FROM OpportunityLineItem OPL WHERE Opportunityid= :OP.id ORDER BY productcode ASC ]; { UPDATE GetItemsList ; return null; } } catch (Exception e){ // roll everything back in case of error Database.rollback(sp); ApexPages.addMessages(e); } return new PageReference('/'+OP.id); } }
VF Page
<apex:page standardController="Opportunity" extensions="OpportunityProductCostRefreshController" action="{!RefreshOpLines}"> <apex:pageMessages /> </apex:page>
- TC Admin
- January 31, 2019
- Like
- 0
- Continue reading or reply
how to write a test code
trigger RollUpOppAmt on Opportunity (after insert) {
Set<Id> setOpportunityIds=new Set<Id>();
for(Opportunity o:Trigger.new)
setOpportunityIds.add(o.id);
List<Account> ListOfAmt = [select id, Amount__c from Account];
List<Account> lstAmtToUpdate=new List<Account>();
for(AggregateResult result:[SELECT AccountId, SUM(Amount) FROM Opportunity
WHERE Id IN :setOpportunityIds GROUP BY AccountId]) {
for(Account acc : ListOfAmt) {
if(result.get('AccountId') == acc.Id) {
if(acc.Amount__c == null) {
acc.Amount__c = 0;
}
acc.Amount__c = acc.Amount__c + Decimal.ValueOf(String.ValueOf(result.get('expr0')));
lstAmtToUpdate.add(acc);
}
}
}
if(lstAmtToUpdate.size()>0) {
UPDATE lstAmtToUpdate;
}
}
Set<Id> setOpportunityIds=new Set<Id>();
for(Opportunity o:Trigger.new)
setOpportunityIds.add(o.id);
List<Account> ListOfAmt = [select id, Amount__c from Account];
List<Account> lstAmtToUpdate=new List<Account>();
for(AggregateResult result:[SELECT AccountId, SUM(Amount) FROM Opportunity
WHERE Id IN :setOpportunityIds GROUP BY AccountId]) {
for(Account acc : ListOfAmt) {
if(result.get('AccountId') == acc.Id) {
if(acc.Amount__c == null) {
acc.Amount__c = 0;
}
acc.Amount__c = acc.Amount__c + Decimal.ValueOf(String.ValueOf(result.get('expr0')));
lstAmtToUpdate.add(acc);
}
}
}
if(lstAmtToUpdate.size()>0) {
UPDATE lstAmtToUpdate;
}
}
- Chiyan
- January 31, 2019
- Like
- 0
- Continue reading or reply
list has more than 1 row for assignment
Hi all,
May I have some assistance with the below code , this works perfectly if one record is being created but when i create multiple records at the same time I get an error that the List has more than 1 row for assignment to SObject.
Can someone take a look at what I may be doing wrong. This is the line where the error is originating.
newSOWrappers.Add(new SOWrapper(shipmentOrder));
May I have some assistance with the below code , this works perfectly if one record is being created but when i create multiple records at the same time I get an error that the List has more than 1 row for assignment to SObject.
Can someone take a look at what I may be doing wrong. This is the line where the error is originating.
newSOWrappers.Add(new SOWrapper(shipmentOrder));
public class SOWrapper { public SOWrapper(Shipment_Order__c so, boolean recalculateCosts) { this.SO = so; this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c]; this.Client = so.Account__r; if (recalculateCosts ) recalculateCostings(); else buildCostings(); } public SOWrapper(Shipment_Order__c so) { this.SO = so; this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c]; this.Client = so.Account__r; if (so.CPA_v2_0__c != null) buildCostings(); } public Shipment_Order__c SO { set; get; } public CPA_v2_0__c CAP { set; get; } public Account Client { set; get; } private List<CPA_Costing__c> relatedCostings; private List<CPA_Costing__c> relatedCostingsIOR; private List<CPA_Costing__c> relatedCostingsEOR; private List<CPA_Costing__c> addedCostings; private List<CPA_Costing__c> updatedCostings; private Id recordTypeId = Schema.SObjectType.CPA_Costing__c.getRecordTypeInfosByName() .get('Display').getRecordTypeId(); public void buildCostings() { relatedCostingsIOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'IOR' ]; relatedCostingsEOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'EOR']; If(SO.Service_Type__c == 'IOR') { List<CPA_Costing__c> SOCPAcostingsIOR = relatedCostingsIOR.deepClone(); for(CPA_Costing__c cost : SOCPAcostingsIOR) { cost.Shipment_Order_Old__c = SO.ID; cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c; cost.recordTypeID = recordTypeId; cost.VAT_Rate__c = CAP.VAT_Rate__c; if (SO.Shipment_Value_USD__c != null) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, cost, false); } } addedCostings = SOCPAcostingsIOR; } Else If(SO.Service_Type__c == 'EOR') { List<CPA_Costing__c> SOCPAcostingsEOR = relatedCostingsEOR.deepClone(); for(CPA_Costing__c cost : SOCPAcostingsEOR) { cost.Shipment_Order_Old__c = SO.ID; cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c; cost.recordTypeID = recordTypeId; cost.VAT_Rate__c = CAP.VAT_Rate__c; if (SO.Shipment_Value_USD__c != null && (SO.FC_Total__c == null || SO.FC_Total__c == 0)) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, cost, false); } } addedCostings = SOCPAcostingsEOR; } } public void recalculateCostings() { relatedCostings = [SELECT Name, Shipment_Order_Old__c, IOR_EOR__c,Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE Shipment_Order_Old__c =: SO.ID]; System.debug('relatedCostings --- '+relatedCostings.size()); List<CPA_Costing__c> delList = new List<CPA_Costing__c>(); for(CPA_Costing__c var: relatedCostings ) { if(var.Cost_Type__c == 'Variable'){ CPA_Costing__c del = new CPA_Costing__c(); del.id =var.id; delList.add(del); } } updatedCostings = new List<CPA_Costing__c>(); System.debug('updatedCostings --- '+updatedCostings.size()); List<CPA_Costing__c> relatedTemplateCPAcostings = [SELECT Name, IOR_EOR__c,Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, CPA_v2_0__r.VAT_Rate__c, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id ]; List<CPA_Costing__c> updateCosting = new List<CPA_Costing__c >(); Set<Id> ids = new Set<id>(); for (CPA_Costing__c templateCost : relatedTemplateCPAcostings) { SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false); System.debug('The cost id; ----------# '+templateCost.Id+' Amount:- '+templateCost.Amount__c); for(CPA_Costing__c cost : relatedCostings){ if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name != cost.Name && templateCost.Cost_Type__c == cost.Cost_Type__c && templateCost.Applied_to__c == cost.Applied_to__c && templateCost.IOR_EOR__c == cost.IOR_EOR__c){ System.debug(' Do update: '+cost.Id+' the amount '+templateCost.Amount__c+' --- name '+ templateCost.Name); if(!ids.contains(cost.id) && templateCost.Amount__c > -1){ cost.Id = cost.Id; cost.Name = templateCost.Name; cost.Amount__c = templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c; cost.Ceiling__c = templateCost.Ceiling__c; cost.Conditional_value__c = templateCost.Conditional_value__c; cost.Condition__c = templateCost.Condition__c; cost.Cost_Type__c = templateCost.Cost_Type__c; cost.Floor__c = templateCost.Floor__c; cost.Max__c = templateCost.Max__c; cost.Min__c = templateCost.Min__c; cost.Rate__c = templateCost.Rate__c; cost.Variable_threshold__c = templateCost.Variable_threshold__c; cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c; cost.Cost_Category__c = templateCost.Cost_Category__c ; cost.IOR_EOR__c = templateCost.IOR_EOR__c; updateCosting.add(cost); ids.add(cost.id); } } } } if(!updateCosting.IsEmpty()){ update updateCosting; } List<CPA_Costing__c> updateCostList = new List<CPA_Costing__c>(); for(CPA_Costing__c cost : relatedCostings) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, cost, false); System.debug('The cost id; --------'+cost.Id+' Amount:- '+cost.Amount__c); IF(cost.Amount__c == -1){ } System.debug(' --- cost '+cost.Amount__c); if (cost.Amount__c >= 0) { System.debug(' --- amount '+relatedTemplateCPAcostings); for (CPA_Costing__c templateCost : relatedTemplateCPAcostings) { System.debug(' --- templateCost '); if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name == cost.Name) { cost.Updating__c = !cost.Updating__c; SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false); System.debug(' --- templateCost2 '+templateCost.Amount__c); if (templateCost.Amount__c > 0) { System.debug(' ---inside '+templateCost.Amount__c); cost.Amount__c = templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c; cost.Ceiling__c = templateCost.Ceiling__c; cost.Conditional_value__c = templateCost.Conditional_value__c; cost.Condition__c = templateCost.Condition__c; cost.Cost_Type__c = templateCost.Cost_Type__c; cost.Floor__c = templateCost.Floor__c; cost.Max__c = templateCost.Max__c; cost.Min__c = templateCost.Min__c; cost.Rate__c = templateCost.Rate__c; cost.Variable_threshold__c = templateCost.Variable_threshold__c; cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c; system.debug('THE COST ' + cost.ID+' '+cost.Name); } } } } updatedCostings.Add(cost); } if(!updateCostList.IsEmpty()){ insert updateCostList; } } public List<CPA_Costing__c> getApplicableCostings() { List<CPA_Costing__c> applicableCostings = new List<CPA_Costing__c>(); if (addedCostings != null) for (CPA_Costing__c cost : addedCostings) if (cost.Amount__c > -1 && cost.Shipment_Order_Old__c != null) applicableCostings.Add(cost); if (updatedCostings != null) for (CPA_Costing__c cost : updatedCostings) if (cost.Amount__c > -1) applicableCostings.Add(cost); return applicableCostings; } }
public class CalculateCosts { @InvocableMethod public static void createSOCosts(List<Id> SOIds) { List<SOWrapper> newSOWrappers = new List<SOWrapper>(); List<ID> SOsToUpdate = new List<Id>(); List<Shipment_Order__c> shipmentOrder = [Select Id, Name, Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c, FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c, TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c, Account__c, Service_Type__c, Total_Taxes__c FROM Shipment_Order__c where id IN :SOIds]; List<Shipment_Order__c> SOs = new List<Shipment_Order__c>(); List<CPA_Costing__c> costingsToAddUpdate = new List<CPA_Costing__c>(); List<Shipment_Order__c> updatedSOs = [SELECt Id, Name, Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c, FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c, TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c FROM Shipment_Order__c WHERE ID in: SOsToUpdate]; newSOWrappers.Add(new SOWrapper(shipmentOrder)); if (newSOWrappers.size() > 0 && shipmentOrder.size() > 0 ) { for (SOWrapper wrp : newSOWrappers) { Shipment_Order__c SO; for (Shipment_Order__c SOToUpdate : updatedSOs) if (SOToUpdate.ID == wrp.SO.ID) { SO = SOToUpdate; break; } costingsToAddUpdate.AddAll(wrp.getApplicableCostings()); } } Upsert costingsToAddUpdate; update SOs; } }
- Masechaba Maseli 8
- December 19, 2018
- Like
- 0
- Continue reading or reply
i am getting error variable doesnt exist .variable doesnt exist Contact_Area__c, contact_country__c
parent object: account
fields : contact country - Picklist values: India, Africa, America
child object : contact
field : Contact Area - Picklist values: Karataka, Andhra Pradesh, Kerala, South Africa, Nigeria, Kenya, California, San Fransisco, Texas
when contact is inserted / updated, based the contact's Contact Area field the parents contact Country should change with respected country. wirte a trigger for insert, Update. create required fields.
trigger ConnectA on Contact (after insert,after update) {
Map<Id,Contact> AccID = New Map<Id,Contact>();
Map<Id,Contact> oldCOn = trigger.oldMap ;
for(Contact con : Trigger.new){
if( (con.contact_country__c!=oldCOn.get(con.Id).contact_country__c) ||
(con.Contact_Area__c!=oldCOn.get(con.Id).Contact_Area__c) ){
AccID.add(con.AccountId);
}
}
List<Account> accList = [SELECT Name, BillingStreet FROM Account WHERE id in :AccID.keySet()];
for(Account a :accList){
Contact c = AccID.get(a.Id) ;
a.Contact_Area__c = c.Contact_Area__c ;
a.contact_country__c = c.contact_country__c ;
}
update accList;
}
fields : contact country - Picklist values: India, Africa, America
child object : contact
field : Contact Area - Picklist values: Karataka, Andhra Pradesh, Kerala, South Africa, Nigeria, Kenya, California, San Fransisco, Texas
when contact is inserted / updated, based the contact's Contact Area field the parents contact Country should change with respected country. wirte a trigger for insert, Update. create required fields.
trigger ConnectA on Contact (after insert,after update) {
Map<Id,Contact> AccID = New Map<Id,Contact>();
Map<Id,Contact> oldCOn = trigger.oldMap ;
for(Contact con : Trigger.new){
if( (con.contact_country__c!=oldCOn.get(con.Id).contact_country__c) ||
(con.Contact_Area__c!=oldCOn.get(con.Id).Contact_Area__c) ){
AccID.add(con.AccountId);
}
}
List<Account> accList = [SELECT Name, BillingStreet FROM Account WHERE id in :AccID.keySet()];
for(Account a :accList){
Contact c = AccID.get(a.Id) ;
a.Contact_Area__c = c.Contact_Area__c ;
a.contact_country__c = c.contact_country__c ;
}
update accList;
}
- DIVAKAR BABU 15
- December 16, 2018
- Like
- 0
- Continue reading or reply
Print a string in a banner based on picklist value selected
I want my banner to simply say something that references the picklist option selected (I know I can do this with just visualforce, but would like to add more than the picklist option (for example: "The promotion for this opportunity is: [promo]"), but I keep on getting the "Content cannot be displayed: SObject row was retrieved via SOQL without querying the requested field: Opportunity.Promotion_Code__c" error. Any help is appreciated. Here's my visualforce and controller code:
VF Code:
<apex:page standardController="Opportunity" extensions="PartnerPromotionBanner">
<marquee id="banner" rendered="{!Msgid}" style="box-shadow: 0px 0px 15px black; border-radius: 5px; padding: 10px; background-color: #FF0000; font-weight: bolder; font-size: 16px; margin: 10px; color: #FFFFFF font-family:'Lucida'">{!Promo}</marquee>
</apex:page>
Controller Code:
public class PartnerPromotionBanner {
private final Opportunity opp;
public String showMsg { get; set; }
public boolean Msgid { get; set; }
public PartnerPromotionBanner(ApexPages.StandardController stdController) {
this.opp = (Opportunity)stdController.getRecord();
}
public string getPromo() {
if (opp.Promotion_Code__c == 'FinServ Bundle Promo')
{
return 'The promotion for this opportunity is: ' + opp.Promotion_Code__c;
}
return opp.Promotion_Code__c;
}
}
VF Code:
<apex:page standardController="Opportunity" extensions="PartnerPromotionBanner">
<marquee id="banner" rendered="{!Msgid}" style="box-shadow: 0px 0px 15px black; border-radius: 5px; padding: 10px; background-color: #FF0000; font-weight: bolder; font-size: 16px; margin: 10px; color: #FFFFFF font-family:'Lucida'">{!Promo}</marquee>
</apex:page>
Controller Code:
public class PartnerPromotionBanner {
private final Opportunity opp;
public String showMsg { get; set; }
public boolean Msgid { get; set; }
public PartnerPromotionBanner(ApexPages.StandardController stdController) {
this.opp = (Opportunity)stdController.getRecord();
}
public string getPromo() {
if (opp.Promotion_Code__c == 'FinServ Bundle Promo')
{
return 'The promotion for this opportunity is: ' + opp.Promotion_Code__c;
}
return opp.Promotion_Code__c;
}
}
- John Guthmiller
- December 14, 2018
- Like
- 0
- Continue reading or reply
Trigger Issue : Updating parent object data from child object ?
Hi Team,
We are using trigger for updating count and sum from child to parent object. I am getting issue with one scenario.
Ex :
Parent - A
Parent - B
Child -1.
Scenario : 1
------------------
Child -1 attached with Parent - A, now its updating Parent - A data.
Scenario : 2
---------------------
Child -1 attached with Parent- A, now i am updating the lookup field with Parent - B, Now Parent - B updating with child data but Parent - A data is not erased still it is showing Child - 1 data (sum and count).
Please let me know how can we resolve this issue.
Code :
----------
Thanks,
Lakshmi
We are using trigger for updating count and sum from child to parent object. I am getting issue with one scenario.
Ex :
Parent - A
Parent - B
Child -1.
Scenario : 1
------------------
Child -1 attached with Parent - A, now its updating Parent - A data.
Scenario : 2
---------------------
Child -1 attached with Parent- A, now i am updating the lookup field with Parent - B, Now Parent - B updating with child data but Parent - A data is not erased still it is showing Child - 1 data (sum and count).
Please let me know how can we resolve this issue.
Code :
----------
public static void rollupSumUpdate(Map<Id, child1__c> newRecs, Map<Id, child1__c> oldRecs){ try{ Set<String> parentIds = new Set<String>(); for(Id chIds : newRecs.keySet()){ child1__c tr = newRecs.get(chIds); if(tr.parentId__c != Null){ parentIds.add(tr.parentId__c); System.debug('******If block - Update Method - parentIds : **********'+parentIds); } else { parentIds.add(oldRecs.get(chIds).parentId__c); System.debug('******else block - Update Method - parentIds : **********'+parentIds); } } Map<Id,parent__c> mapToUpdate = new Map<Id,parent__c>(); if(parentIds.size() > 0){ Map<Id,parent__c> fsOppMap = new Map<Id,parent__c>([Select Id,Amount__c,Trade_Count__c from parent__c where Id In :parentIds]); parent__c fsOpp = new parent__c(); List<AggregateResult> ar = [Select parentId__c,Count(Id)tradeCount,Sum(Annual_Recurring_Revenue__c)arrSum,Sum(Non_Recurring_Revenue__c)nrrSum from child1__c where parentId__c In :parentIds Group By parentId__c]; System.debug('--------Aggregate Result : '+ar); If(ar.size() > 0){ for(AggregateResult res : ar){ Id fsId = (Id)res.get('parentId__c'); fsOpp = fsOppMap.get(fsId); fsOpp.Trade_Count__c = (Integer)res.get('tradeCount'); System.debug('---Update Method-----Trade Count : '+fsOpp.Trade_Count__c); Decimal arr = (Decimal)res.get('arrSum'); System.debug('----Update Method----ARR : '+arr); Decimal nrr = (Decimal)res.get('nrrSum'); System.debug('----Update Method----NRR : '+nrr); fsOpp.Amount__c = arr + nrr ; System.debug('----Update Method----Amount : '+fsOpp.Amount__c); mapToUpdate.put(fsOpp.Id,fsOpp); } } else { for(Id ids : parentIds){ fsOpp = new parent__c(id = ids); fsOpp.Trade_Count__c = Null; System.debug('----Update Method--Else Block--Trade Count : '+fsOpp.Trade_Count__c); fsOpp.Amount__c = 0; System.debug('----Update Method--Else Block--Amount : '+fsOpp.Amount__c); mapToUpdate.put(fsOpp.Id,fsOpp); } } } Database.SaveResult[] res = Database.update(mapToUpdate.values(), false); } catch(Exception ex){ System.debug('---Exception caught in Rollup Sum Update Method :'+ex.getLineNumber()); } }Please let me know any one..
Thanks,
Lakshmi
- Lakshmi S
- December 14, 2018
- Like
- 0
- Continue reading or reply
soql injection in dynamic soql query
Hi All,
I have submitted code for security scanning but i got "SOQL injection issue". Please any one help me to resolve this.
Thanks in advance!
I have submitted code for security scanning but i got "SOQL injection issue". Please any one help me to resolve this.
@RemoteAction public static string addrecordtothirdparty(string partId, string AuthToken, string instantURL, string recordIds, string IdAndTag, string MappingJSON) { WrapperClass.Details detailsWrapper = new WrapperClass.Details(); try { map<Id,map<string,string>> recordLstFnl = new map<Id,map<string,string>>(); list<Contact> conRecLst = new list<Contact>(); list<string> recIdsLst = new list<string>(); map < String, Schema.SObjectField > contactFields = Schema.SObjectType.Contact.fields.getMap(); map < String, Schema.SObjectField > accountFields = Schema.SObjectType.Account.fields.getMap(); list<Account> acntLst = new list<Account>(); map<string,Account> acntMap = new map<string,Account>(); map <String, Object> fieldMapping = (map <String, Object>) JSON.deserializeUntyped(MappingJSON); list<string> strLst = new list<string>(); list<string> acntstrLst = new list<string>(); list<string> IdAndTagLst = IdAndTag.split(','); string tag = IdAndTagLst[0]; string Id = IdAndTagLst[1]; recIdsLst = recordIds.split(','); for( Object str : fieldMapping.values() ) { if( str != 'record_type') { strLst.add(string.valueof(str)); } } string fieldLst = string.join(strLst,','); string Query = 'select '+fieldLst+' from Contact where Id =: recIdsLst '; conRecLst = Database.query(Query);It is urgent!!!
Thanks in advance!
- soorya r
- December 14, 2018
- Like
- 0
- Continue reading or reply
visualforce chart won't render
Hey,
I'm trying to create a narrow chart that will show the color status of an account. Data is populated in a related object weekly. Currently, I'm not getting an error, but nothing is rendering. Debug logs show my query is returning the records. I've never used charts before, so it's probably something silly i've missed. Any thoughts?
Page
Controller ext.
I'm trying to create a narrow chart that will show the color status of an account. Data is populated in a related object weekly. Currently, I'm not getting an error, but nothing is rendering. Debug logs show my query is returning the records. I've never used charts before, so it's probably something silly i've missed. Any thoughts?
Page
<apex:page standardcontroller="Account" extensions="ClientHealthExtension"> <apex:chart height="125" width="100%" data="{!trendData}"> <apex:axis type="Numeric" position="bottom" fields="week"/> <apex:axis type="Category" position="left" fields="xName"/> <apex:barSeries orientation="vertical" axis="bottom" xField="week" yField="xName"/> </apex:chart> </apex:page>
Controller ext.
public class ClientHealthExtension { private final Account acct; public Account acctName; public ID acctId; public List<Account> nameList; public ClientHealthExtension (ApexPages.StandardController stdController){ this.acct = (Account) stdController.getRecord(); acctId = acct.Id; nameList = [SELECT Name FROM Account WHERE Id=:acctId limit 1]; if(!nameList.isEmpty()){ acctName = nameList[0]; } } public List<Account_Trend__c> gettrendData(){ List<Account_Trend__c> trends = [SELECT Account_Name__c, Client_Health_Status_Indicator__c, CreatedDate FROM Account_Trend__c WHERE Account_Name__c =:acctName.Name ORDER BY CreatedDate]; system.debug('trends: '+trends); return trends; } // Wrapper class public class trendData { public String xName { get; set; } public String health { get; set; } public date week { get; set; } public ID xId { get; set; } public String xIso { get; set; } public trendData(String xName, String health, date week, ID xId, String xIso) { this.xName = xName; this.health = health; this.week = week; } } }
- Mike 317
- December 10, 2018
- Like
- 0
- Continue reading or reply
My test class is not giving any error & running successfully but while checking code coverage it is giving none
I mentioned my class with respective test class. please let me know where I am doing wrong.
My class is calling in a trigger which fires when my support Request(object) Record is approved by the approver through the standard approval process. when the record is approved the trigger automatically create an Event record. below is the class with test class .
Public class AutoCreateEvent
{
Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
{
List<Event> EventRec = new List<Event>();
RecordType SuppReqRecordType = [SELECT Id
FROM RecordType
WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
LIMIT 1];
for(DealSupportRequest__c ds:dsreq)
{
if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c != oldDsreqMap.get(ds.Id).Is_approved__c) )
{
Event e = new Event();
e.WhatId = ds.Account__c;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = ds.Ownerid;
e.Subject_Custom__c =ds.Purpose__c;
e.Description = ds.OtherPurpose__c;
e.StartDateTime =ds.StartDateTime__c;
e.EndDateTime = ds.EndDateTime__c;
e.LocationCallInInfo__c = ds.CampusLocation__c;
e.Support_Request__c = ds.Id;
EventRec.add(e);
}
}
If(EventRec.size()>0)
Insert EventRec;
}
}
Test class:
@IsTest
public class AutoCreateEvent_Test {
static testmethod void CreateEvent(){
Test.startTest();
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000@amamama.com',
Username = 'puser000@amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
EmployeeNumber='1'
);
insert u;
List<Event> EventRec = new List<Event>();
Account a = new Account(Name='1st Community CU',Membership_Defined__c='Member',Type='Client', ownerid=u.id );
Insert a;
DealSupportRequest__c dsr = new DealSupportRequest__c(Account__c=a.Id,StartDateTime__c=system.now(),EndDateTime__c=system.now().addDays(1),ownerid=a.Ownerid);
Insert dsr;
Event e = new Event();
e.WhatId=a.Id;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = dsr.Ownerid;
// e.Support_Request__c=dsr.Id;
e.StartDateTime =dsr.StartDateTime__c;
e.EndDateTime = dsr.EndDateTime__c;
EventRec.add(e);
insert EventRec;
Test.stopTest() ;
}
}
My class is calling in a trigger which fires when my support Request(object) Record is approved by the approver through the standard approval process. when the record is approved the trigger automatically create an Event record. below is the class with test class .
Public class AutoCreateEvent
{
Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
{
List<Event> EventRec = new List<Event>();
RecordType SuppReqRecordType = [SELECT Id
FROM RecordType
WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
LIMIT 1];
for(DealSupportRequest__c ds:dsreq)
{
if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c != oldDsreqMap.get(ds.Id).Is_approved__c) )
{
Event e = new Event();
e.WhatId = ds.Account__c;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = ds.Ownerid;
e.Subject_Custom__c =ds.Purpose__c;
e.Description = ds.OtherPurpose__c;
e.StartDateTime =ds.StartDateTime__c;
e.EndDateTime = ds.EndDateTime__c;
e.LocationCallInInfo__c = ds.CampusLocation__c;
e.Support_Request__c = ds.Id;
EventRec.add(e);
}
}
If(EventRec.size()>0)
Insert EventRec;
}
}
Test class:
@IsTest
public class AutoCreateEvent_Test {
static testmethod void CreateEvent(){
Test.startTest();
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000@amamama.com',
Username = 'puser000@amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
EmployeeNumber='1'
);
insert u;
List<Event> EventRec = new List<Event>();
Account a = new Account(Name='1st Community CU',Membership_Defined__c='Member',Type='Client', ownerid=u.id );
Insert a;
DealSupportRequest__c dsr = new DealSupportRequest__c(Account__c=a.Id,StartDateTime__c=system.now(),EndDateTime__c=system.now().addDays(1),ownerid=a.Ownerid);
Insert dsr;
Event e = new Event();
e.WhatId=a.Id;
e.Type = 'On-Site at PSCU';
e.Status__c = 'Scheduled';
e.OwnerId = dsr.Ownerid;
// e.Support_Request__c=dsr.Id;
e.StartDateTime =dsr.StartDateTime__c;
e.EndDateTime = dsr.EndDateTime__c;
EventRec.add(e);
insert EventRec;
Test.stopTest() ;
}
}
- subodh chaturvedi 17
- November 29, 2018
- Like
- 0
- Continue reading or reply