• Thiyagarajan Selvaraj (SFDC Developer)
  • NEWBIE
  • 310 Points
  • Member since 2015
  • Xactium

  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 38
    Replies
Ultimate goal:  I need to end up with a list of 100 Contacts based on two other related objects and certain criteria.  
Background:  The Account object is related to two other objects Contact (lookup, 1 Account can have many Contacts) and I have another object, a custom object, BD__c, with a master detail relationship to the Account object (1 Account can have many BD__c's).   

To start with, I return a list of these BD__c and I want to order them by Opportunity_Amount__c (descending):

BD__c record #1 Opportunity_Amount__c = $100,000.
BD__c record #2 Opportunity_Amount__c = $50,000.
BD__c record #3 Opportunity_Amount__c = $20,000.
BD__c record #4 Opportunity_Amount__c = $0.

Problem to solve:  Since each BD__c is associated to an Account I want the contacts from the associated account from BD record #1, record #2, record #3 (and so forth) until the total # of contacts reaches 100. In other words I want the first 100 contacts associated with accounts related to the BD__c records who have the highest Opportunity_Amount__c.

So far the code I have is:  

Set<Id> setOfBDIds = new Set<Id>();
for (BD__c bbb : [SELECT b.Account__r.Id  FROM BD__c WHERE Opportunity_Amount__c > 0 ORDER BY Opportunity_Amount__c DESC]) 
{
    setOfBDIds.add(bbb.Account__r.Id);
}
List<Contacts> contacts = [SELECT AccountId, Name FROM Contact WHERE AccountId IN =: setOfBDIds LIMIT 100];

The problem is that, with this structure, the contacts in the list won't necessarily be from the BD__c/Accounts who have the highest Opportunity_Amount__c - they can be from any account.

I thought about trying this using SOQL but according to this:  https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_limits.htm (https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_limits.htm" target="_blank)

"In each specified relationship, only one level of parent-to-child relationship can be specified in a query"

Any thoughts on how this can be acheived? 

Thanks in advance!
Hi, I tried reading up on static boolean variables and tried using them with not much success. Can somebody help how I can prevent recursive triggering in the below example? Many thanks!

First Trigger updates Invoice a dollar value equal to the sum of the dollar value from Permits which have a matching Invoice number. As below:

trigger InvoiceAmountUpdate on Permit__c (after update) {

for(Permit__c obj : trigger.new)
{
    List<Permit__c> permit = [select Total1__c from Permit__c p where p.Invoice_Num__c = :obj.Invoice_Num__c];

    decimal sum = 0;
    for (Permit__c p : permit) {sum = sum + p.Total1__c;}
    List<bb_Invoice__c> invoice = [select Invoice_Amount__c from bb_Invoice__c i where i.id = :obj.Invoice_Num__c];
    
for (bb_Invoice__c i : invoice) {
        i.Invoice_Amount__c = sum;
        update i;
    }
}
}

Second Trigger updates payment amount on Permits when the full invoice value is paid. However, with each update on Permit, the first trigger is called ending in a recursive pattern

trigger PaymentStatusUpdate on bb_Invoice__c (before update) {

for(bb_Invoice__c obj : trigger.new)
{
   if (obj.Paid_Amount__c>=obj.Invoice_Amount__c) {
    obj.Payment_Status__c = 'Paid';
   
List<Permit__c> permit = [select Total1__c,Paid__c from Permit__c p where p.Invoice_Num__c = :obj.id];

    for (Permit__c p : permit) {
        p.Paid__c = p.Total1__c;
        update p;
    }
    } 

    else if (obj.Paid_Amount__c>0) {
    if (obj.Paid_Amount__c<obj.Invoice_Amount__c) {
    obj.Payment_Status__c = 'Partially Paid';
    } 
    }
}
Hi,

The current scenario is that a custom Opportunity Field (Cfield__c) needs to be required when the Opportunity.Amount >= $200,000 and Stage is A,B,C, and E. Through the UI, a red bar needs to appear next to the field to indicate it is required when it meets the criteria above, but needs to be "grayed out" (not visible) if the Amount < $200,000.

How may i use an apex trigger or validation rule to do this? If this cannot be done with Apex Trigger or validation rule, what other method may I use? Ideally I would like to stay away from overriding the Opportunity Edit page with a VF page. 

I thought i could do this with Salesforce Flow, but I am new to that and it seems cumbersome to get that to work.

Requirements:
  • Opportunity.Amount >= $200,000
  • Stage = A,B,C, and E.
  • Cfield__c is required (dropdown with Yes or No as values)
  • Red bar appears next to Cfield__c to indicate it is required.
when I run the block of ‘static’ code in execute anonymous, it throws an error “only top-level methods in the class are allowed to be declared as static”. I tried my code also: there also same issue.
 public StringArrayTest {  public static void generateStringArray() {}  }
 Can anyone help on this?

thank you.
I have written a trigger to send email. Whenever the trigger is fired i am getting equal no of mails which is equal to no of records retrieved.

Ex - If i am getting 3 records, three times i am receiving email. Can anybody tell me where i am going wrong . I want a single email to be fired.

trigger taskEmail on Project__c (after update ) {
    set<String> projName = new set<String>();
    list<Task__c> listTask = new list<Task__c>();
    
    for(Project__c pro : Trigger.new) {
        projName.add(pro.Name);
    }
    
    listTask = [SELECT Id,Project_Approval__c,Project_Name__c,Status__c,Task_Executioner__c FROM Task__c WHERE Project_Name__c IN : projName];
    system.debug('11111' + listTask.size());
    EmailTemplate et=[Select id from EmailTemplate where name='Multiple Tasks'];
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
    Set<Task__c> setTaskName = new Set<Task__c>();
    setTaskName.addAll(listTask);
    List<Task__c> finalTsk = new List<Task__c>();
    finalTsk.addAll(setTaskName);
    
    
    if(listTask.size() > 0) {
    system.debug('222222' + listTask.size());
        for(Task__c con : finalTsk) {
        system.debug('33333  enter for ');       
        if(con.Project_Approval__c =='Approved' && con.Status__c == 'Open'){
            system.debug('444   enter if inside for '); 
            //String userEmail = t.Task_Executioner__r.Email;
            //String[] toAddresses = new String[] {userEmail};    
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            //mail.setToAddresses(toAddresses);
            //mail.setSenderDisplayName('Test');
            mail.setTargetObjectId(con.Task_Executioner__c);
            //mail.setTargetObjectId(t.Task_Executioner_1__c);
            //mail.setTargetObjectId(t.Task_Executioner_2__c);
            mail.setTemplateId(et.Id);
            mail.setSaveAsActivity(false);
            mail.setWhatId(con.Id);
            mails.add(mail);
            //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
        system.debug('0000000');
       
    }
    
    Messaging.sendEmail(mails);
}
}

Regards
Hello

   I am new salesfroce, i have  requirement, I have an appointment object in that i have two fields
1. Start Date(Date/Time) and status(picklist). Whenever the start date/Time is more than current date and time, status as to be updated as In Progres. Can someone suggest which is better to use timebased workflow or time based triggres

Regards
raj
Hi,

I have used the text field . I want to add validation for text field below   : NOT(REGEX(Address__c    , "[a-zA-Z0-9,/.\r\n -]+")). but its working fine only given special character.  But we enable the validations means its the mantatory field.  
Note :  I need to check the condition if text field is empty means it should save. How to do that.

Any one guide me to solve this.

Advance Thanks.
Maheshwar
I am trying to add some custom buttons to a VF page and keep getting the following error when ever I try to add it.  Field $label.Retunt_To_Corporate_Transportation_Pro_Serv does not exist.  Check spelling.  The spelling is correct and the button is set up exactly the same as other buttons that have been added to the VF page.  I am pretty new to this so I am definately missing many of the nuances of VF development but I cannot see why it will not let me add the field.  I also created 3 other fields on the same object and none will work with the page either I just get the same error.
public with sharing class legalactionsubmission
{   
    public legal_action__c legact{get;set;}
    public String currentid= ApexPages.currentPage().getParameters().get('id');
    public boolean savedis{get;set;}
    public string idcurr;
    
    public legalactionsubmission(ApexPages.StandardController controller)
    {
        savedis=false;
        legact=new legal_action__c();
        legact=(legal_action__c)controller.getrecord();
        system.debug('>>>legact'+legact);
        this.idcurr=ApexPages.currentpage().getparameters().get('id');
        if(currentid!=null && currentid!='')
        {
          //Legal_Action__c a = new Legal_Action__c();
          legact=[select id,submit_done__c,entry_by__c from legal_action__c where id=:currentid];
          if(legact.submit_done__c==true)
          {
           savedis=true;
           String msg = 'Thank you for Submitting.';
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,msg));
          }
        }  
    }
    
    public pagereference save()
    {
     savedis=true;
     legal_action__c leg= new legal_action__c();
     //legal_action__c legact= new legal_action__c();
     system.debug('>>>legact'+legact);
     leg=[select id,Name_of_Client__c,submit_done__c,Name_of_VA__c,entry_by__c,reviewed_by__C,Summary_of_Situation__c,Attachment_summary__c from legal_action__c where id=:currentid];
     if(leg.submit_done__c==false)
     {
       leg.Name_of_Client__c=legact.Name_of_Client__c; // Error Line 
       leg.submit_done__c=true;
       leg.Name_of_VA__c=legact.Name_of_VA__c;
       leg.entry_by__c=legact.entry_by__c;
       leg.reviewed_by__C=legact.reviewed_by__C;
       leg.Summary_of_Situation__c=legact.Summary_of_Situation__c;
       leg.Attachment_summary__c=legact.Attachment_summary__c;
       update leg;
       system.debug('>>>>entryby'+leg.entry_by__c);
     }
     
        pagereference ref;
        ref = new pagereference('/apex/legal_action_final_reviewe?id='+legact.id);
        ref.setredirect(true);
        return ref;
    }
}
Hi,
Can anyone help me for this, I know where it goes wrong..  I have queried correctly but still its showing the error.. Any mistakes here?
 
Hello,

I have a Approval process initiated from process builder.
The approvaal email is received but i cannot see anythign in chatter.

It is received in salesforce1 app.

Any reason for this cause

Hi Community,

I am new to Salesforce and using APEX.  I am completely self-taught too.  With that said, I am trying to learn triggers and cannot find an exact example of how to achieve what I am working on.  My problem is that when a Contact updates their information through my Visualforce page, Salesforce will overwright fields with the new data they inputted - which is great, except for the 'Description' field.  I want the new 'Description' to append to whatever they previously had written in that field.  Can anyone help me?

The pseudo code would be something like:

trigger UpdateDescription on Contact (before update) {
          Contact.Description = Contact.OldDescription + " " + Contact.NewDescription;

}

Thank you in advance for your help!

I have written used the below code in my apex class and got hte error : " Compile Error: sObject type 'NewsFeed' is not supported"
public List<NewsFeed> getNewsFeed()  {                                // Retrieving all feeds form Newsfeed
        List<NewsFeed> myfeed = [SELECT Id, Type,
                         CreatedById, CreatedBy.FirstName, CreatedBy.LastName,CreatedDate,
                         ParentId, Parent.Name, 
                         Body, Title, LinkUrl, ContentData, ContentFileName,
                             (SELECT Id, FieldName, OldValue, NewValue
                              FROM FeedTrackedChanges ORDER BY Id DESC), 
                             (SELECT Id, CommentBody, CreatedDate,
                              CreatedBy.FirstName, CreatedBy.LastName
                              FROM FeedComments ORDER BY CreatedDate LIMIT 10),
                             (SELECT CreatedBy.FirstName, CreatedBy.LastName
                              FROM FeedLikes)
                         FROM NewsFeed
                         ORDER BY CreatedDate DESC, Id DESC
                         LIMIT 20];
           return myfeed;
    }
 can anyone teel me solution to remove this error??
Hi guys,

I have custom opportunity field named Total_Amount__c.
I need to get Top 5 accounts with opportunities based on Total Amount.
Need to code above(not in reports)

Note: Consider if an account have 5 opps, then the sum of 5 opp fields need to be taken into consideration.


Thanks in advance,
 
Hi friends

I need to count the number of contacts for each account. so I created a custom field (Number_of_Contacts_c) on the account object.
For new accounts I have written code and its working fine. Also when I delete a contact in detail page of account  its workign fine.
There will be old accounts with no contacts records in detail page prior to this code.  I am stuck here as how to update this accounts and show the number of contacts records

apex class code:
public class CountContacts_InAccount
{
      public void CountContacts()
      {
          list<Account> noofcontacts = [select Id,Number_of_contacts__c from Account];
          list<Contact> conforcontacts = [select ID,AccountID from Contact];
          
          for (Account acct : noofcontacts ) 
          {
              list<ID> conIds = new list<ID>();

              for (Contact con : conforcontacts )
              {
                    if (con.AccountId == acct.Id)
                    {
                       conIds.add(con.Id);
                       acct.Number_of_contacts__c= conIds.size();
                     }
              }
         }
          Database.Update(noofcontacts);   
     }
}

trigger code:
trigger trg_CountContacts on Contact (after Insert,after Update,after Delete,after Undelete)
{
     CountContacts  obj = new CountContacts();
     
     if ((Trigger.IsInsert) || (Trigger.IsUndelete))
     {
         obj.CountContacts(Trigger.New);
     }
     
     if (Trigger.IsDelete)
     {
         obj.CountContacts(Trigger.Old);
     }
}

Can any one psl elt me know:?

Regards
sonali verma
Ultimate goal:  I need to end up with a list of 100 Contacts based on two other related objects and certain criteria.  
Background:  The Account object is related to two other objects Contact (lookup, 1 Account can have many Contacts) and I have another object, a custom object, BD__c, with a master detail relationship to the Account object (1 Account can have many BD__c's).   

To start with, I return a list of these BD__c and I want to order them by Opportunity_Amount__c (descending):

BD__c record #1 Opportunity_Amount__c = $100,000.
BD__c record #2 Opportunity_Amount__c = $50,000.
BD__c record #3 Opportunity_Amount__c = $20,000.
BD__c record #4 Opportunity_Amount__c = $0.

Problem to solve:  Since each BD__c is associated to an Account I want the contacts from the associated account from BD record #1, record #2, record #3 (and so forth) until the total # of contacts reaches 100. In other words I want the first 100 contacts associated with accounts related to the BD__c records who have the highest Opportunity_Amount__c.

So far the code I have is:  

Set<Id> setOfBDIds = new Set<Id>();
for (BD__c bbb : [SELECT b.Account__r.Id  FROM BD__c WHERE Opportunity_Amount__c > 0 ORDER BY Opportunity_Amount__c DESC]) 
{
    setOfBDIds.add(bbb.Account__r.Id);
}
List<Contacts> contacts = [SELECT AccountId, Name FROM Contact WHERE AccountId IN =: setOfBDIds LIMIT 100];

The problem is that, with this structure, the contacts in the list won't necessarily be from the BD__c/Accounts who have the highest Opportunity_Amount__c - they can be from any account.

I thought about trying this using SOQL but according to this:  https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_limits.htm (https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_limits.htm" target="_blank)

"In each specified relationship, only one level of parent-to-child relationship can be specified in a query"

Any thoughts on how this can be acheived? 

Thanks in advance!
Controller
public class PosAppController {

    public Id selectedposition{get;set;}
    
    public List<Job_Application__c> AppplicationDetails{get;set;}

    public List<Job_Position__c> getMypositions() {
    
        return [SELECT id,Name FROM Job_Position__c];
    }
    
    public void PositionClicked(){
    
      AppplicationDetails = [SELECT Name FROM  Job_Application__c WHERE Job_Position__c.Id = :selectedposition]; //showing error when trying to match the id 
    }

}
VisualForce Page
<apex:page controller="MyController">
  <apex:form >
    <apex:dataList value="{!myaccounts}" var="acct">
       <apex:commandLink action="{!accountclicked}" reRender="ContactDetail">
       <apex:outputText value="{!acct.name}">
       </apex:outputText>
       <apex:param name="id" value="{!acct.id}" assignTo="{!selectedAccount}"/>
       </apex:commandLink>
    </apex:dataList>
    <apex:outputPanel id="ContactDetail">
       <apex:repeat value="{!contactsInformation}" var="contact">
         <p> {!Contact.FirstName & ' ' & Contact.LastName} </p>
       
       </apex:repeat>
    </apex:outputPanel>
  </apex:form>
</apex:page>

I need to show up the job positions names on the page and clicking on each position should show up the job application names related to that position and the relationship between position and application is look-up
Hello,

I have a field with type "Record Type".

How can i use it in SOQL query ?

recordType , recordTypeId didnt work
Hi all, 
Please clarify my doubt,
My Question is: through controller i want to save account record, after saving perticular record i want to be stay on corresponding detail page itself.  Please see the bellow vf page and apex class and suggest me what i need to add to get detail page.
Thanks in advance,
venkat.

The Page is:
------------------
<apex:page controller="SaveAccount">
  <apex:form >
    <apex:pageblock title="Enter Account Details">
       <apex:pageblockSection >
          <apex:inputtext value="{!AcName}" label="Acc_Name"/>
          <apex:inputtext value="{!AcPhone}" label="Acc_Phone"/>
       </apex:pageblockSection>
       <apex:pageblockButtons location="Bottom" >
       <apex:commandButton action="{!Save}" value="Save"/>
       </apex:pageblockButtons>
    </apex:pageblock>
  </apex:form>
</apex:page>
----------------------------------
class is:
----------------------------------
public with sharing class SaveAccount {

    public PageReference Save() {
    account ac = new account();
    ac.name = AcName;
    ac.phone = AcPhone;
    insert ac;
        return null;
    }
    public String AcPhone { get; set; }
    public String AcName { get; set; }
}

 
Hi All,

Could you please let me know , how can we run a batch class which are containing callouts, on Scheduled Apex.
when i am running batch process on click event It is working fine but when i scheduled it the it is giving me error like 'callouts is not allowed at Scheduled Apex. '

Regards
Sumit
Hello Everyone,

While doing callout getting the error :: 
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out .

Actually i am sending request to 3rd party system based on the response iam upserting records in salesforce.
When i was doing with 1 record, it is working fine. But when i tried with bulkified manner getting the above error.

So while research i got an idea that i need to seperate the transactions for both the Callout's and DML's.
Is there any function or method that callout has been done, with that i can seperate both the transactions for DML's in salesforce and Callouts

How can i avoid this particular error??  Please suggest me !!!
frinds, 
 in overriding vf pages with new button or edit button the vf page override option show only none option how to get more option on these..
Hello,

I have a requirement, where a junction object record needs to be created based on the matching field values of both the parent objects.
For e.g Master1 object (Flat) has a picklist field 'Flat type' (1BHK, 2BHK) and same field is there on Master2 object (Enquiry). If 'Flat type' picklist value matches in both Master object a new junction object record needs to be created with same both records as parent. 
i.e If a Enquiry record is created with 1BHK as Flat Type then it should match with some existing record in Flat object with 1BHK as flat type and then a new junction object record should be created.

I am new in development and have no idea where to start with.
Please help.

Thanks in advance.
 
Hi, I tried reading up on static boolean variables and tried using them with not much success. Can somebody help how I can prevent recursive triggering in the below example? Many thanks!

First Trigger updates Invoice a dollar value equal to the sum of the dollar value from Permits which have a matching Invoice number. As below:

trigger InvoiceAmountUpdate on Permit__c (after update) {

for(Permit__c obj : trigger.new)
{
    List<Permit__c> permit = [select Total1__c from Permit__c p where p.Invoice_Num__c = :obj.Invoice_Num__c];

    decimal sum = 0;
    for (Permit__c p : permit) {sum = sum + p.Total1__c;}
    List<bb_Invoice__c> invoice = [select Invoice_Amount__c from bb_Invoice__c i where i.id = :obj.Invoice_Num__c];
    
for (bb_Invoice__c i : invoice) {
        i.Invoice_Amount__c = sum;
        update i;
    }
}
}

Second Trigger updates payment amount on Permits when the full invoice value is paid. However, with each update on Permit, the first trigger is called ending in a recursive pattern

trigger PaymentStatusUpdate on bb_Invoice__c (before update) {

for(bb_Invoice__c obj : trigger.new)
{
   if (obj.Paid_Amount__c>=obj.Invoice_Amount__c) {
    obj.Payment_Status__c = 'Paid';
   
List<Permit__c> permit = [select Total1__c,Paid__c from Permit__c p where p.Invoice_Num__c = :obj.id];

    for (Permit__c p : permit) {
        p.Paid__c = p.Total1__c;
        update p;
    }
    } 

    else if (obj.Paid_Amount__c>0) {
    if (obj.Paid_Amount__c<obj.Invoice_Amount__c) {
    obj.Payment_Status__c = 'Partially Paid';
    } 
    }
}
The line attempting to create the Set "ids" is throwing an error upon insert of a new lead.

Here is the error "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, leadTrigger: execution of BeforeInsert     caused by: System.NullPointerException: Attempt to de-reference a null object". 

How do you get the Id for trigger.new?
 
trigger leadTrigger on Lead (before insert, after insert, after update) {
    Set<ID> ids = Trigger.newMap.keySet();  // getting error here
    List<Lead> triggerLeads = [SELECT Id, Email, LeadSource FROM Lead WHERE Id in :ids];
}

 
Hi,

The current scenario is that a custom Opportunity Field (Cfield__c) needs to be required when the Opportunity.Amount >= $200,000 and Stage is A,B,C, and E. Through the UI, a red bar needs to appear next to the field to indicate it is required when it meets the criteria above, but needs to be "grayed out" (not visible) if the Amount < $200,000.

How may i use an apex trigger or validation rule to do this? If this cannot be done with Apex Trigger or validation rule, what other method may I use? Ideally I would like to stay away from overriding the Opportunity Edit page with a VF page. 

I thought i could do this with Salesforce Flow, but I am new to that and it seems cumbersome to get that to work.

Requirements:
  • Opportunity.Amount >= $200,000
  • Stage = A,B,C, and E.
  • Cfield__c is required (dropdown with Yes or No as values)
  • Red bar appears next to Cfield__c to indicate it is required.
Hi,
Here is the problem i have written a trigger that inserts a record along with that vf created pdf.when i execute from console the reocrd and pdf is inserting when i click on pdf content is exact but when i insert a record manually,pdf is also created but when i download the pdf file it is getting null pdf?please Help out.
 if(!Test.isRunningTest()) 
                    {
                        b = pdf.getContent();
                        
                        System.debug('blobcontent+++++++++++'+b );
                    }
                    else
                    {
                        b = Blob.valueof('Some random String');
                    }
                    
                    n = new Attachment();
                    n.ParentId = id;
                    n.Name = 'Carrier_Confirmation.pdf';
                    
                    n.Body = pdf.getContentAsPDF();
                  
                        //n.Body = Blob.valueof('Some random String');
                 
                    n.IsPrivate = false;
                    n.contentType = 'image/pdf';
                    
                    insert n;
when I run the block of ‘static’ code in execute anonymous, it throws an error “only top-level methods in the class are allowed to be declared as static”. I tried my code also: there also same issue.
 public StringArrayTest {  public static void generateStringArray() {}  }
 Can anyone help on this?

thank you.