• SUCHARITA MONDAL
  • NEWBIE
  • 374 Points
  • Member since 2015


  • Chatter
    Feed
  • 12
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 87
    Replies
Hi All,

Im writing a test class for batch apex that will be scheduled to run on the first of each month.  Were testing it here, but i keep running into this error at line 25 "System.QueryException: List has no rows for assignment to SObject".  I dont know why that list would be blank.  Can anyone advise? thanks/
 
public class TouchSalesDatasTest {
	@isTest
    public static void Test() {
        Map<ID,Sales_Data__c> SDMap = new Map<ID,Sales_Data__c>();
        Account Acc = TestDataFactory.createAccount('TouchSalesDataTest EU ', 'desiredrecordtypeid', null, null, true);
        Account Dist = TestDataFactory.createAccount('TouchSalesDataTest Dist ', 'desiredrecordtypeid', null, null, true);
        for (Integer i = 0; i < 200; i++) {
            Sales_Data__c SD = new Sales_Data__c(End_User__c = Acc.ID,
                                                 Distributor__c = Dist.Id,
                                                 Amount__c = i,
                                                 Quantity__c = i,
                                                 Date__c = System.today().addDays(-25),
                                                 Product__c = 'desiredproductid');
            SDMap.put(SD.Id,SD);
        }
        insert SDMap.values();
        
        Decimal expectedValue = System.today().addDays(-25).daysBetween(System.today())/31;
        
        Test.startTest();
        TouchSalesDatas t = new TouchSalesDatas();
        Database.executeBatch(t);
        Test.stopTest();
        
        Sales_Data__c UpdatedTest = [SELECT ID,Name,Months_Ago__c FROM Sales_Data__c WHERE ID IN :SDMap.keySet() Limit 1];
        System.assertEquals(Math.round(expectedValue), UpdatedTest.Months_Ago__c);
    }
}

 
I entered a contact in the Name and Attendees field and now I want to be able to make sure that if I deleted a Contact from the name field it gets removed from the Invitees field and vise versa. To make this happen, I did an IF statement to check if the value of isParent == false OR isInvitee == false. This works for the isParent == false, but it doesn't seem to catch it if the isInvitee == false. Can anyone help me on why 'OR' is not working and have any suggestions on how to make this work? Thanks.

if (trigger.isUpdate){ List<EventRelation> erLst = [SELECT EventId, RelationId, isParent, isInvitee FROM EventRelation where EventId IN :sEvents ]; for(EventRelation sObj: erLst ){ if (sObj.IsParent == false || sObj.IsInvitee == false ){ delete sObj; } else{ sObj.IsParent = true; sObj.IsInvitee = true; UpdatedLst.add(sObj); update UpdatedLst; } } }
  • May 09, 2020
  • Like
  • 0
Hi all - we don't use accounts in my installation, yet the reports all need an Account or the Contacts don't show up.

It is easy enough to update all existing contacts with AcctID=Individual, but how can I set it up so any new Contact has default of Individual account?

Please don't say "make Account required field and make them pick Individual".. I want it to default.

Thank you!
Hello, we have a trigger on Lead that creates a Contact based on 2 fields from the Lead . After the Contact is inserted, we want to turn the Lead field that contains the name of the Contact to turn into a hyperlink with a link to that Contact record. I built a trigger, but it is not working, and I am not sure why not. Can someone please help. Here is the trigger:

trigger ContactsTrigger on Contact (after insert) {
     // add mobilephone to set and assign id variable
    Set<String> contactNumSet = new Set<String>();
    Id newConId;
    for (contact c : trigger.new){
        if (c.mobilephone != null){
            newConId = c.id;
            contactNumSet.add(c.mobilephone);
        }
    }
 //query related lead   
 List<Lead> refsToInvestigate = new List<Lead>();       
 List<Lead> refsToUpdate = new List<Lead>();  
 String nok1;
    refsToInvestigate = [select emergency_contact_phone__c from Lead where emergency_contact_phone__c = :contactNumSet];    
        for (Lead ref : refsToInvestigate){
                nok1 = ref.NextofKin__c; }
    
    for (Lead refer : refsToInvestigate){
                refer.nextofkin__c =  '<a href=https://centers--partial.lightning.force.com/'+newConId+'>'+nok1+ '</a>' ;
        refsToUpdate.add(refer);  } 
         update refsToUpdate;

}
global class AgeUpdate implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext bc)

    {

    return Database.getQueryLocator([SELECT dateOfBirth__c,Id,Status FROM Lead WHERE Status = 'Unqualified' AND dateOfBirth__c = TODAY]);

   }

     global void execute(Database.BatchableContext bc, List<Lead> scope)

   {

      for(Lead l: scope)

        {

            l.Age__c = l.Current_Age__c;

        }

            update scope;
       
    }
    
     global void finish(Database.BatchableContext bc)
     {}

}
 
Hello,

I have created an apex class to count the number of textpost in a case but my code doesn't not iterate...
Could someone help?
Thanks
public class FeedItemTriggerHandler {
    public static void countFeedItem(List<FeedItem> lstFeed){ 
        set<id> relatedCasesIds = new set<id>();
        for(FeedItem fd : lstFeed) {
            if (fd.type =='TextPost')relatedCasesIds.add(fd.ParentId);
        }
        Map<Id, case> relatedCases = new Map<Id, case> ([Select id, caseNumber,All_Users_Feed_Count__c FROM case where id in: relatedCasesIds]);
       	List<case> casesToUpdate = new List<case>(); 
        
        integer count = 0;
        for(case c:relatedCases.values()) {
           for(FeedItem fd : lstFeed) {
               if (fd.type =='TextPost' && fd.Visibility =='AllUsers' && fd.ParentId == c.id) {
                   count+=1;
                   
               } 
       		 } 
            c.All_Users_Feed_Count__c = count;
            count = 0;
            casesToUpdate.add(c);
              
        }
        if(casesToUpdate.size() > 0) update casesToUpdate; 
    }
}

 
Hi guys,

I've created a custom screen flow and I want to add it to a community page, launched from a custom button on the Homepage. 
The flow guides users through creating a case. I am getting the following error when I add the component to the page: "Action failed: c:CustomCaseCommunityComponent$controller$init [flowData is not defined]"

This is my component. 

<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,forceCommunity:availableForAllPageTypes,force:hasRecordId,force:lightningQuickActionWithoutHeader" access="global">

    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    <lightning:flow aura:id="flowData"/>
    
</aura:component>


({
init : function (component) {
var flow = component.find(flowData);
flow.startFlow(CaseFlow);
},
})
Hello All,

I am trying to write a trigger to update a parent object field when its child record is added/updated. I am quite new to Salesforce Apex and tried to read a few posts in the forum and still could not get it working. Any thoughts on this is appreciated. Thank you!

Example:
Parent Object: Sales_Event__c
Field to update: Cost_Item_Update__c
Child Object: Sales_Event_Cost_Item__c (Master-Detail(Sales Event))
Sales_Event_ID__c = Sales_Event__r.Id (I’m not too sure if there is proper way to get Sales_Event ID in Sales_Event_Cost_Item__c so I create a new formula field here which I think may not be necessary though..)
Fields to be CONCATENATED: Cost_Items__c and  Quantity__c
So I would like to get below in my Parent Object:
e.g. Sales Event A has 2 Cost items,
Cost_Item_Update__c = “Cost_Item one (Quantity__c), Cost_Item two (Quantity__c)”
But my Cost_Item_Update__c  even can’t get the Cost_Items__c (Cost_Item one, Cost_Item two iteration) right.. I am wondering if I map the objects incorrectly...
trigger TestSalesEventCostItemUpdate on Sales_Event_Cost_Item__c (after insert, after delete, after update) {

    list<id> parentIDstoUpdate = new list<id>();
    if(Trigger.isInsert||Trigger.isAfter||Trigger.isDelete ){
            for (Sales_Event_Cost_Item__c co : Trigger.new) {
                parentIDstoUpdate.add(co.Sales_Event__c);       
            } 
    }

    map<id,string>  mapParentIdtoString = new Map<ID,String>();
    string str;

    for (Sales_Event_Cost_Item__c co: [SELECT Sales_Event_ID__c, Cost_Items__c from Sales_Event_Cost_Item__c WHERE Sales_Event_ID__c =:parentIDstoUpdate ]){
        if(mapParentIdtoString.containsKey(co.Sales_Event_ID__c)){
            str = mapParentIdtoString.get(co.Sales_Event_ID__c);
            str = str + ';' + co.Cost_Items__c;  
            mapParentIdtoString.put(co.Sales_Event_ID__c,str);
        }else{
            mapParentIdtoString.put(co.Sales_Event_ID__c,co.Cost_Items__c);
        }
    }
    
    list<Sales_Event__c> recordstoUpdate = new list<Sales_Event__c>();
    for (Sales_Event__c p: [SELECT ID, Cost_Item_Update__c FROM Sales_Event__c WHERE id =:recordstoUpdate ]){ 
        p.Cost_Item_Update__c = mapParentIdtoString.get(p.id);
        recordstoUpdate.add(p);
    }

    if (recordstoUpdate != null && recordstoUpdate.size()>0){
        update recordstoUpdate;
    }
}
Good morning all. I have a trigger that creates new records related to opportunities.

I have everything working but my loop and i am stuck. I am very new to coding and would really appreciate some assistance.

This iwhat I have so far and everything works...except....
                            //while loop create record process                     	
              				decimal counter = 0;
              				while (counter < opportunityList.Quarters_Spanned_op__c)
                			{
                                
                			Open_Quarter__c oq           = new Open_Quarter__C();
                			Quarter_Number__c qn		 = new Quarter_Number__c();
                			oq.Amount_Per_Quarter_oq__c  = opportunityList.Amount_per_Quarter_op__c;
                			oq.Close_Date_oq__c          = opportunityList.CloseDate;
                			oq.Name            			 = opportunityList.Quarter_Created_op__c;
                			oq.Opportunity_Name_oq__c    = opportunityList.Id;
                			oq.Quarters_Spanned_oq__c    = opportunityList.Quarters_Spanned_op__c;

							createOpenQuarter.add(oq);
                			counter++;
          					
                            }//end while loop                                             
When I create each new record I need it to populate a field in that record with escalating quarter names. Right now it creates the right nimber of records but they all have the same quarter name in them which the starting quarter of the opp.

Now I have four custom formula fields in the opp that I can use.
  • One with the name for the quarter when the opp was created in this format: 2019-Q1 etc
  • One with the year the opp was started as a number "2019"
  • One with the starting quarter as a number (1-4)
  • One with the number of quarters the opp spanse based upon the created and close dates also expressed as a number.
I was told that I can loop the quarters within the year so that if an opp ovewrlaps years i can increment the rear number and reset the quarter to one and continue the loop for the same number of times as the quarters spanned (I already have that part)

But the rest is all very new to me. How do I build these nested loops with an output for each iteration that looks like this "2019-Q1" that I can use in creating my new records.

I am really stuck here so any help at all will be greatly appreciated.
Best regards,
Steve
 
Hi All.  Long Time admin but Very new to apex and developing.  I have a child object for accounts "sales data" which essentially is just transactional line items of purchases (related to the distributor, and the account).  So now I want to have a trigger on the sales data object that takes the sum of the amt in last 45 days by account then by distributor.  So that i can update the primary & secondary relationship on the account to indicate the distributor that is doing the most and second most sales for that account respectively.  below is what i have so far.  Please take a look and help out with getting thsi to run, and also how do i bulkify this??  Thanks guys!
 
trigger DistributorIDs on Sales_data__c (after insert, after update) {
       Date AfterDate = Date.today().addDays(-45);
       List <Account> AccountsList = new List<Account>();
    For (Sales_data__c Sd: Trigger.new) {
        AccountsList.add(Sd.End_user__r);
    } 
       Set<Account> DeDupSet = new Set<Account>();
       List<Account> DeDupAccounts = new List<Account>();
       DeDupSet.addAll(AccountsList);
       DeDupAccounts.addAll(DeDupSet);
    For (Account Acc: DeDupAccounts) {
        List<AggregateResult> Distributors = [SELECT Distributor__c, SUM(Amount__c) FROM Sales_Data__c 
                                    WHERE Date__c >= :AfterDate AND End_user__c = :Acc.Id
                                    GROUP BY Distributor__c ORDER BY SUM(Amount__c) LIMIT 2];
        ID FirstPosition = (ID)Distributors[0].get('expr0');
        ID SecondPosition = (ID)Distributors[1].get('expr1');
        Acc.Acct_Primary_Distributor__c = FirstPosition;
        Acc.Acct_Secondary_Distributor__c = SecondPosition;
    }
    update DeDupAccounts;
}

 
Hi everybody,

I am trying to access subquery field which is in a list.
ex: List<Account> newList = new List<Account>([Select Name,phone,(Select name,phone from Contacts)  from Account]);
In the above code the values can be accessed for account by using "newList.Name". But when i try to access contacts of that account i.e.(newList.Contacts.name).It is giving me error.

So,is there any way to access the subquery(Contacts) field values.

Thanks.
I have a trigger that creates records related the opportunity that fires the trigger.

I need to add a step that will delete any of these existing records if the close date is updated.

Each opp will have one or more of these related records.

How do i identify / list these records and delete them?

I think I have my conditionals all set up the way I need them. i just need to identify them and delete them.

Any suggestions out there?
Steve

Hi All,
Did anyone faced such error as below:

INVALID_TYPE: sObject type 'CaseComment' is not supported in describeCompactLayouts.

I'm getting above error in Lightning, while clicking on Case comment on Case record.

P.S. Any help/direction is appreciated.

Thanks,
Sucharita

 

here is the controller code..

({
    doClose : function(component, event, helper) {
        var recid = component.get("v.recordId");
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
            "url": "/"+recid
        });
        urlEvent.fire();
        
    },
    handleSubmit : function(component, event, helper) {
        component.find("recordEditForm").submit();
        
        var payload = event.getParams().response;
        debugger;
        console.log(payload.id);
    }
})

Hey..

We want to track the email and links that how many time email is opened and links are clicked and that to by using tracking pixel.
Could anybody help that how can we create tracking pixel in Salesforce it is as same as salesforce embeds when email is fired using email templates and tracks are updated which can be shown at HTML Email Status related list.

Thanks..

I'm sure this is a very simple problem, but I'm still fairly new to saleforce and can't seem to find the solution. So I'm trying to compair new records when inserted with all existing records to ensure that the last name values are unique otherwise it won't post the new record. I'm sure that I will have to put this in a before insert trigger but I can seem to figure out how exactly to run the compairson. 

I'm getting the following error when I run a debug log on an update to an APEX Class, FATAL_ERROR|System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account.Account_Owner_For_Jiva__c
The field is a formula text field that brings in the account owners email address. We use this to pass the email to our external system. I added the field the existing APEX Class like this:

 //json container for Account
    private class AccountCompany{
        private Id SalesforceID; //required
        private String Name; //required
        private String AccountOwner; //required
        private String PrimaryCountry; //required
        //private String EAGRelationshipID;
        private String UnicodeName;
        private String IndustrySectorID;
        private String ManufacturingTypeID;
       

        public AccountCompany(Sobject record)
        {
            Account account = (Account)record;

            this.SalesforceID = account.Id;
            this.Name = account.Name;
            this.PrimaryCountry = account.Primary_Country__c;
            this.AccountOwner = account.Account_Owner_For_Jiva__c;
            //this.EAGRelationshipID = EAGRelationshipID; //no related field in salesforce
            this.UnicodeName = account.Account_Name_Unicode__c;
            this.IndustrySectorID = account.Industry_Sector_ID__c;
            this.ManufacturingTypeID = account.Manufacturing_Type_ID__c;
            
        }
    }


The updated Class saves with no errors, but was not communicating correctly which is when I ran the code debug log. I saw where I need to add it to the query, but I don't see anything else in the class that includes the existing fields.

 

Hi All,

Im writing a test class for batch apex that will be scheduled to run on the first of each month.  Were testing it here, but i keep running into this error at line 25 "System.QueryException: List has no rows for assignment to SObject".  I dont know why that list would be blank.  Can anyone advise? thanks/
 
public class TouchSalesDatasTest {
	@isTest
    public static void Test() {
        Map<ID,Sales_Data__c> SDMap = new Map<ID,Sales_Data__c>();
        Account Acc = TestDataFactory.createAccount('TouchSalesDataTest EU ', 'desiredrecordtypeid', null, null, true);
        Account Dist = TestDataFactory.createAccount('TouchSalesDataTest Dist ', 'desiredrecordtypeid', null, null, true);
        for (Integer i = 0; i < 200; i++) {
            Sales_Data__c SD = new Sales_Data__c(End_User__c = Acc.ID,
                                                 Distributor__c = Dist.Id,
                                                 Amount__c = i,
                                                 Quantity__c = i,
                                                 Date__c = System.today().addDays(-25),
                                                 Product__c = 'desiredproductid');
            SDMap.put(SD.Id,SD);
        }
        insert SDMap.values();
        
        Decimal expectedValue = System.today().addDays(-25).daysBetween(System.today())/31;
        
        Test.startTest();
        TouchSalesDatas t = new TouchSalesDatas();
        Database.executeBatch(t);
        Test.stopTest();
        
        Sales_Data__c UpdatedTest = [SELECT ID,Name,Months_Ago__c FROM Sales_Data__c WHERE ID IN :SDMap.keySet() Limit 1];
        System.assertEquals(Math.round(expectedValue), UpdatedTest.Months_Ago__c);
    }
}

 

Hello, I have a requirement to create a trigger to not allow users to edit records if they are not the creator OR if they are not the owner. Owner can be a simple user or a QUEUE.
 

This is what I wrote until now... my code is not working.

 

trigger permissionToEditAdminTasks on SIG_Administrative_Task__c (after update) {
  
      //fetch the id of the creator of the record <start>
           Set<String> ownerIds = new Set<String>();
        for (SIG_Administrative_Task__c record : Trigger.New) {
            ownerIds.add(record.OwnerId);
             
        }
        
       
        
      // <end>
        
        List<Group> groups = [SELECT Id, (SELECT Id, UserOrGroupId FROM GroupMembers) FROM Group WHERE Id =: ownerIds];
        System.debug('####groups' + groups);    
        
          
        Map<String, Set<String>> memberIdsByGroupId = new Map<String, Set<String>>();
        
        //fetch the id's of the users from the the current owner queue  <start>
        for (Group groupRec : groups) {
            Set<String> memberIds = new Set<String>();
            for (GroupMember member : groupRec.GroupMembers) {
                memberIds.add(member.UserOrGroupId);
            }
               System.debug('####memberIds  ' + memberIds );   
        }
        // <end>
       

        for (SIG_Administrative_Task__c record : Trigger.New) {
            if (memberIdsByGroupId.get(record.OwnerId) != null && memberIdsByGroupId.get(record.OwnerId).contains(UserInfo.getUserId()))
            {
             
            }else{
                 record.addError('You have not permission for editing this record');
                  System.debug('record.OwnerId' + record.OwnerId);
            }
        }
    

}
I cannot edit the record no matter what, I don't know what is wrong in my code.. please help.
Spring 2020 release notes says that we can assign Tasks to queue.
I am able to assign task to any queue from task screen but it doesn't our problem of assigning task to queue using trigger or from process builder.

We have a requirement to create a new task and assigned to queue whenever any new case is created ?How can I achieve that?

Thanks,
Gaurav Seth
Hey everyone! 
I'm an admin who is trying to move into coding and to translate what I've learned in Visual Flow into code to help me be able to tackle problems I can't resolve in VF.
I could do this in VF, but I'm using it as an example to try to translate what I know, and I'm running into some issues.

Greatly appreciate any help anyone can provide to help me on my first trigger and class.
Class
public class ServiceOrderClass {
    public static void getServiceForOrder(List<Service__c> servicefromTrigger)
 { 
     List<Order> relatedOrder= new List<Order>();
     Order foundorder = new Order();
     for (Service__c svc:servicefromTrigger)  
    {
        if (svc.First_Service_Order__c!=NULL && svc.Service_Order__c=='') 
        {
            relatedOrder=[Select Id, SAP_DocNum__c From Order WHERE SAP_DocNum__c=:svc.First_Service_Order__c]; 
            {System.debug('this is the related order record '+relatedOrder);}
            foundorder=relatedOrder[0];
           svc.Service_Order__c= foundorder.id;
        }
    }
     update servicefromTrigger;
  }
}

Trigger
trigger servicefromTrigger on Service__c (before update) 
{
 ServiceOrderClass.getServiceForOrder(trigger.new);
}
The error message I'm receiving when I try to update a service record is: servicefromTrigger: execution of BeforeUpdate cuased by System.StringException: Invalid Id : Class.ServiceOrderClass.getServiceforOrder: line 8, column 1 Trigger.servicefromTrigger: line 3, column 1

What I'm trying to do is pass the Service__c.Id from the Trigger to the list in the Class, check to see if the First_Service_Order__c field is populated and the Service_Order__c field is NULL, and if those conditions are met, find the order that hasw the same 6 digit order number as the First_Service_Order__c field and write that order to a lookup field Service__c.Service_Order__c

Thanks again for any help.
Frances

I created all the custom fields and validation rules and cross checked with this Forum answers , but still am facing below error! 

Can you guide me to trace what is missing to complete this challenge
Process Automation Specialist challenge #2

Hi all,  I'm new to Salesforce Development.
I need to write a trigger on task object .
Requirement is whenever Opportunity Date field changes in opportunity it should populate on Task object Opportunity date field .any help would be appreciated
I entered a contact in the Name and Attendees field and now I want to be able to make sure that if I deleted a Contact from the name field it gets removed from the Invitees field and vise versa. To make this happen, I did an IF statement to check if the value of isParent == false OR isInvitee == false. This works for the isParent == false, but it doesn't seem to catch it if the isInvitee == false. Can anyone help me on why 'OR' is not working and have any suggestions on how to make this work? Thanks.

if (trigger.isUpdate){ List<EventRelation> erLst = [SELECT EventId, RelationId, isParent, isInvitee FROM EventRelation where EventId IN :sEvents ]; for(EventRelation sObj: erLst ){ if (sObj.IsParent == false || sObj.IsInvitee == false ){ delete sObj; } else{ sObj.IsParent = true; sObj.IsInvitee = true; UpdatedLst.add(sObj); update UpdatedLst; } } }
  • May 09, 2020
  • Like
  • 0
Future methods are typically used for:
Callouts to external Web services. If you are making callouts from a trigger or after performing a DML operation, you must use a future or queueable method. A callout in a trigger would hold the database connection open for the lifetime of the callout and that is a "no-no" in a multitenant environment.
 
Users need to identify all the Accounts which have one or more Opportunity children for which Status='Won'  and also have one or more Opportunity children for which Status='Lost' . A report would be ideal but any easy solution would be nice. Of course I can write batchable Apex to traverse all the data but there must be a simpler way.  
I have a list button for the Product2 object in my org that redirects to a VisualForce page. This VisualForce page displays the product name and description of all the product records that were selected in list view. That works fine, and I have the page rendered as a PDF using the renderAs tag.
renderAs="pdf"
My problem occurs when I go to download the PDF using the provided button in the browser. When I do this, the PDF is downloaded but the content shows the name and description of every single product record, not just the ones I selected.
How can I get the downloaded PDF to show only the selected records?
Am I missing something? I feel like this may be some sort of caching issue but I really don't know honestly.

Here is my VF code for reference:
<apex:page standardController="Product2" recordSetVar="prods" showHeader="false" extensions="CatalogueGenerationExt" renderAs="pdf">
    <!-- Static resource style sheet -->
    <apex:stylesheet value="{!URLFOR($Resource.cataloguegenstyle)}"/>

    <div class="main-containter" style="background-image:url('{!URLFOR($Resource.watermarkfull)}');">
        <div class="head">
            <div class="genTitle">
                Custom Catalog Generation (<apex:outputText value="{0, date,MMMM d',' yyyy - HH:mm 'GMT'}"><apex:param value="{!NOW()}"/></apex:outputText>)
            </div>
        </div>
        <div>
            <apex:repeat value="{!prods}" var="q">
                <div class="product-inner">
                    <div class="prod-title">
                        <h3>
                            <apex:outputField value="{!q.Name}"/>
                        </h3>
                    </div>
                    <div class="client-desc-cont">
                        <apex:outputField value="{!q.Client_Description__c}"/>
                        <apex:outputText rendered="{!q.Client_Description__c=Null}">&lt;No Description available&gt;</apex:outputText>
                    </div>
                </div>
            </apex:repeat>
        </div>
    </div>
</apex:page>

 
  • May 08, 2020
  • Like
  • 0

Hello All,

Hope everyone is safe and healthy.

I have a field on the Opportunity object called NetworkPath__c which composed of Account and Opportunity fields.

When the Opportunity is created or updated or the Account is updated NetworkPath__c may need to be updated. All is good except when the Opportunity Stage is "Closed" where a Validation Rule (VR) presents the User with an error message "You cannot update a Closed Opportunity". This by design.

I need a way to allow the user to update Opportunity NetworkPath__c when certain Opportunity or Account fields are changed. I don't want allow the User update to complete Opportunity, only the fields that compose NetworkPath__c.

I am thinking a pagelayout limited to the fields that compose NetworkPath__c, but how do I get past the VR that presents the User with the error message.

How about this idea...add a field to the User Profile that grants certain individuals the ability to update the fields that compose NetworkPath__c, then modify the VR to check User Profile for new field.

Doe's this make any sense? Or is there a better way to do this? I am open to all ideas.

Thanks for reading my caffine driven rant.

Cheers!

Robert

I have written the below test class to add list of partner leads with record type as Partner Lead registartion on account page. Can you help me with the code
@isTest
public class PartnerLeadControllerTestClass {
    
    static testMethod void leadscontroller()
    {        
        Account myaccount = new Account (name='Test');
        insert myaccount;
        
        PageReference pageRef = Page.PartnerleadList;
        pageRef.getparameters().put('recordId', myaccount.Id);  
        Test.setCurrentPage(pageRef);
        
        Apexpages.StandardController sc = new Apexpages.StandardController(myaccount);
        PartnerLeadController partlead = new PartnerLeadController(sc);   
        partlead.getlead();
        partlead.initlead();
    }
   
}

Apex class

public  class PartnerLeadController {
    public Account acc{get;set;}
    public List<Lead> LeadList{get;set;}  
    Set<String> UserContactId = new Set<String>(); 
    public PartnerLeadController(ApexPages.StandardController stdController) {
        LeadList = new List<Lead>();
        this.acc = (Account)stdController.getRecord();
        list<contact> conlist=[Select Id From Contact WHERE AccountId =:acc.Id]; 
        for(User u: [Select Id, Name, ContactId FROM USER WHERE isactive=TRUE AND ContactId In:conlist]){
            UserContactId.add(u.Id);
        }
        LeadList = [select id,Name,CreatedDate,Company,OwnerId,Owner.Name,LeadSource,MAU__c,Estimated_Opportunity_Deal__c,recordType.Name,CRM_User__r.Name,CRM_User__r.Id,CRM_User__c, Status, Account__c,LastName, Account__r.id,Account__r.OwnerId
                    from Lead 
                    where    CRM_User__c !=null And Account__c=: acc.Id AND LeadSource='Partner' AND recordType.Name = 'Partner Lead Registration' ];
    }
}

VF Page

<apex:page standardController="Account" extensions="PartnerLeadController" lightningStylesheets="true" sidebar="false"  >

    <apex:form >
       

        <apex:pageBlock rendered="true" >
            <apex:outputPanel layout="block" styleClass="container">
            <apex:pageBlockTable value="{!LeadList}" var="ld" width="100" >
               
                          
            <apex:column >
                <apex:outputLink value="/{!ld.Owner}" target="_top">{!ld.Owner.Name}</apex:outputLink>
                <apex:facet name="header">Owner Name</apex:facet>
            </apex:column>/> 
                
                 <apex:column ><apex:outputField value="{!ld.Name}" />
                <apex:facet name="header">Lead Name</apex:facet>
            </apex:column>
            <apex:column ><apex:outputField value="{!ld.Status}" />
                <apex:facet name="header">Status</apex:facet>
            </apex:column> 
                <apex:column ><apex:outputField value="{!ld.Company}" />
                <apex:facet name="header">Company</apex:facet>
            </apex:column> 
                 <apex:column ><apex:outputField value="{!ld.MAU__c}" />
                <apex:facet name="header">MAU</apex:facet>
            </apex:column> 
                <apex:column ><apex:outputField value="{!ld.Estimated_Opportunity_Deal__c}" />
                <apex:facet name="header">Estimated Opportunity Deal</apex:facet>
            </apex:column> 
                
            <apex:column ><apex:outputField value="{!ld.CreatedDate}" />
                <apex:facet name="header">CreatedDate</apex:facet>
         
            </apex:column> 
            </apex:pageBlockTable>
                </apex:outputPanel>
        </apex:pageBlock>  
      
    </apex:form>
</apex:page>

User-added image
Hi everyone,

Currently I have a trigger which will copy values from related list and I also have a custom lightning component which will display these values. I have a requirement to automatically refresh this lightning component whenever values are updated by trgger at the backend. Any suggestion on how to achieve this?

Note: I have tried with recordupdated functionality from force :recordData, but its not working since I want the component to be refreshed when  record is updated at the backend and recordupdated does not support this functionality.
Hi all !
I'm having problems doing this. I need to save the reponse of this API call as Contacts in Salesforce but I can't figure it out.
 
public class GetClient {
    public List<Object> getClient(String clientId){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://api.disputeprocess.com/api/v1/clients?clientId=' + clientId);
        request.setMethod('GET');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setHeader('api_key', 'xxxx');
        request.setHeader('api_token', 'xxxx');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200 & response.getbody() != null & response.getbody() != '{}') {
            // Deserialize the JSON string into collections
    		Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            system.debug('result ' + result);
            
         
          
        }
        else{
            system.debug('Error making the callout');
        }
        
        return null;
    }
}

The result variable looks like this:
 
{clients=({Customer_FolderId=3, Customer_Secondary_FolderId=0, Customer_WorkflowId=31, Name=Whatever}

I'm stuck here !

Requirement is to connect to this API sending it a clientId and if the client ID exists store the client as a Contact in SF.

Any help would be much apreaciated
Hi Guys,
I need urgent help . I am deserializing callout response into list<object> which looks like below:
(
{
DealerSelected=true,
address={country=AU, postCode=2154, state=NSW, streetAddress=2 Victoria Ave, suburb=CASTLE HILL},
ealerCode=36333, dealerName=Castle Hill Toyota, 
lastUpdated=2019-11-25, latitude=-33.7345000, localityName=NSW, longitude=150.9810610, sapBranchCode=36333
},
)
i want to iterate over it and get attributes for but unable to read 
using dot notation. 

Below is code :



global class DealerSearchController {
 // Callout method
    @AuraEnabled
    public static ResponseWrapper getDealerList(String SearchString){
    //public static List<object>  getDealerList(String SearchString){
    system.debug('SearchString '+SearchString);  
    ResponseWrapper wr=new ResponseWrapper();         
    Http http=new Http();
    HttpRequest req= new HttpRequest();
    req.setMethod('GET');     
    String endpoint ='URL';
     req.setEndpoint(endpoint);    
     
    HttpResponse res=http.send(req);
    system.debug('Response '+res.getBody());
    List<object> DealerList;    
    if (res.getStatusCode()== 200){ 
        
    
    system.debug('body '+json.deserializeUntyped(res.getBody())) ; 
    Map<String,Object>DeserializedResponse=(Map<String,Object>)json.deserializeUntyped(res.getBody()); 
          
    DealerList= (List<object>) DeserializedResponse.get('locations');    
    system.debug('deserializedResponse '+DeserializedResponse);
    system.debug('Locations '+DealerList);
    wr.DealerList=DealerList; 

}

return wr;

    
    }    
   
 // other method  
    @AuraEnabled
public static void addSelectedDealer(List<Object>selectedDealers,String AccountId){
    //Map<String,Object>obj=New Map<String,Object>(selectedDealers);  
    //Map<String,Object>obj=(Map<String,Object>)selectedDealers;
  //iterating over selectedDealers
    for (object s : selectedDealers){      
    system.debug('record '+s); 
    //system.debug('abc '+s.dealerCode);     //throwing variable doent exist        
    }
    
    }

Can someone help how convert into list<object> into map to get object attributes?

Thanks
Hi all - we don't use accounts in my installation, yet the reports all need an Account or the Contacts don't show up.

It is easy enough to update all existing contacts with AcctID=Individual, but how can I set it up so any new Contact has default of Individual account?

Please don't say "make Account required field and make them pick Individual".. I want it to default.

Thank you!