• Apoorv Saxena 4
  • SMARTIE
  • 1414 Points
  • Member since 2014

  • Chatter
    Feed
  • 49
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 176
    Replies
Hello,

i am using field BillingAddress from Account but its alwaoys giing error when creating new account, in apex class its not giving error,

If i need to use city, zip code for for comparing account; which field can i use
  • November 08, 2016
  • Like
  • 0
Hi all,

public with sharing class SimpleErrorController { }

In the above code what is the with sharing..
when i save my trigger i m getting this error
ERROR ::: Method does not exist or incorrect signature: op_trigger.op_check(List<Opportunity>) at line 2 column 1

this my trigger code

trigger trigger_1 on Opportunity (before insert, before update) {
op_trigger.op_check(Trigger.New);
}



this is my class code

public class op_trigger
{
    public void op_check(List<Opportunity> ops)
        {
            Double Total_Amount = 0 ;
            for(Opportunity o1 : [select amount from Opportunity where CreatedDate = Today AND CreatedByID = :UserInfo.getUserID()])

                                    {
                                        Total_Amount = Total_Amount + o1.Amount;
                                    }
                                    
          for(Opportunity o2 : ops)
          {
              Total_Amount = Total_Amount + o2.Amount;
              
              if(Total_Amount > 1000000)
              o2.addError('out of Limit');
          }                          
        }

}
I have written a trigger to clone/copy a record from Custom object "Student__c" (when a new student is created or modified)  to Account (Person Account) and it works, I am not sure on how to write a test class to increase the code coverage, please help.  The trigger is as below:

trigger CreatePersonAccountfromStudent on Student__c (after insert,after update)
{
    List<account> acc=new List<account>();
    for(student__c stud:Trigger.New)
    {
        acc.add(new account(
               LastName=Stud.name__c,
               recordtypeid='012O00000009RtPIAU',
               Autocreated__pc=True,
               PersonBirthdate=Stud.DOB__c,
               Current_Acedamic_Year__pc=Stud.Current_Acedamic_Year__c,
               Date_of_Collection__pc=Stud.Date_of_Collection__c,
               Discount_Percentage__pc=Stud.Discount_Percentage__c,
               Discount_Policy__pc=Stud.Discount_Policy__c,
               Discount_Remarks__pc=Stud.Discount_Remarks__c,
               Discount_Type__pc=Stud.Discount_Type__c,
               English__pc=Stud.English__c,
               Exclude_Registration__pc=Stud.Exclude_Registration__c,
               Father_Email__pc=Stud.Father_Email__c,
               Father_Name__pc=Stud.Father_Name__c,
               Father_NRIC__pc=Stud.Father_NRIC__c,
               Father_Office_Phone__pc=Stud.Father_Office_Phone__c,
               Father_Primary_Contact__pc=Stud.Father_Primary_Contact__c,
               Father_Remark__pc=Stud.Father_Remark__c,
               Father_Staff__pc=Stud.Father_Staff__c,
               Gender__pc=Stud.Gender__c,
               GEP__pc=Stud.GEP__c,
               Guardian_Email__pc=Stud.Guardian_Email__c,
               Guardian_Mobile__pc=Stud.Guardian_Mobile__c,
               Guardian_Name__pc=Stud.Guardian_Name__c,
               Guardian_NRIC__pc=Stud.Guardian_NRIC__c,
               Guardian_Office_Phone__pc=Stud.Guardian_Office_Phone__c,
               Guardian_Primary_Contact__pc=Stud.Guardian_Primary_Contact__c,
               Guardian_Relationship__pc=Stud.Guardian_Relationship__c,
               Guardian_Remarks__pc=Stud.Guardian_Remark__c,
               Guardian_Staff__pc=Stud.Guardian_Staff__c,
               PersonHomePhone=Stud.Home_No__c,
               Is_Mind_Stretcher_Staff_Mother__pc=Stud.Is_Mind_Stretcher_Staff_Mother__c,
               Level__pc=Stud.Level__c,
               Level_Promoted_DateTime__pc=Stud.Level_Promoted_DateTime__c,
               PersonMailingStreet=Stud.Unit_Number__c+' '+Stud.Block__c+' '+Stud.Street__c+' '+Stud.Postal_Code__c,
               Maths__pc=Stud.Maths__c,
               Mobile_No_Father__pc=Stud.Mobile_No_Father__c,
               Mother_Email__pc=Stud.Mother_Email__c,
               Mother_Name__pc=Stud.Mother_Name__c,
               Mother_No_Mobile__pc=Stud.Mobile_No_Mother__c,
               Mother_NRIC__pc=Stud.Mother_NRIC__c,
               Mother_Office_Phone__pc=Stud.Mother_Office_Phone__c,
               Mother_Primary_Contact__pc=Stud.Mother_Primary_Contact__c,
               Mother_Remark__pc=Stud.Mother_Remark__c,
               Mother_Staff__pc=Stud.Mother_Staff__c,
               MS_Start_Kit_Bag__pc=Stud.MS_Start_Kit_Bag__c,
               Nationality__pc=Stud.Nationality__c,
               NRIC__pc=Stud.NRIC__c,
               NTUC_10_Discount__pc=Stud.NTUC_10_Discount__c,
               NTUC_Card_Expiry__pc=Stud.NTUC_Card_Expiry__c,
               NTUC_Remark__pc=Stud.NTUC_Remark__c,
               Others__pc=Stud.Others__c,
               Person_Contact__pc=Stud.Person_Contact__c,
               Primary_Contact_Number__pc=Stud.Contact_number__c,
               Primary_Email__pc=Stud.Primary_Email__c,
               Primary_Name__pc=Stud.Primary_Name__c,
               Primary_Remark__pc=Stud.Primary_Remark__c,
               Promotion__pc=Stud.Promotion__c,
               Reading_Oceans_Email__pc=Stud.Reading_Oceans_Email__c,
               Reading_Oceans_End_Date__pc=Stud.Reading_Oceans_End_Date__c,
               Reading_Oceans_Start_Date__pc=Stud.Reading_Oceans_Start_Date__c,
               Reading_Oceans_Subscrip__pc=Stud.Reading_Oceans_Subscrip__c,
               Registraation_Centre__pc=Stud.Registration_Centre__c,
               Related_Centres__pc=Stud.Related_Centres__c,
               Remarks__pc=Stud.Remarks__c,
               RO_Date_Send_User__pc=Stud.RO_Date_Send_User__c,
               RO_Type__pc=Stud.RO_Type__c,
               Safra_Card_Expiry__pc=Stud.Safra_Card_Expiry__c,
               Safra_Card_Holding__pc=Stud.Safra_Card_Holding__c,
               Safra_Remark__pc=Stud.Safra_Remark__c,
               Salesforce_Id_from_Student_Object__pc=Stud.ID,
               School__pc=Stud.School__c,
               Science_Percentage__pc=Stud.Science__c,
               Secondary_Stream__pc=Stud.Secondary_Stream__c,
               Student_Id_from_Student_Prospects__pc=Stud.name,
               Student_Old_Reference_ID__pc=Stud.Student_Old_Reference_ID__c,
               Student_Status__pc=Stud.Student_Status__c,
               Student_Type__pc='Student',
               Tick_to_activate_inter_branch_discount__pc=Stud.Tick_to_activate_inter_branch_discount__c
               ));
    }
    insert acc;
}
  • October 18, 2016
  • Like
  • 0
Hello,

I have 3 custom objects: Commission, Tax ID and Broker Appointment. Commission and Broker Appointment are not related but Tax ID has 1 to many relationship with each of those objects. Commission and Broker Appointment have TAX ID as a lookup field. 
I want to updated a field in Commission when Broker Appointment Status is Approved. 

Here is the code I built.
trigger ReleaseCommissionWhenBrokerApproved on Broker_Appointment__c (after update) {

     map<Id, Broker_Appointment__c> brokerApptIds = new map<Id, Broker_Appointment__c>();
   
        for (Broker_Appointment__c a : trigger.New){
            if ( a.Tax_ID__c != null && a != null && a.Appointment_Status__c == 'Approved'){
            brokerApptIds.put(a.Tax_ID__c, a);
          }
        }
    
    List<Commission__c> comm = [ SELECT Id, Tax_ID__c, Underwriter__c, Domicile_State1__c, Broker_Writing_Agent__c, On_Hold_Reason__c, Hold_Payment__c FROM Commission__c WHERE Tax_ID__c IN :brokerApptIds.keySet() AND Hold_Payment__c = TRUE];
  
    Broker_Appointment__c appt;
       
    for (Commission__c c: comm){
        
             if(!brokerApptIds.isEmpty() && brokerApptIds.containsKey(c.Tax_ID__c) && appt != null ){
       			 if (appt.Underwriter_Account__c == c.Underwriter__c && appt.Producer_Contact__c == c.Broker_Writing_Agent__c && appt.State__c == c.Domicile_State1__c)
                 {
                    c.Hold_Payment__c = FALSE;      
               }  
          }
       update comm;
    }        
}

When I remove the line "if (appt.Underwriter_Account__c == c.Underwriter__c && appt.Producer_Contact__c == c.Broker_Writing_Agent__c && appt.State__c == c.Domicile_State1__c)", the trigger works but I need to compare thos fields before updating the fields.

Help need please. Maybe I'm missing something.

Thank you.
Working on a test class and am missing something basic, error is System.NullPointerException: Attempt to de-reference a null object  and the stack trace is Class.programclone.<init>: line 39, column 1
Class.testclonedppage.test_method_one: line 52, column 1

VF page 
 
<apex:page Controller="programclone" >
 


     <apex:form id="frm1" >
     

     
        <apex:pageblock >
        
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}" />
                <apex:commandButton value="Cancel" action="{!cancel}" />
            </apex:pageBlockButtons>
            
            
                    <apex:pageBlockTable value="{!Records}" var="Record"> 
            <apex:column > 
                <apex:facet name="header">Account Name</apex:facet> 
                <apex:outputText value="{!Record.Account_Name__r.name}"/> 
            </apex:column> 
            
                        <apex:column > 
                <apex:facet name="header">EWS Territory</apex:facet> 
                <apex:outputText value="{!Record.Account_Name__r.Territory_EWS__c}"/> 
            </apex:column> 
            
            <apex:column > 
                <apex:facet name="header">City</apex:facet> 
                <apex:outputText value="{!Record.Account_Name__r.billingcity}"/> 
            </apex:column> 
            
            <apex:column > 
                <apex:facet name="header">State</apex:facet> 
                <apex:outputText value="{!Record.Account_Name__r.billingState}"/> 
            </apex:column> 
            
            <apex:column > 
                <apex:facet name="header">Key Contact</apex:facet> 
                <apex:outputText value="{!Record.DIST_EXEC_SPONSOR__r.firstname}"/> 
            </apex:column> 

            <apex:column > 
                <apex:facet name="header">Email</apex:facet> 
                <apex:outputText value="{!Record.DIST_E_S_Email__c}"/> 
            </apex:column>             
            <apex:column > 
                <apex:facet name="header">Program Type </apex:facet> 
                <apex:outputText value="{!Record.RecordType.name }"/> 
            </apex:column> 
            
            <apex:column > 
                <apex:facet name="header">Status</apex:facet> 
                <apex:outputText value="{!Record.Program_Status__c }"/> 
            </apex:column> 
            
            <apex:column > 
                <apex:facet name="header">100%</apex:facet> 
                <apex:Outputtext value="{!Record.CS_100PercentCommitted__c }"/> 
            </apex:column> 
           
           
           
             <apex:column > 
                <apex:facet name="header">YTD Sales</apex:facet> 
              <apex:Outputtext value="{!Record.CS_YTD_Sales__c}"/> 
            </apex:column>  
            
            <apex:column > 
                <apex:facet name="header">Run Rate</apex:facet> 
               <apex:Outputtext value="{!Record.CS_Run_Rate__c}"/> 
            </apex:column>  
                         
            <apex:column > 
                <apex:facet name="header">Projected Payout</apex:facet> 
               <apex:Outputtext value="{!Record.CS_Projected_Payout__c}"/> 
            </apex:column>  
            
            
            <apex:column > 
                <apex:facet name="header">Clone</apex:facet> 
                <apex:inputField value="{!Record.Clone_no_send__c}"/> 
            </apex:column> 
            
            
                        <apex:column > 
                <apex:facet name="header">Send now</apex:facet> 
                <apex:inputField value="{!Record.Clone_Send_now__c }"/> 
            </apex:column> 
            
        </apex:pageBlockTable> 
            
            
            
        </apex:pageblock>
    </apex:form>
 
 
</apex:page>

and controller
public class programclone {

    public programclone() {
    
     String myterr = [Select Sales_Territory__c From User Where Id = :UserInfo.getUserId()][0].Sales_Territory__c ;
    System.debug(cloneyear );
        Records =[select Account_Name__r.name,
                         Account_Name__r.billingcity, 
                         Account_Name__r.billingstate, 
                         Account_Name__r.Territory_EWS__c,
                         DIST_EXEC_SPONSOR__r.name,
                         DIST_EXEC_SPONSOR__r.firstname,
                         DIST_E_S_Email__c,
                         Account_Number__c, 
                         Program_Status__c, 
                         RecordTypeid, 
                         Program_Year__c,
                         recordtype.name,
                         CS_YTD_Sales__c,
                         CS_Run_Rate__c,
                         CS_Projected_Payout__c,
                         CS_100PercentCommitted__c,  
                         Clone_Send_now__c , 
                         Clone_no_send__c 
                         from Distributor_Program__c 
                         Where Program_Status__c='active' 
                         and ( CreatedByid = :UserInfo.getUserid()  or   Account_Name__r.Territory_EWS__c = :myterr ) 
                         and Program_Year__c = :cloneyear 
                         and   Clone_no_send__c  != true 
                         and   Clone_Send_now__c != true 
                         order by Account_Name__r.name limit 200]; 


    }


        cloan_program_year__c settings = cloan_program_year__c.getInstance('cloneyear');
   
        string cloneyear =string.valueof(settings.Year__c);

       
   

public List<Distributor_Program__c> Records {get; set;} 


 

    public PageReference cancel() {
             return new PageReference('/home/home.jsp');
    }


    public PageReference Save() {
       update records;
        return new PageReference('/apex/nextstep');

    }



    }

And the test class 
 
@isTest
private class testclonedppage {

private static final Id acctrtid = Schema.SObjectType.account.getRecordTypeInfosByName().get('Distributor').getRecordTypeId();
private static final Id dpid = Schema.SObjectType.Distributor_Program__c.getRecordTypeInfosByName().get('PS Cornerstone').getRecordTypeId();

	@isTest static void test_method_one() {
		 
   

	Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
	User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
	EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
	LocaleSidKey='en_US', ProfileId = p.Id, 
	TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@hammybuiltthis.com',
	Sales_Territory__c = '1');

  	cloan_program_year__C cs = new cloan_program_year__c(name = 'cloneyear' , year__c = '2016', year1__c = '2017' );

  	Account acc = new Account();
  	acc.Name='Abce';
	acc.Type='Distributor';
	acc.recordtypeid = acctrtid;
	acc.Territory_EWS__c = '1';
  	
  	insert acc;

  	Contact c = new Contact();
  	c.Firstname = 'first';
  	c.Lastname = 'last';
  	c.Email = 'email@email.com';
  	c.Accountid = acc.id;


  	insert c;

	System.runAs(u) {

		Distributor_Program__c  dp = new Distributor_Program__c();
		dp.RecordTypeId = dpid;
		dp.Account_Number__c = '1';
		dp.Program_Year__c = cs.year__c;
		dp.Account_Name__c = acc.id;
		dp.DIST_EXEC_SPONSOR__c = c.id;
		insert dp;
		
System.debug('Current Contact name: ' + c.firstname);
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
		
		Test.setCurrentPage(Page.programclone);
		programclone controller = new programclone();
	
		controller.save();


		

		}

	}
	

	
}

 
My test class below keeps coming up with an error when i triy to move an updated trigger over to my production org via outbound change set or eclipse. The error is List has no rows for assignement. If anyone can help find the reason this test class keeps coming up with an error, i would appreciate it.
User-added image

/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 *
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */

@isTest
private class Account_Create_Contact_TestClass {

    static testMethod void myUnitTest() {
       
        Profile p = [SELECT Id FROM Profile WHERE Name = 'BLX Telemarketer' LIMIT 1];
        User u = [SELECT Id FROM User WHERE ProfileId = :p.Id AND User.IsActive = true LIMIT 1];
        List<Account> accs = new List<Account>();
        List<Account> conAccs = new List<Account>();
        Set<Id> accIds = new Set<Id>();
       
        Integer i = 0;
        System.runAs(u) {
           
            // Test Accounts with no Last Name has been added
            for (Account a : [SELECT Id FROM Account LIMIT 50]) {
                a.Eerstenaam__c = 'Test First Name';
            }
           
            if (!accs.isEmpty()) {
                update(accs);
                accs.clear();
            }
                   
            for (Account a : [SELECT Id FROM Account LIMIT 50]) {
                accIds.add(a.Id);
                a.Eerstenaam__c = 'Test First Name';
                a.Achternaam__c = 'Test Last Name';
                a.Nieuwsbrieven_ontvangen__c = false;
                if (i == 0) {
                    a.Nieuwsbrieven_Ontvangen__c = true;
                    a.Dezelfde_Email__c = true;
                    i = 1;
                }
                else if (i == 1) {
                    i = 2;
                    a.Status_Belactie_2010__c = 'Wil Gebeld Worden Door Account Manager';
                    a.Opmerkingen__c = 'This is a test Task';
                }
                else {
                    a.Achternaam__c = NULL;
                }
                accs.add(a);
            }
            if (!accs.isEmpty()) {
                update(accs);
            }
           
            for (Contact c : [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId IN :accIds AND LastName = 'Test Last Name']) {
                Account a = new Account(Id=c.AccountId);
                a.Achternaam__c = c.LastName;
                conAccs.add(a);
            }
           
            if (!conAccs.isEmpty()) {
                update(conAccs);
            }          
        }
               
       
    }
}
  • October 17, 2016
  • Like
  • 0
Hi All,

I am new to the salesforce, I have one query.i have two Apps namely ABC and XYZ. and Account object on both these apps.
how to fetch Account records based on only ABC app not XYZ.

Thanks
Divya. 
How to call batch class inside apex class method.Is there any way to call ? if so please give some example.
  • October 17, 2016
  • Like
  • 0
ERROR : Variable does not exist: myContct.Email

this is my code...

trigger Proposal on Contact (before insert) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Contact myContact : Trigger.new)
    {
        if(myContct.Email != null && myContact.FirstName !== null)
        {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> SendTo = new  List<String>();
            SendTo.add(myContact.Email);
            mail.setToAddresses(SendTo);
            mail.setReplyTo('ashmi@aglowiditsolutions.com');
            mail.setSenderDisplayName('BY Ashmi');
            
            mail.setSubject('Business Proposal');
            String body = 'Dear' + myContact.FirstName +', ';
            body += 'hiii';
            body += 'hellooo';
            body += 'kem cho??';
            body += 'its a business proposal...';
            mail.setHtmlBody(body);
            mails.add(mail);
        }
    }
    Messaging.sendEmail(mails);
}


 
In an Apex class, I'd like to take two lists of contacts, merge them, remove duplicate contacts, and then sort them? Any suggestions? Thanks.
 
I have created a form in Visualforce page, which will create a lead in SFDC. So far, it is looking and working as expected.
However, I would like to pass some values without making it visible on the Visualforce page.

For example, the URL ends in ".......?param1=ClassName&param2=ABC"
I have an extension that gets the values of param1 and param2.

On the visualforce page - I have:  <apex:outputText value="{!Param2}" style="width:225px"/> 
and other fields that are getting entered manually: <apex:inputText value="{!lead.Company}" style="width:225px"/>
 

How can I store the {!Param2} value into a custom lead field (Training_Location_and_Date__c)?
When the lead is created, the custom field is empty.



 
Hello , 

Please help in wrting the trigger if the phone number in the account tab is changed by the user it must automatically update in the contact tab phone number also

Thanks & Regards,
Rakesh Konda
Hi everyone,
Can anyone hlep me how to write the test class for the after insert trigger. I'm new to salesforce.
My trigger is as below
trigger ChangeLeadStatus on Task (after update) {
    Set<Id> leadIds = new Set<Id>();
    for(Task tsk : trigger.new){
        if(tsk.Status == 'Completed' && String.valueOf(tsk.whoId).startsWith('00Q')){
            leadIds.add(tsk.whoId);
        }
    }
    Map<Id,Lead> allRealtedLeads = new Map<Id,Lead>([Select status from Lead where ID IN :leadIds]);
    List<Lead> leadsToUpdate = new List<Lead>();
    for(Task tsk : trigger.new){
        if(tsk.Status == 'Completed' && String.valueOf(tsk.whoId).startsWith('00Q') && allRealtedLeads.containsKey(tsk.whoId)){
            allRealtedLeads.get(tsk.whoId).Status = tsk.Subject;
            leadsToUpdate.add(allRealtedLeads.get(tsk.whoId));
        }
    }
    if(leadsToUpdate.size() > 0){
        update leadsToUpdate;
    }
}

regards,
Suneel.
I have Try to get the text value to the Number (because the text has the charector of number) for my requirement  in formula fieldnbut it's provide the result instant of it's provide the "#ERROR" in the result page I don't know why If any body know please tell the solution to rectify this thing and my code is followingly,
VALUE(MID(RIGHT((TEXT(Calculating_Date__c - 0.2916)),9),0,5))
I want to do here to take a time portion of the Calculating Date field value if it is 10/14/2016 11:35 means  as like 11:35  or 23:35 is I want to in my output here but it's not working so that's my problem .For answer'sthanks in advance.Mohan(here I subtracting the value is My org is using (GMT - 7) so that's why).
 
My controller class -- 

Public Class ContactUpdateServer { 
    public Contact objContact{get;set;}
    public String currentRecordId {get;set;}
    public Contact con{get;set;}
   
    public List<contact> up = new List<Contact>();
    
    List<ContactCreationCalloutParser.Profile> lstProfilemain = new List<ContactCreationCalloutParser.Profile>() ;
    
    public ContactUpdateServer(ApexPages.StandardController controller) {
     Boolean isValid = False;
    currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        con = [select SSO_Number__c,Name from Contact where id =: currentRecordId ];
        system.debug('----- sso --- ' +con);
        string searchstring = con.SSO_Number__c;
        if(searchString.length() == 9){
                // Check if search string is 9 digit long numeric value. i.e SSO number.
                   if(searchString.isNumeric()){
                     isValid = True;
       }}
       if(isValid){
       system.debug('----isvalid----' +isValid);
        ContactServer();}
    }
 Public Pagereference Goback(){
    Contact objContact = new Contact();
    objContact.Id = ApexPages.CurrentPage().getparameters().get('id');
    PageReference pageRef = new PageReference('/' + objContact.Id);
     pageRef.setRedirect(true);
      return pageRef;
      }
    

Test Class : 

@isTest 
private Class ContactUpdateServerTest{
static testMethod void test1()
    {
        Contact objContact = new Contact(lastname = 'test',firstname = 'firstTest', title ='titletest',type__c = 'type',SSO_Number__c = '502066194');
        insert objContact;
     
       Test.startTest();
       ContactUpdateServer obj = new ContactUpdateServer(new ApexPages.StandardController(objContact));
      ApexPages.currentPage().getParameters().put(obj.currentRecordId,objContact.id);
       
       system.assertequals(objContact.SSO_Number__c.Length(),9);
       // string searchstring = objContact.SSO_Number__c;
      //  string currentRecordId = objContact.Id;
        

     Test.stopTest();
    }
 
   Static TestMethod  void test2(){
   Contact objContact = new Contact(lastname = 'test',firstname = 'firstTest', title ='titletest',type__c = 'type',SSO_Number__c = '502066194');
        insert objContact;
   
   test.startTest();
   
            ApexPages.StandardController sc = new ApexPages.standardController(objContact);

               ContactUpdateServer obj = new ContactUpdateServer(sc);
               
                PageReference pageRef = obj.Goback();
                  Test.setCurrentPage(pageRef);
                  pageRef.getParameters().put('id',objContact.id);
            
            obj.GoBack();
            
            System.assertNotEquals(null,pageRef);

        test.stopTest();

   }
}


Please suggest where i am going wrong -- I am getting an error "List has no rows for assignment to SObject". 
Hi, 

 Need a help in one of the strange error am getting in the below controller calling this from visualforce page. 

Below is the error am getting while loading the visualforce page 

System.NullPointerException: Argument 1 cannot be null 
Class.ShareForecastController.getRoles: line 37, column 1​

Please suggest me how to fix this error. 


Class
public with sharing class ShareForecastController {

    public List<User> users {get;set;}
    private String soql {get;set;}
    private Map<Id,User> rolesMap;
    private String userId;
    private String userRoleId = '';
	private Set<Id> alreadySharedUserIds;

    public String shareToUserId {
        get  { if (shareToUserId == null) {  shareToUserId = ''; } return shareToUserId;  }
        set;
    }

    public String sortDir {
        get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
        set;
    }

    public String sortField {
        get  { if (sortField == null) {sortField = 'UserRole.name'; } return sortField;  }
        set;
    }

    public string getSelectedRole(){
         return userRoleId ;
    }

    public void setSelectedRole(String s){
        this.userRoleId  = s;
    }

    public list<SelectOption>getRoles(){
        list<SelectOption> options = new list<SelectOption>();
        options.add(new SelectOption('-- Select Role --', '-- Select Role --', true));
        for(User obj : rolesMap.values()) {
            options.add(new SelectOption(obj.UserRoleId,obj.UserRole.name));
        }
         return options;
    }
	
	public ShareForecastController() {
		alreadySharedUserIds = new Set<Id>();
        users = new List<User>();
        userId = userInfo.getUserId();
        userRoleId = userInfo.getUserRoleId();
		
		for(Custom_Forecast_Share__c obj : [Select id,Name,Forecast_Shared_To__c from Custom_Forecast_Share__c where isActive__c  = true]) {
			alreadySharedUserIds.add(obj.Forecast_Shared_To__c);
		}
		
        soql = 'SELECT Id,FirstName,LastName,UserRoleId,UserRole.name,UserRole.ParentRoleId FROM User WHERE Id Not IN :alreadySharedUserIds AND IsActive = True AND ForecastEnabled = True';
        runQuery();
        rolesMap = new Map<Id,User>();
        for(User obj : users) {
            rolesMap.put(obj.UserRoleId,obj);
        }
    }

    public void toggleSort() {
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
        runQuery();
    }

    public void toggleRole() {
        system.debug('In toggleRole userRoleId: '+userRoleId);
        soql = 'SELECT Id,FirstName,LastName,UserRoleId,UserRole.name,UserRole.ParentRoleId FROM User WHERE Id Not IN :alreadySharedUserIds AND IsActive = True AND ForecastEnabled = True AND UserRoleId = :userRoleId';
        runQuery();
    }

    public void runQuery() {
        try {
            users = Database.query(soql + ' AND id != :userId order by ' + sortField + ' ' + sortDir+ ' LIMIT 999');
            system.debug('Final Query'+soql + ' AND id != :userId order by ' + sortField + ' ' + sortDir);

            if(users.size() <= 0) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'No records were found based on your criteria'));
            }
        } catch (Exception e) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'+e.getMessage()));
        }
    }

    public PageReference runSearch() {

        String Name = Apexpages.currentPage().getParameters().get('name');

        soql = 'SELECT Id,FirstName,LastName,UserRole.name FROM User WHERE IsActive = True AND ForecastEnabled = True';
        if (!Name.equals(''))
            soql += ' AND Name LIKE \'%'+String.escapeSingleQuotes(Name)+'%\'';

        runQuery();

        return null;
    }

    public PageReference shareForecast() {
        try{
            Custom_Forecast_Share__c ojb = new Custom_Forecast_Share__c(
                Forecast_Owner__c = userId,
                Forecast_Shared_To__c = shareToUserId,
                isActive__c = true
            );
            insert ojb;
        } catch(Exception e) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops! Something went wrong.'));
            return null;
        }

        PageReference pg = Page.Forecasting;
        pg.setRedirect(true);
        return pg ;
    }    

}

Visual Force Page. 
<apex:page controller="ShareForecastController" sidebar="false" title="Share Forecast" tabStyle="Custom_Forecast__tab">
   <apex:form >
      <apex:pageMessages id="errors" />
      
         <apex:sectionHeader title="Share Forecast" subtitle="Share your forecast"/>

         <table width="100%" border="0">
            <tr>
               <td width="200" valign="top">
                  <apex:pageBlock title="Search" mode="edit" id="criteria">
                     <script type="text/javascript">
                        function doSearch() {
                            var Name = document.getElementById("Name").value;
                            //console.log(Name );

                            if(Name == '') {
                                alert('Please enter your search criteria.');
                                return false;
                            }else{
                                searchServer(
                                    document.getElementById("Name").value
                                );
                            }
                        }
                     </script> 
                     <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,errors">
                        <apex:param name="Name" value="" />
                     </apex:actionFunction>
                     <table cellpadding="2" cellspacing="2">
                        <tr>
                           <td style="font-weight:bold;">Name<br/>
                              <input type="text" id="Name"/>
                           </td>
                        </tr>
                        <tr>
                           <td style="font-weight:bold;">
                               <apex:commandButton value="Search" onclick="doSearch();" reRender="forRerender" status="searchStatus"/>
                               <apex:inputHidden id="forRerender"/>
                               <apex:actionStatus startText="Searching..." id="searchStatus">
                                   <apex:facet name="stop"></apex:facet>
                               </apex:actionStatus>
                           </td>
                        </tr>
                     </table>
                  </apex:pageBlock>
               </td>
               
               <td valign="top">
                  <apex:pageBlock mode="edit" id="results">
                      <apex:pageBlockSection >
                          <apex:pageblockSectionItem >
                              <apex:outputLabel >Roles:&nbsp;</apex:outputLabel>
                              <apex:selectlist value="{!SelectedRole}" size="1">
                                 <apex:actionSupport event="onchange" action="{!toggleRole}" rerender="results"/>
                                 <apex:selectOptions value="{!Roles}"  />
                              </apex:selectlist>
                          </apex:pageblockSectionItem>
                      </apex:pageBlockSection>

                    <apex:pageBlockTable value="{!users}" var="user" rendered="{!users.size>0}">
                        <apex:column >
                           <apex:facet name="header">
                              <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results">
                                 <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                              </apex:commandLink>
                           </apex:facet>
                           <apex:outputField value="{!user.firstName}"/>
                        </apex:column>
                        <apex:column >
                           <apex:facet name="header">
                              <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results">
                                 <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                              </apex:commandLink>
                           </apex:facet>
                           <apex:outputField value="{!user.lastName}"/>
                        </apex:column>
                        <apex:column >
                           <apex:facet name="header">
                              <apex:commandLink value="Role" action="{!toggleSort}" rerender="results">
                                 <apex:param name="sortField" value="UserRole.Name" assignTo="{!sortField}"/>
                              </apex:commandLink>
                           </apex:facet>
                           <apex:outputField value="{!user.UserRole.name}"/>
                        </apex:column>
                        <apex:column headerValue="Action" width="100">
                            <apex:commandLink value="Share Forecast" action="{!shareForecast}" reRender="errors">
                                <apex:param name="shareToUserI" value="{!user.Id}" assignTo="{!shareToUserId}"/>
                            </apex:commandLink>
                        </apex:column>
                     </apex:pageBlockTable>
                  </apex:pageBlock>
               </td>
            </tr>
         </table>
   </apex:form>
</apex:page>

 
Hello Guys ,

i am confused with the sub query concept in triggers can any one explain me the sub query concept
for eg:
select id,(select id from opportunities) from Account where id IN: Trigger.New

Thanks & Regards,
konda
 
Hello ,

I am trying to create an opportunity using triggers when an account is created .

i have executed  following code but i was unable to create the account
CODE:
trigger createopportunity on Account (after insert) {
list<opportunity> opp=new list <opportunity>();
for( account acc :trigger.new){
opportunity oppt=new opportunity();
oppt.Name = acc .Name;
oppt.Accountid = acc .id;
oppt.StageName= 'proposal';
 oppt.CloseDate = System.today() + 30;
 opp.add(oppt);
}
 if (opp.isEmpty() == false) {
 Database.update(opp);
        }
        }

ERROR:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger createopportunity caused an unexpected exception, contact your administrator: createopportunity: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: Trigger.createopportunity: line 12, column 1

please help me with your suggestions
Hi,
I have been struggling with this piece of apex for the last few days  - had considered using batchable context but was struggling to get my head around it. So, I am persevering with a schedulable piece of code - its not very elegant but initial testing on volume data indicates it won't blow the dml or cpu limits ( now that I am not doing a nested loop )  - what I am struggling with is the syntax to assign my values I have loaded in the Sobject to my list. Would someone be able to point me in the right direction?
My code is:
 
Global class RefreshScheduleMirror  implements Schedulable {

      global void execute(SchedulableContext SC) {

      RefreshSchedule();
   }

    public void RefreshSchedule()  {
    
    /// Delete the old mirror records ///

	ScheduleMirror__c[] doomedMirrors = [SELECT Name FROM ScheduleMirror__c]; 
		try {
  	delete doomedMirrors;
	} catch (DmlException e) {
    // Process exception here
    }
       /// use generic object to pull combined line item and schedule records 
        SObject[] allSchedules = [ SELECT  CurrencyIsoCode, OpportunityLineItemId, ScheduleDate,    Revenue,Quantity, Type, Description, OpportunityLineItem.Name, OpportunityLineItem.OpportunityId, 
                                  OpportunityLineItem.Product2Id, OpportunityLineItem.ProductCode 
                                  FROM OpportunityLineItemSchedule];  
        
        SObject IsoCode = getSObject('CurrencyIsoCode');
        
        /// Create new list to store the records ( based on the structure defined by the custom object Schedule Mirror )
        List<ScheduleMirror__c> newmirrors = new List<ScheduleMirror__c>();
        
        /// for (OpportunityLineItem Schedule myschedule : allSchedules) {
        
        for (SObject myschedule : allSchedules) {
             
                // create variable 'mymirror' to hold the record values 
                 ScheduleMirror__c mymirror = new ScheduleMirror__c(); 
                 
                 mymirror.CurrencyIsoCode = myschedule.get(OpportunityLineItemSchedule.CurrencyIsoCode);
            	 mymirror.Name = myschedule.get('ScheduleDate.year() + '-' + myschedule.ScheduleDate.month() + '-' + myschedule.Name');
                 //mymirror.LineItemID__c = string.valueOf(myschedule.get('OpportunityLineItemId'));
				 //mymirror.Opportunity__c = string.valueOf(myschedule.get('OpportunityId'));
                 //mymirror.Schedule_Amount__c = string.valueOf(myschedule.get('Revenue'));
                 //mymirror.Schedule_Date__c =  string.valueOf(myschedule.get('ScheduleDate'));   
                 //mymirror.Schedule_Description__c = string.valueOf(myschedule.get('Description'));
                 //mymirror.Schedule_Quantity__c = string.valueOf(myschedule.get('Quantity'));
				 //mymirror.Schedule_Type__c = string.valueOf(myschedule.get('Type'));
				 //mymirror.Schedule_Type__c = string.valueOf(myschedule.get('Product2Id'));
				 //mymirror.Product_Code__c = string.valueOf(myschedule.get('ProductCode'));
                 //mymirror.Name = string.valueOf(myschedule.get('Name'));


            // Update the list with all the records retrieved in the for loop
             newmirrors.add(mymirror);

                }
             // update database outwith the for loop!!!!     
     		 upsert newmirrors;  
                 
    }       
}

it is where I am building up the list " ScheduleMirror__c mymirror = new ScheduleMirror__c(); "  that I have my issue:
mymirror.CurrencyIsoCode = myschedule.get(OpportunityLineItemSchedule.CurrencyIsoCode); 
mymirror.Name = myschedule.get('ScheduleDate.year() + '-' + myschedule.ScheduleDate.month() + '-' + myschedule.Name');

My basic issue for example, is that I am trying to map mymirror.currencyIsoCode  to the field CurrencyIsoCode from my SObject  - I can't work out the syntax for this.
Secondly, once I get that resolved, I need to be able to build mymirror.Name  by concatenating the year,  month ( from the ScheduleDate  ) and the Name  from the SObject.

Any help would be appreciated.

Thanks
Dave
  • October 13, 2016
  • Like
  • 0
Hello,

i am using field BillingAddress from Account but its alwaoys giing error when creating new account, in apex class its not giving error,

If i need to use city, zip code for for comparing account; which field can i use
  • November 08, 2016
  • Like
  • 0
Hi all,

public with sharing class SimpleErrorController { }

In the above code what is the with sharing..
Here is apex class:
public class SampleController {
    public Interest__c interest {get;set;}
    public Member__c member {get;set;}
    public SampleController(){
        interest = new Interest__c();
    }
    
    public void fetchMemberDetails(){
        member = [SELECT Name FROM Member__c WHERE Id = : interest.Member__c];
        interest.Member_Name__c = member.Name;
    }
}
I am not a JS developer so I'm struggling to get my head around this.  

I am bulding a JS OnClick button that updates the Owner field in a custom object to a queue.  

Here's the code:
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")} 

var SupportRequestObj = new sforce.SObject("SupportRequest__c"); 
SupportRequestObj.Id = '{!SupportRequest__c.Name}'; 
SupportRequestObj.OwnerId = '00G50000001dv2s'; 
var result = sforce.connection.update([SupportRequestObj]); 
window.location.href=window.location.href;

The custom object's API name is SupportRequest__c and the Object Name is SupportRequest.

The Syntax comes back clean but when the button is clicked there's nothing. No error. No update to the owner field.  

What am I doing wrong?
Hi,
I'm trying to create a formula field to round up to either 1.00 or 1.50 or 2.00 or 3.00.  There will not ever be anything over 
The formula field is as follows: ROUND(X10Min_ofHours__c + X15Min_ofHours__c + X20Min_ofHours__c + X45Min_ofHours__c,1)

These are driven by products selected and rounds into minutes.  Example of roll-up: if .80, then it should display 1.00, and if 1.10, than it should show up as 1.50 and if it shows 1.60, it should show as 2.00 and if it shows 2.10 or anything over, it will all round up/down to 3.00  So it's a roundup.  How can I configure this formula field.
Hi All,

I have created a Visual force page for site user . so whenever i insert record on site ,it will give a error message and record is not inserted  .However when i click on preview visualforce and insert the data the record gets inserted. Can Anyone tell me the problem??
Hi,
can any one help test class for following trigger
trigger CaseMilestone on Case (after update) {
    try{        
        set <Id> caseIds =new  set <Id>();
        list<Commision__c> Comlist =new  list<Commision__c>();        
        for(case c:trigger.new)
        {
            if(c.Status == 'closed' && c.Milestone_Approval_Status__c ==TRUE){
                caseIds.add(c.id);  
            }
        } 
        system.debug('caseIds :'+caseIds);
        
        List<CaseMilestone> cmsToUpdate = [select Id, completionDate,MilestoneTypeId,CreatedById,BusinessHoursId,CaseId,ElapsedTimeInDays,ElapsedTimeInHrs,IsCompleted,IsViolated  from CaseMilestone cm  where caseId in :caseIds /* and cm.MilestoneType.Name=:Milestone2 */ and completionDate != null limit 1];
        system.debug('cmsToUpdate :'+cmsToUpdate); 
        for(CaseMilestone cm :cmsToUpdate)
        {
            Commision__c com = new Commision__c();
            com.Case__c = cm.CaseId;
            com.OwnerId =cm.CreatedById;
            com.Owner__c=cm.CreatedById;
            com.IsCompleted__c=cm.IsCompleted;
            com.CompletionDate__c=cm.completionDate;   
            com.Milestone_Name__c=cm.MilestoneTypeId;
            Comlist.add(com);
        }
        insert Comlist;
           
        system.debug('Comlist :'+Comlist); 
    }
    catch (Exception e){
        system.debug('Exeption ::'+e + 'Line Number ::' +e.getLineNumber() + 'getCause ::' +e.getCause()+ 'getMessage ::'+e.getMessage());
    }
}

Thanks,
when i save my trigger i m getting this error
ERROR ::: Method does not exist or incorrect signature: op_trigger.op_check(List<Opportunity>) at line 2 column 1

this my trigger code

trigger trigger_1 on Opportunity (before insert, before update) {
op_trigger.op_check(Trigger.New);
}



this is my class code

public class op_trigger
{
    public void op_check(List<Opportunity> ops)
        {
            Double Total_Amount = 0 ;
            for(Opportunity o1 : [select amount from Opportunity where CreatedDate = Today AND CreatedByID = :UserInfo.getUserID()])

                                    {
                                        Total_Amount = Total_Amount + o1.Amount;
                                    }
                                    
          for(Opportunity o2 : ops)
          {
              Total_Amount = Total_Amount + o2.Amount;
              
              if(Total_Amount > 1000000)
              o2.addError('out of Limit');
          }                          
        }

}
I have written a trigger to clone/copy a record from Custom object "Student__c" (when a new student is created or modified)  to Account (Person Account) and it works, I am not sure on how to write a test class to increase the code coverage, please help.  The trigger is as below:

trigger CreatePersonAccountfromStudent on Student__c (after insert,after update)
{
    List<account> acc=new List<account>();
    for(student__c stud:Trigger.New)
    {
        acc.add(new account(
               LastName=Stud.name__c,
               recordtypeid='012O00000009RtPIAU',
               Autocreated__pc=True,
               PersonBirthdate=Stud.DOB__c,
               Current_Acedamic_Year__pc=Stud.Current_Acedamic_Year__c,
               Date_of_Collection__pc=Stud.Date_of_Collection__c,
               Discount_Percentage__pc=Stud.Discount_Percentage__c,
               Discount_Policy__pc=Stud.Discount_Policy__c,
               Discount_Remarks__pc=Stud.Discount_Remarks__c,
               Discount_Type__pc=Stud.Discount_Type__c,
               English__pc=Stud.English__c,
               Exclude_Registration__pc=Stud.Exclude_Registration__c,
               Father_Email__pc=Stud.Father_Email__c,
               Father_Name__pc=Stud.Father_Name__c,
               Father_NRIC__pc=Stud.Father_NRIC__c,
               Father_Office_Phone__pc=Stud.Father_Office_Phone__c,
               Father_Primary_Contact__pc=Stud.Father_Primary_Contact__c,
               Father_Remark__pc=Stud.Father_Remark__c,
               Father_Staff__pc=Stud.Father_Staff__c,
               Gender__pc=Stud.Gender__c,
               GEP__pc=Stud.GEP__c,
               Guardian_Email__pc=Stud.Guardian_Email__c,
               Guardian_Mobile__pc=Stud.Guardian_Mobile__c,
               Guardian_Name__pc=Stud.Guardian_Name__c,
               Guardian_NRIC__pc=Stud.Guardian_NRIC__c,
               Guardian_Office_Phone__pc=Stud.Guardian_Office_Phone__c,
               Guardian_Primary_Contact__pc=Stud.Guardian_Primary_Contact__c,
               Guardian_Relationship__pc=Stud.Guardian_Relationship__c,
               Guardian_Remarks__pc=Stud.Guardian_Remark__c,
               Guardian_Staff__pc=Stud.Guardian_Staff__c,
               PersonHomePhone=Stud.Home_No__c,
               Is_Mind_Stretcher_Staff_Mother__pc=Stud.Is_Mind_Stretcher_Staff_Mother__c,
               Level__pc=Stud.Level__c,
               Level_Promoted_DateTime__pc=Stud.Level_Promoted_DateTime__c,
               PersonMailingStreet=Stud.Unit_Number__c+' '+Stud.Block__c+' '+Stud.Street__c+' '+Stud.Postal_Code__c,
               Maths__pc=Stud.Maths__c,
               Mobile_No_Father__pc=Stud.Mobile_No_Father__c,
               Mother_Email__pc=Stud.Mother_Email__c,
               Mother_Name__pc=Stud.Mother_Name__c,
               Mother_No_Mobile__pc=Stud.Mobile_No_Mother__c,
               Mother_NRIC__pc=Stud.Mother_NRIC__c,
               Mother_Office_Phone__pc=Stud.Mother_Office_Phone__c,
               Mother_Primary_Contact__pc=Stud.Mother_Primary_Contact__c,
               Mother_Remark__pc=Stud.Mother_Remark__c,
               Mother_Staff__pc=Stud.Mother_Staff__c,
               MS_Start_Kit_Bag__pc=Stud.MS_Start_Kit_Bag__c,
               Nationality__pc=Stud.Nationality__c,
               NRIC__pc=Stud.NRIC__c,
               NTUC_10_Discount__pc=Stud.NTUC_10_Discount__c,
               NTUC_Card_Expiry__pc=Stud.NTUC_Card_Expiry__c,
               NTUC_Remark__pc=Stud.NTUC_Remark__c,
               Others__pc=Stud.Others__c,
               Person_Contact__pc=Stud.Person_Contact__c,
               Primary_Contact_Number__pc=Stud.Contact_number__c,
               Primary_Email__pc=Stud.Primary_Email__c,
               Primary_Name__pc=Stud.Primary_Name__c,
               Primary_Remark__pc=Stud.Primary_Remark__c,
               Promotion__pc=Stud.Promotion__c,
               Reading_Oceans_Email__pc=Stud.Reading_Oceans_Email__c,
               Reading_Oceans_End_Date__pc=Stud.Reading_Oceans_End_Date__c,
               Reading_Oceans_Start_Date__pc=Stud.Reading_Oceans_Start_Date__c,
               Reading_Oceans_Subscrip__pc=Stud.Reading_Oceans_Subscrip__c,
               Registraation_Centre__pc=Stud.Registration_Centre__c,
               Related_Centres__pc=Stud.Related_Centres__c,
               Remarks__pc=Stud.Remarks__c,
               RO_Date_Send_User__pc=Stud.RO_Date_Send_User__c,
               RO_Type__pc=Stud.RO_Type__c,
               Safra_Card_Expiry__pc=Stud.Safra_Card_Expiry__c,
               Safra_Card_Holding__pc=Stud.Safra_Card_Holding__c,
               Safra_Remark__pc=Stud.Safra_Remark__c,
               Salesforce_Id_from_Student_Object__pc=Stud.ID,
               School__pc=Stud.School__c,
               Science_Percentage__pc=Stud.Science__c,
               Secondary_Stream__pc=Stud.Secondary_Stream__c,
               Student_Id_from_Student_Prospects__pc=Stud.name,
               Student_Old_Reference_ID__pc=Stud.Student_Old_Reference_ID__c,
               Student_Status__pc=Stud.Student_Status__c,
               Student_Type__pc='Student',
               Tick_to_activate_inter_branch_discount__pc=Stud.Tick_to_activate_inter_branch_discount__c
               ));
    }
    insert acc;
}
  • October 18, 2016
  • Like
  • 0
Hello salesforce developpers!

I have an understanding issue with events/activities in Salesforce: I must insert event data in salesforce from an ERP using Talend.

During Talend insertion, I see the processed IDs in the logs. When searching for this ID by typing "https://eu5.salesforce.com/<ID>", I see the corresponding event and all its details. Seems fine.

However, when searching in developper console (SOQL) like this:
Select Id, Subject from event where Id = '<ID>'

... No event found.

Could someone explain to me why I do not see the event in console? is it stored in another table? (i've also searched in Activity table without much success).

Best regards, and thanks in advance!
Hi -- 
I am receiving this error: Invalid field Restaurant__ID__c for SObject Account

Here is a partial copy of the critical lines of code in my controller:

 public ObjectStructureMap[] formatObjectStructure( String currentId ){
    
        List<ObjectStructureMap> asm = new List<ObjectStructureMap>{};
        masm.clear();

        //Change below
        List<Account> al            = new List<Account>{};
        List<ID> currentParent      = new List<ID>{};
        Map<ID, String> nodeList    = new Map<ID, String>{};
        List<String> nodeSortList   = new List<String>{};
        List<Boolean> levelFlag     = new List<Boolean>{};
        List<Boolean> closeFlag     = new List<Boolean>{};
        String nodeId               = '0';
        String nodeType             = 'child';
        Integer count               = 0;
        Integer level               = 0;
        Boolean endOfStructure      = false;
        
        //Find highest level obejct in the structure
        currentParent.add( GetTopElement( currentId ) );

        //Loop though all children
        while ( !endOfStructure ){

            if( level == 0 ){
                //Change below     
                al = [ SELECT a.Type, a.Site, a.ParentId, a.OwnerId,a.Restaurant_ID__c,a.Name,a.Deck_Rank__c, a.Market_Area__c,a.Lead_List__c,a.Phone,a.GPV_30_days__c,a.LastActivityDate,a.Account_Type__c,a.Lead_Type__c,a.Owner.Alias, a.Id FROM Account a WHERE a.id IN : CurrentParent ORDER BY a.Name ];
            } 
            else {
                //Change below      
                al = [ SELECT a.Type, a.Site, a.ParentId, a.OwnerId,  a.Restaurant_ID__c,a.Name,a.Deck_Rank__c, a.Market_Area__c,a.Lead_List__c,a.Phone,a.GPV_30_days__c,a.LastActivityDate,a.Account_Type__c,a.Lead_Type__c,a.Owner.Alias, a.Id FROM Account a WHERE a.ParentID IN : CurrentParent ORDER BY a.Name ];
            }

            if( al.size() == 0 ){
                endOfStructure = true;
            }
            else{
                currentParent.clear();
                for ( Integer i = 0 ; i < al.size(); i++ ){
                    //Change below
                    Account a = al[i];
                    nodeId = ( level > 0 ) ? NodeList.get( a.ParentId )+'.'+String.valueOf( i ) : String.valueOf( i );
                    masm.put( NodeID, new ObjectStructureMap( nodeID, levelFlag, closeFlag, nodeType, false, false, a ) );
                    currentParent.add( a.id );
                    nodeList.put( a.id,nodeId );
                    nodeSortList.add( nodeId );
                }
                
                maxLevel.add( level );                
                level++;
            }
        }
        
        //Account structure must now be formatted
        NodeSortList.sort();
        for( Integer i = 0; i < NodeSortList.size(); i++ ){
            List<String> pnl = new List<String> {};
            List<String> cnl = new List<String> {};
            List<String> nnl = new List<String> {};
            
            if ( i > 0 ){
                String pn     = NodeSortList[i-1];
                pnl         = pn.split( '\\.', -1 );
            }

            String cn     = NodeSortList[i];
            cnl         = cn.split( '\\.', -1 );

            if( i < NodeSortList.size()-1 ){
                String nn = NodeSortList[i+1];
                nnl = nn.split( '\\.', -1 );
            }
            
            ObjectStructureMap tasm = masm.get( cn );
            if ( cnl.size() < nnl.size() ){
                //Parent
                tasm.nodeType = ( isLastNode( cnl ) ) ? 'parent_end' : 'parent';
            }
            else if( cnl.size() > nnl.size() ){
                tasm.nodeType     = 'child_end';
                tasm.closeFlag     = setcloseFlag( cnl, nnl, tasm.nodeType );
            }
            else{
                tasm.nodeType = 'child';
            }
            
            tasm.levelFlag = setlevelFlag( cnl, tasm.nodeType ); 
            
            //Change below
            if ( tasm.account.id == currentId ) {
                tasm.currentNode = true;
            }
            asm.add( tasm );
        }
        
        asm[0].nodeType             = 'start';
        asm[asm.size()-1].nodeType     = 'end';
        
        return asm;
    }
    

and here is the relevant chunk of my visualforce page:

  <apex:outputLink value="/{!pos.account.id}" style="{!IF(pos.currentNode,'font-weight: bold;','')}" styleClass="columnHeadActiveBlack" target="_top">{!pos.account.name}</apex:outputLink>

<!-- Include the following if you uses sites with accounts -->
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.account.Restaurant__ID__c}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.account.Deck_Rank__c}"rendered="{!IF(pos.account.Deck_Rank__c!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.account.Lead_List__c}" rendered="{!IF(pos.Lead_List__c!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.Phone}" rendered="{!IF(pos.Phone!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.GPV_30_days__c}" rendered="{!IF(pos.GPV_30_days__c!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.LastActivityDate}" rendered="{!IF(pos.LastActivityDate!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.Account_Type__c}" rendered="{!IF(pos.Account_Type__c!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.Lead_Type__c}" rendered="{!IF(pos.Lead_Type__c!= '', true, false)}"/>
            <apex:outputText style="{!IF(pos.currentNode,'font-weight: bold;','')}" value=", {!pos.Owner.Alias}" rendered="{!IF(pos.Owner.Alias!= '', true, false)}"/>&nbsp;
<!-- Stop -->
            </span>
            <div> </div>
            <apex:outputText rendered="{!IF(OR(pos.nodeType=='child_end',pos.nodeType=='child'),false,true)}">
                <div id='{!pos.nodeId}'>
            </apex:outputText>
            <apex:outputText rendered="{!IF(OR(pos.nodeType=='child_end',pos.nodeType=='child'),true,false)}">
                <div id='{!pos.nodeId}'><apex:image url="/s.gif" alt="" width="1" height="1"/></div>
            </apex:outputText>
            <apex:repeat value="{!pos.closeFlag}" var="close">
                </div>
            </apex:repeat>            


Can someone help me here?