• v varaprasad
  • SMARTIE
  • 1608 Points
  • Member since 2015
  • Salesforce Developer

  • Chatter
    Feed
  • 51
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 414
    Replies
Hi,

I am stuck at this challange. 

-Create an Apex class that returns an array (or list) of strings.
-Create an Apex class that returns an array (or list) of formatted strings ('Test 0', 'Test 1', ...). The length of the array is determined by an integer parameter.
-The Apex class must be called 'StringArrayTest' and be in the public scope.
-The Apex class must have a public static method called 'generateStringArray'.
-The 'generateStringArray' method must return an array (or list) of strings. Each string must have a value in the format 'Test n' where n is the index of the current string in the array. The number of returned strings is specified by the integer parameter to the 'generateStringArray' method.
I am getting test errors from the Apex for Xero API (https://github.com/benedwards44/Apex-for-Xero) when trying to use HTTPCalloutMock  - System.NullPointerException: Attempt to de-reference a null object 

Stack Trace:
Class.XeroCalloutUtility.executeCallout: line 33, column 1
Class.XeroAccountingApi.getContacts: line 20, column 1
Class.XeroAccountingApiTest.getContactsSuccess: line 21, column 1

This is the test class, the full code can be seen on GitHub link above. 

I have raised an issue with the developer, but I wondered if anyone could give me any pointers.
 
/**
* @author       Ben Edwards (ben@benedwards.co.nz)
* @description  Test class for the Xero API methods
**/
@isTest
public class XeroAccountingApiTest {

	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test a successful callout of the getContacts() method
	**/
	@isTest
	static void getContactsSuccess () {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(200, 'XeroContactsMock'));

		Test.startTest();

		// Execute the callout
		List<XeroContact> xeroContacts = XeroAccountingApi.getContacts();

		Test.stopTest();

		// Assert that a contact exists
		system.assertEquals(
			1,
			xeroContacts.size(),
			'There should be one contact returned from the callout'
		);
	}


	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test an unsuccessful callout of the getContacts() method
	**/
	@isTest
	static void getContactsFail () {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(500, 'XeroContactsMock'));

		Test.startTest();

		// Execute the callout
		try {

			List<XeroContact> xeroContacts = XeroAccountingApi.getContacts();
		} 
		catch (Exception ex) {

			// Error expected, as failed callout raises an exception
			system.assert(
				String.valueOf(ex).contains('500'),
				'The 500 error code should be contained in the string.'
			);
		}

		Test.stopTest();
	}

	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test a successful callout of the createContact() method
	**/
	@isTest
	static void createContactSuccess () {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(200, 'XeroContactsMock'));

		Test.startTest();

		// Execute the callout
		XeroContact createdContact = XeroAccountingApi.createContact('<Contact><Name>Test Contact</Name></Contact>');

		Test.stopTest();

		// Assert that a contact exists
		system.assertNotEquals(
			null,
			createdContact,
			'The contact should be created and not null.'
		);
	}


	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test an unsuccessful callout of the createContact() method
	**/
	@isTest
	static void createContactsFail () {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(500, 'XeroContactsMock'));

		Test.startTest();

		// Execute the callout
		try {

			XeroContact createdContact = XeroAccountingApi.createContact('<Contact><Name>Test Contact</Name></Contact>');
		} 
		catch (Exception ex) {

			// Error expected, as failed callout raises an exception
			system.assert(
				String.valueOf(ex).contains('500'),
				'The 500 error code should be contained in the string.'
			);
		}

		Test.stopTest();
	}

	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test a successful callout of the getInvoices() method
	**/
	@isTest
	static void getInvoicesSuccess() {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(200, 'XeroInvoicesMock'));

		Test.startTest();

		// Execute the callout
		List<XeroInvoice> xeroInvoices = XeroAccountingApi.getInvoices();

		Test.stopTest();

		// Assert that a contact exists
		system.assertEquals(
			1,
			xeroInvoices.size(),
			'There should be one invoice returned from the callout'
		);
	}


	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test an unsuccessful callout of the getInvoices() method
	**/
	@isTest
	static void getInvoicesFail() {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(500, 'XeroInvoicesMock'));

		Test.startTest();

		// Execute the callout
		try {

			List<XeroInvoice> xeroInvoices = XeroAccountingApi.getInvoices();
		} 
		catch (Exception ex) {

			// Error expected, as failed callout raises an exception
			system.assert(
				String.valueOf(ex).contains('500'),
				'The 500 error code should be contained in the string.'
			);
		}

		Test.stopTest();
	}

	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test a successful callout of the getInvoicesForContact() method
	**/
	@isTest
	static void getInvoicesForContactSuccess() {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(200, 'XeroInvoicesMock'));

		Test.startTest();

		// Execute the callout
		List<XeroInvoice> xeroInvoices = XeroAccountingApi.getInvoicesForContact('ABC123');

		Test.stopTest();

		// Assert that a contact exists
		system.assertEquals(
			1,
			xeroInvoices.size(),
			'There should be one invoice returned from the callout'
		);
	}

	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test a successful callout of the createInvoice() method
	**/
	@isTest
	static void createInvoiceSuccess() {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(200, 'XeroInvoicesMock'));

		Test.startTest();

		// Execute the callout
		XeroInvoice createdInvoice = XeroAccountingApi.createInvoice('<Invoice>BODY</Invoice>');

		Test.stopTest();

		// Assert that a contact exists
		system.assertNotEquals(
			null,
			createdInvoice,
			'There should be one invoice created from the callout'
		);
	}


	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test an unsuccessful callout of the createInvoice() method
	**/
	@isTest
	static void createInvoiceFail() {

		// Set the Mock Class for the callout
		Test.setMock(HttpCalloutMock.class, getStaticMock(500, 'XeroInvoicesMock'));

		Test.startTest();

		// Execute the callout
		try {

			XeroInvoice createdInvoice = XeroAccountingApi.createInvoice('<Invoice>BODY</Invoice>');
		} 
		catch (Exception ex) {

			// Error expected, as failed callout raises an exception
			system.assert(
				String.valueOf(ex).contains('500'),
				'The 500 error code should be contained in the string.'
			);
		}

		Test.stopTest();
	}

	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test scenario where no Xero Settings can be found
	**/
	@isTest
	static void getXeroSettingsError() {

		// Delete the Xero Settings created
		delete [Select Id From Xero_Settings__c];

		// Assert no Xero Settings found in Utility
		system.assertEquals(
			null,
			XeroCalloutUtility.xeroSettings.Id,
			'There should be no Xero Setting record found.'
		);

	}


	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Test an unsuccessful callout of the getContacts() method
	**/
	private static StaticResourceCalloutMock getStaticMock (Integer responseCode, String mockName) {

		StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
		mock.setStaticResource(mockName);
		mock.setStatusCode(responseCode);
		mock.setHeader('Content-Type', 'application/json');

		return mock;
	}


	/**
	* 	@author Ben Edwards (ben@benedwards.co.nz)
	*	@description Create test data for the method
	**/
	@testSetup
	static void setupTestData () {

		// Create a test Xero Setting record
		insert new Xero_Settings__c(
			SetupOwnerId = Userinfo.getOrganizationId(),
			Consumer_Key__c = '123456789',
			Endpoint__c = 'https://api.xero-test.com?param1=value1&param2=value2/'
		);

	}
	
}

 

HI All,

Need to query the data that's displayed here

As you can see the image above, It's list of records from Activity List View. How can I query all the TASK records that are getting displayed in this ListView.

Trying to implement, this functionality because, LEX doesn't support Activity List View

Thanks in advance!

wanted to count total number of records 

public List<Contact> contactsize = new List<Contact>();
     global void execute(Database.BatchableContext bc,  List<Contact> Scope){
          conupdate = new List<Contact>();
       system.debug('calling update check execute');
    
       For(Contact c: Scope){  
            c.Direct_send__c= true;
              conupdate.add(c);   
           }
       system.debug('contact list' + conupdate.size());  
         contactsize.addAll(conupdate);
         update conupdate;
     }  
    global void finish(Database.BatchableContext bc){
     system.debug('contacts size :' + contactsize.size());
        recordcount = contactsize.size();
Hello everyone, I successfully create a form of record views of users and now cannot deploy in my production org without a test class. I've searched all day for a sample test that can help explain what I am to do, no luck!

Here is my class code:
 
public class lastViewed{
 
    public Datetime cDT; 
    public String LongDate; 
    public String firstname; 
    public String lastname;    
    public String userid;
 
    private final Chalkboard_Manager__c acct;
 
    public lastViewed(ApexPages.StandardController stdController) {
        this.acct = (Chalkboard_Manager__c)stdController.getRecord();    }
 
                public String getLongDate() {        
                cDT = System.now();        //Format the datetime value to your locale        
                LongDate = cDT.format('dd/MM/yyyy HH:mm');    return LongDate;    
            }
 
        public void updateField() {
        //Get the user info from the current user        
    firstname = System.Userinfo.getFirstName();        
    lastname = System.Userinfo.getLastName();       
    userid = System.Userinfo.getUserId();
 
        //Get the chalkboard record to be updated        
    Chalkboard_Manager__c a = [select Last_Viewed_By__c from Chalkboard_Manager__c where id = :acct.id limit 1];        
 
    //Assign values to Last Viewed By field & update the record        
    a.Last_Viewed_By__c = (firstname + ' ' + lastname + ', ' + getLongDate());        
    update a;    
    }
 
}

 
I am very new to writing triggers and would appreciate any and all help.  I have searched the forums to no avail, I am unable to find any information related to this particular scenario.  I do not want to go the roll up summary field route.

I have a custom object (related list) on which I would like to prevent the deletion of a record if checkbox=true on the related Opportunity record.
Hi All,

I have a batch class which retrieves user records and updates the users email. In my test class, I created 10 users and called the batch class. All good till here, but when I requery the user records to assert, it returns all the records from the org. This is strange to me. Could some explain me this behaviour. 
Batch class
/**
 * Created by darya on 1/2/2018.
 */

global class UpdateQAEmailsBatch implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {

        List<Id> profileIds = new List<Id>();
        List<String> profileNameStrings = new List<String>{'System Administrator','Profile B','Profile C'};
        for (Profile p :  [SELECT Id FROM Profile WHERE Name in: profileNameStrings])
        {
            profileIds.add(p.Id);

        }
        String[] emailFilters = new String[]
        {
                '%@company.com'
        };
        String query = 'SELECT Id, Name, Email, ProfileId FROM User WHERE Email like :emailFilters AND ProfileId NOT IN :profileIds';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<User> scope) {
        for (User usr : scope)
        {
            String email = usr.Email;
            email = email.replace('@', '=') + '@example.com';
            usr.Email = email;
        }
        update scope;
    }

    global void finish(Database.BatchableContext BC) {
        //TODO: Send Email
    }
}

Test class
/**
 * Created by darya on 1/3/2018.
 */
@isTest
public with sharing class UpdateQAEmailsBatchTest {

    @TestSetup static void setup() {

        List<User> users = new List<User>();
        List<Id> profileIds = new List<Id>();
        List<String> profileNameStrings = new List<String>{'Profile C','Profile D','Profile E','Profile F','Profile G','Profile H'};
        for (Profile p :  [SELECT Id FROM Profile WHERE Name in: profileNameStrings])
        {
            profileIds.add(p.Id);

        }

        for (Integer i = 0; i < 10; i++)
        {
            User user = new User(alias = 'testQA' + i,
                    email = 'testUserQAUpdate' + i + '@company.com',
                    LastName = 'testUserQAUpdate' + i,
                    Username = 'testUserQAUpdate' + i + '@company.com',
                    emailencodingkey = 'UTF-8',
                    languagelocalekey = 'en_US',
                    localesidkey = 'en_US',
                    profileid = profileIds[(math.random() * (profileIds.size())).intValue()],
                    country = 'United States',
                    IsActive = true,
                    CompanyName = 'Getinge France',
                    Getinge_Company__c = 'Getinge',
                    timezonesidkey = 'America/Los_Angeles');
            users.add(user);
        }
            insert users;
    }

    static testmethod void executeBatch() {

        UpdateQAEmailsBatch batch = new UpdateQAEmailsBatch();

        Test.startTest();
            Database.executeBatch(batch);
        Test.stopTest();
        List<User> users = [SELECT Id,Email FROM User];
        System.debug('Here its returns all the records from the Org. It should only return the above created 10 records');
        System.debug('users retrieved count: '+ users.size());
        for (User user : users)
        {
            System.debug('Id: ' + user.Id + '   Email:  ' + user.Email);
            Integer index = ((String) user.Email).indexOf('@');
            System.assertEquals(((String) user.Email).substring(index, index + 12), '@example.com');
        }
    }
}
Thanks in advance.
 
Hi All,
I have the followwing VF page and controller class
<apex:page standardController="test__c" extensions="Recordtypes" id="pg">
    <apex:form >
        <apex:pageBlock title="Recordtypes" id="pd">
            <apex:selectList size="1" value="{!RecordTypes}" >
                <apex:actionSupport event="onchange" reRender="panel1,panel2" />
                RecordTypes :  <apex:selectOptions value="{!RecordTypes}">
                
                </apex:selectOptions>
            </apex:selectList>
            <apex:outputPanel id="panel1">   
                  <apex:pageBlockSection rendered="{!RecordTypes=='R1'}" >
                     Field1 :  <apex:inputText />
                  </apex:pageBlockSection>
              </apex:outputPanel> 
            <apex:outputPanel id="panel2">   
                  <apex:pageBlockSection rendered="{!RecordTypes=='R2'}" >
                     Field2 :  <apex:inputText />
                  </apex:pageBlockSection>
              </apex:outputPanel> 
        </apex:pageBlock>
        
    </apex:form>
</apex:page>
 
public class Recordtypes {
    public list<selectoption> lstOfRectypes{set;get;}
    List<RecordType> recList;
    test__c t;
    ApexPages.StandardController controller;
    public Recordtypes (ApexPages.StandardController controller) {
        this.controller = controller;
        t = (test__c) Controller.getRecord();
        }
    public list<SelectOption> getRecordTypes() {
        list<SelectOption> options = new list<SelectOption>();
        for (list<RecordType> rts : [SELECT ID, name FROM RecordType WHERE SObjectType = 'test__c' ORDER BY name]) {
            for (RecordType rt : rts) {
                options.add(new SelectOption(rt.ID, rt.Name));
            } 
        }
        return options;
    }
    
}
I have written above code, to render VF page based on record type selection
when I am selecting selecting record type, VF page is not redering 
Please help me if any correction need to do for above code

Thanks in Advance
Hi All,
I am getting record types by using below list

List<RecordType> recList= new List<RecordType>([select id, name from recordtype where sobjecttype='obj1__c']);

I want to show this values in apex:select. How can I do this
I tried some ways, but not working.
Please help me

Thanks in Advance!!
hi all,

the soql in the following code is failing. Could somebody explain this to me.
Map<Id, String> profileIds = new Map<Id, String>();
profileIds.put('00eee000000xxxx','System Administrator');
profileIds.put('00eee00000yyyyy','YYY Profile');
profileIds.put('00eee00000zzzzz','ZZZ Profile');

List<User> users = [SELECT Id, Name, Email, ProfileId FROM User WHERE NOT(Email like '%@example.com') AND ProfileId NOT IN :profileIds.keySet()];
System.debug(users.size());
for (User usr: users)
{
    System.debug(usr.id+'    '+usr.Email);
}
Where i remove one of the clause from the where statement, it works.

Thanks.
 
I have a field on parent (Card Program__c) object i.e  card_processor_status__c  & have a Child (Solution_participation__c) Object which has Active__c checkbox Field I want to Update the Checkbox Field  Whenever the card_processor_status__c   changes to  either Active or Inactive .
I tried to update this with process builder But it is No Success .How we can Update this through Code? 
Challenge Not yet complete... here's what's wrong: 
Could not find the contact's name in the debug log. Be sure to run a query for your record, and to write your contact's name to the debug log using the System.debug() method.

I have this error in this unit any help would be great.

Thanks in advance.
Hey everyone,
I need some help converting my Apex trigger into a class. I am just unsure about the syntax differences between the trigger and class and I'm aware that I can't use trigger.new in the class. Do I need to create a new list to be able to use trigger.new? Any help or direction would be greatly appreciated!

Trigger:
trigger TotalAumUpdate on Account (after update) {
    for(Account acc : Trigger.new){
        Account oldAcc = Trigger.oldMap.get(acc.Id);
        if(oldAcc.Total_AUM__c != acc.Total_AUM__c){
            List<Opportunity> opps = [SELECT Id, AccountId, Current_Balance__c from Opportunity where AccountId = :acc.Id];                              
            List<Opportunity> newids = new List <Opportunity>();
            	for(Opportunity opp: opps){
                    if(opp.Current_Balance__c != acc.Total_AUM__c){
                        opp.Current_Balance__c = acc.Total_AUM__c;
                        newids.add(opp);
                    }
            }
            if(newids.isEmpty()== false){
                update newids;
            }
        }
    }

}

 
I have written a simple trigger, which works when tested manually. I am running into a problem when writing my test class and receive the error message: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, 
Required fields are missing: [Parent_Account__c]: [Parent_Account__c]  

The field Parent_Account__c is a required field with filter criteria. The criteria is that the Account Record Type EQUALS Parent Account. This is a master-detail where Account is master and Account Contract is detail. As written below no problems are highlighted and when I run the Test Class it receives 100% overall code coverage. I am having trouble figuring out how to write in the required field (Parent_Account__c) so that the insert can happen. I have tried a few approaches but continue to run into errors. Any insight would be much appreciated! 

Below is the trigger followed by my initial test class:

trigger ActiveContractCheckbox on Account_Contract__c (before update, before insert) {
    for (Account_Contract__c ac : Trigger.new) {
        If (ac.Contract_Start_Date__c <= DATE.TODAY() && ac.Contract_End_Date__c >= DATE.TODAY()){
                ac.Active_Contract__c = True;
        } Else If (ac.Contract_Start_Date__c > DATE.TODAY() || ac.Contract_End_Date__c < DATE.TODAY()){
                ac.Active_Contract__c = False;
            }   
         }
      }
  
@isTest
public class ActiveContractCheckboxTest
{
static testMethod void updateAccountContract()
    {
        Account_Contract__c myAcctContract = new Account_Contract__c();
        myAcctContract.Contract_Start_Date__c = Date.today();
        myAcctContract.Contract_End_Date__c   = Date.today();
            insert myAcctContract; 
        myAcctContract.Assigned_To__c = 'Jane Doe';
     update myAcctContract;
      }
    static testMethod void updateAccountContract2()
    {
        Account_Contract__c myAcctContract = new Account_Contract__c(); 
        Date myDate = Date.Today();
        Date newDate = myDate.addDays(3);
        Date newDate2 = myDate.addDays(-3);
        myAcctContract.Contract_Start_Date__c = newDate;
        myAcctContract.Contract_End_Date__c = newDate2;
         insert myAcctContract;
        myAcctContract.Assigned_To__c = 'Jason Doe';
         update myAcctContract;        
    }
    }
trigger DeDupeLead on Lead (before insert)

 {  //get the data quality queue record            
     GROUP DataQualityGroup = [SELECT Id 
                                       FROM GROUP
                                       WHERE DeveloperName= 'Data_Quality'
                                       LIMIT 1];
    for(Lead myLead:Trigger.new) {
            
        //Searching for matchingContacts

        List<Contact> matchingContacts = [SELECT Id
                                       FROM Contact
                                       WHERE Email = :myLead.Email];

         System.debug (matchingContacts.size() + 'contact(s) Found.');

        //If MatchingContacts Found...

        If (!matchingContacts.isEmpty()) {
        //Assign the lead to Data quality queue

        myLead.OwnerId  = DataQualityGroup.Id;

        
        //Add the dupe contacts Ids into lead descriptons

        String dupeContactMessages = 'Duplicate Contacts Found: \n';
        for( Contact matchingContact : matchingContacts) {
         dupeContactMessages += matchingContact.FirstName +''
                               +matchingContact.LastName + ''
                               +matchingContact.Account.Name +''
                               +matchingContact.Id; 
    }
    myLead.Description = dupeContactMessages + '\n'+ myLead.Description;
    }

    }
    }
 
Hello Guys,

I have setup a simple SEARCH visualforce page...
I am having a hard time covering test percentage... and am stuck at 35%
Can some one guide me as to how I can improve the code coverage...

I don't think anyone needs VF page as the problem is with test class and the controller. 
 APEX CLASS :
 
public with sharing class URLMonthlySearchController {
	 
    public URL_Monthly_Activity__c usr {get; set;}
     
    public List<URL_Monthly_Activity__c> AllGIDs
    {
        get
        {
            if(con != null)
                return (List<URL_Monthly_Activity__c>)con.getRecords();
            else
                return null ;
        }
        set;
    } 
    
    //Controller
    public URLMonthlySearchController()
    {
        AllGIDs = new List<URL_Monthly_Activity__c>() ;
        usr = new URL_Monthly_Activity__c() ;
    }
    
    //Instantiate the StandardSetController
    public ApexPages.StandardSetController con{get; set;}
    
    public PageReference Search()
    {   
        if(usr.GID__c != null && usr.Month__c != null && usr.Year__c != null)
        {
            con = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Id ,GID__c, Month__c, Year__c,Total_Article_Creates__c, 
                                                                                Total_Compliant_Article_Creates__c,  Total_Article_Updates__c, 
                                                                                Total_Compliant_Article_Updates__c, Total_Newsletter_Creates__c, 
                                                                                Total_Compliant_Newsletter_Creates__c, GAPageviews__c, URL__c  
                                                                                FROM URL_Monthly_Activity__c 
                                                                                WHERE ( URL_Monthly_Activity__c.GID__c =: usr.GID__c AND URL_Monthly_Activity__c.Month__c =: usr.Month__c AND URL_Monthly_Activity__c.Year__c =: usr.Year__c)]));
 
            // sets the number of records in each page set
            con.setPageSize(50);
        }
        else
        {
            con = null;
        }
        return null ;
    }
    
     public PageReference Cancel()
    { 
        return new PageReference('/home/home.jsp');
    }   
        
    
    //Boolean to check if there are more records after the present displaying records
    public Boolean hasNext
    {
        get
        {
            return con.getHasNext();
        }
        set;
    }
 
    //Boolean to check if there are more records before the present displaying records
    public Boolean hasPrevious
    {
        get
        {
            return con.getHasPrevious();
        }
        set;
    }
 
    //Page number of the current displaying records
    public Integer pageNumber
    {
        get
        {
            return con.getPageNumber();
        }
        set;
    }

    //Returns the previous page of records
    public void previous()
    {
        con.previous();
    }
 
    //Returns the next page of records
    public void next()
    {
        con.next();
    }
}

TEST CLASS :
 
@isTest
public class URLMonthlySearchController_Test {
    
    public static testMethod void testPage(){
        
        PageReference pageRef = Page.URLMonthlySearch;
        Test.setCurrentPage(pageRef);
      
        //ApexPages.StandardSetController pageController = new ApexPages.StandardSetController();
        
        URLMonthlySearchController controller = new URLMonthlySearchController();
        //List<URL_Monthly_Activity__c> urlMon = controller.search();
        
        controller.search();
        
    }
}

Any help is appreciated.
Thanks! ​
Hi,
I need to know what will happen when a synchronous method called inside a fututre method. Will it run synchronously or it will also start its execution in asynchronous manner. Also please tell me what will happen if the called method is having any return type?
Thanks
Example:
@future
static void myFutureMethod(List<String> params) {
    // call synchronous method
    mySyncMethod(params);
}
I'm looking for a side gig, about 30 hours a week.

My certficiations: http://certification.salesforce.com/certification-detail-print?conId=003G000002FKbh3IAD

I have about 5 years experience with Salesforce. Please send an email: varaprasad4sfdc@gmail.com email for a resume.

Thanks
Varaprasad
@For Support : varaprasad4sfdc@gmail.com
Some users having issue with list views .
Ex : 

DETAILED DESCRIPTION:
1) select a personalized view (here e.g. 003 - My cases in process).
2) open a case out of this list (here e.g. CAS001).
3) go back to the case list by pressing the "Back-Arrow" of the browser .
 
The wrong list of cases is displayed Here.

Any help really appreciated.

Thanks
Varaprasad
Hi ,

Some times in chatter Chatter bold ,italic buttons are not displaying.
User-added image

Please let me know the reason .

Thanks
Varaprasad
 
Hi I have come across the below error, using JavaScript in Button.

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. 
If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support.
 Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information.
 We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1652772134-27944 (-1092651723)
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var r = "{!Opportunity.Opportunity_Product_Count__c}";
var oppid = "{!Opportunity.Id}";
 

if(r == 1 )
{        
                    window.location.href='/apex/VFPageName?id='+oppid;
}
else
{
    alert ("No Products exists !");

Please help me out with alternative solution ASAP
Hi All,

i need to create one validation rule..

User-added image

in each prefernce picklist field i have 3 values
primary
ok to contact
do not contact

Among all 6 fields i need to select only one field value is primary....


Any Help really Appreciate...

Thanks
varaprasad


 
I have a Parent Object called "Treatement" and a child object "Infusion". For a particular treatement we have to create infusion records. the 1st Infusion record should have infusion number (a field in Infusion) as 1 and 2nd record should have infusion number as 2 , and the count should continue. 

How to achive this..

Thanks 
Hi Everyone.

  i need small help regarding on schedule apex.
  how we will schedule one class with different timings.
EX:i want to schedule one class :  Runs at 4:20; 7:50: 16:20; 20:50 CET these timings.

Thanks in Advance


 
Hi All ,

   i am writing test class for following schedule class 
      global class scheduleAccountWriteXML implements Schedulable{
    
    // Execute method
    
    global void execute(SchedulableContext SC) {
        
        try{
      
// Code to be executed when the schedule class wakes up

            
            CalloutAccountRequest.basicAuthCalloutRequest();
           
            String CRON_EXP = '0 0 * * * ?';
            string jobName = 'Account_Interface_Schedule_job_that_runs_every_1_hour_for_Accounts'; 
            scheduleAccountWriteXML p = new scheduleAccountWriteXML();
            system.schedule(jobName, CRON_EXP, p);              
            
        }     
        
        Catch (Exception e){            
            
            Messaging.SingleEmailMessage emailMessage = new Messaging.SingleEmailMessage();
           
            emailMessage.setToAddresses(new String[] { 'varaprasad.vemula@accenture.com'});
            emailMessage.setSubject('Subject');
            
          
            emailMessage.setPlainTextBody(e.getmessage());
         
            Messaging.SendEmailResult[] emailResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { emailMessage}, true);
        }
    }
}

I received code 90%,but test execution will be fail .

@isTest
public class Test_scheduleAccountWriteXML {
    public static testmethod void testaccountxml(){
    Test.StartTest();
              
            String CRON_EXP = '0 0 * * * ?';           
            scheduleAccountWriteXML scc6= new scheduleAccountWriteXML();       
            String jobid = system.schedule('varam', CRON_EXP, scc6);  
        
     Test.StopTest();  
        
         
    }
}


Any help please.


 
Hi Everyone ,

i created one class for generating xml file and by using callouts i am sending file to external system.
Here my requirement is 
  EX : file is more than one mb 1.5 mb
          i need to split xml file one is 1MB
                                          2nd one is 0.5mb
                                           is it possible to split file,,,,  Give me some ideas

Thanks all.
 
Hi

    I need to create multiple tasks in single page and i need to assign to user.Through vf page how we will implement this one .

 We need to have a VF section  so that from same page I can create multiple tasks without navigating to different page. Essentially in new task we need to have all the fields and can only refer what is in Action plan. 

Thanks to all ....
 

 
Hi All

   A and B are objects having lookup relationship
   A is parent and having status field
   B is child having status field
here my requiremeent is parent is having n on of childs in child what is the staus field value i need to update same thing in parent....

Thanks to alll
 
Hi I have come across the below error, using JavaScript in Button.

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. 
If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support.
 Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information.
 We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1652772134-27944 (-1092651723)
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var r = "{!Opportunity.Opportunity_Product_Count__c}";
var oppid = "{!Opportunity.Id}";
 

if(r == 1 )
{        
                    window.location.href='/apex/VFPageName?id='+oppid;
}
else
{
    alert ("No Products exists !");

Please help me out with alternative solution ASAP
Hi All,

i need to create one validation rule..

User-added image

in each prefernce picklist field i have 3 values
primary
ok to contact
do not contact

Among all 6 fields i need to select only one field value is primary....


Any Help really Appreciate...

Thanks
varaprasad


 
Is it possible to make a table column headers editable. Currently the table is using label as the column headers. This now needs to be editable which will be then stored to field in the object. Any help?
I have a button that when clicked returns a datetime and a user in a field. When this was setup it was working however it has now stopped working.

The following error message is now displayed:

A problem with the OnClick JavaScript for this button or link was encountered:

{faultcode:'soapenv:Client', faultstring:''NaN-NaN-NaNTNaN:NaN:NaN.NaN-NaN:NaN' is not a valid value for the type xsd:dateTime', }


This is the script used for the button:

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}

// identify the record
var a = new sforce.SObject("Account");
a.id = "{!Account.Id}";

// Get the user Info
var user = sforce.connection.getUserInfo();
// make the field change
a.Customer_Contacted_Date__c = new Date(Date.parse( '{!NOW()}'));
a.Contacted_By__c = user.userId; 

// save the change
sforce.connection.update([a]);

//refresh the page
window.location.reload();
I am unable to get the required code coverage for this trigger.Please Help me out.
 
trigger Site_visit_update_in_campaign on Opportunity (after insert,after 
    update,after delete) 
{
    public Boolean s1NullCheck=false;
    public Boolean s2NullCheck=false;
    public Boolean s3NullCheck=false;
    Public Boolean s4NullCheck=false;
    List <Campaign> campaigns=[select id from campaign];
    Set<Id> keysForOpp=new Set<Id>();
    Map<Id,List<Opportunity>> oppList=new Map<Id,List<Opportunity>>();
    List<Id> filteredIds=new List<Id>();
    Campaign[] campaign=new Campaign[]{};
    Map<Id,Campaign> campaignToUpdate=new Map<Id,Campaign>([Select Id,Completed_Site_Visit_1__c,Completed_Site_Visit_2__c,Completed_Site_Visit_3__c,Completed_Site_Visit_4__c From campaign]);

    for(Opportunity oppor:Trigger.new)
    {
        for(Campaign c:campaigns)
        {
            keysForOpp.add(c.Id);
        }

        for(Opportunity o:[Select 
       CampaignId,Site_Visit_1__c,Site_Visit_2__c,Site_Visit_3__c,Site_Visit_4__c From Opportunity Where CampaignId=:keysForOpp])
        {

            try
            {
                List<Opportunity> temp=oppList.get(o.CampaignId);
                if(temp==null)
                {
                    oppList.put(o.CampaignId, new List<Opportunity>{o});
                    filteredIds.add(o.CampaignId);
                }
                else
                {
                    temp.add(o);
                }

            }
            catch(NullPointerException e)
            {
                System.debug('Exception at custom Map setting : 
            '+e.getMessage());
            }

        }

        System.debug('opportunity debug'+opplist);

        for(Id i:filteredIds)
        {
             Integer siteVisitOneCounter=0;
             Integer siteVisitTwoCounter=0;
             Integer siteVisitThreeCounter=0;
             Integer siteVisitFourCounter=0;

            for(Opportunity o:oppList.get(i))
            {



                System.debug('Opportunity after calling key : '+o);

                try
                {
                    if(o.Site_Visit_1__c !=null)
                    {
                        s1NullCheck=true;
                        System.debug('S1check : '+s1NullCheck);
                    }
                }
                catch(NullPointerException e)
                {
                    System.debug('Exeeption at siteVisitOne : '+e.getMessage());
                    System.debug('S1check : '+s1NullCheck);
                }

                try
                {
                    if(o.Site_Visit_2__c !=null)
                    {
                        s2NullCheck=true;
                        System.debug('S2check : '+s2NullCheck);
                    }
                }
                catch(NullPointerException e)
                {
                    System.debug('Exeeption at siteVisitOne : '+e.getMessage());
                    System.debug('S2check : '+s2NullCheck);
                }

                try
                {
                    if(o.Site_Visit_3__c !=null)
                    {
                        s3NullCheck=true;
                        System.debug('S3check : '+s3NullCheck);
                    }
                }
                catch(NullPointerException e)
                {
                    System.debug('Exeeption at siteVisitOne : '+e.getMessage());
                    System.debug('S13heck : '+s3NullCheck);
                }

                try
                {
                    if(o.Site_Visit_4__c !=null)
                    {
                        s4NullCheck=true;
                        System.debug('S4check : '+s4NullCheck);
                    }
                }
                catch(NullPointerException e)
                {
                    System.debug('Exeeption at siteVisitOne : '+e.getMessage());
                    System.debug('S4check : '+s4NullCheck);
                }

                if(s1NullCheck==true)
                {   
                   if(o.Site_Visit_1__c=='Completed')
                   {
                       System.debug('Opportunity : '+o.Site_Visit_1__c);
                       siteVisitOneCounter=siteVisitOneCounter+1;

                   }
                   s1NullCheck=false;
                }

                if(s2NullCheck==true)
                {   
                    if(o.Site_Visit_2__c=='Completed')
                    {
                        System.debug('Opportunity : '+o.Site_Visit_2__c);
                        siteVisitTwoCounter=siteVisitTwoCounter+1;

                    }
                    s2NullCheck=false;
                }

                if(s3NullCheck==true)
                {   
                    if(o.Site_Visit_3__c=='Completed')
                    {
                        System.debug('Opportunity : '+o.Site_Visit_3__c);
                        siteVisitThreeCounter=siteVisitThreeCounter+1;

                    }
                    s3NullCheck=false;
                }

                if(s4NullCheck==true)
                {   
                    if(o.Site_Visit_4__c=='Completed')
                    {
                        System.debug('Opportunity : '+o.Site_Visit_4__c);
                        siteVisitFourCounter=siteVisitFourCounter+1;

                    }
                    s4NullCheck=false;
                }

            }

            System.debug('Site Visit One Total : '+siteVisitOneCounter);
            System.debug('Site Visit two Total : '+siteVisitTwoCounter);
            System.debug('Site Visit three Total : '+siteVisitThreeCounter);
            System.debug('Site Visit four Total : '+siteVisitFourCounter);
            Campaign cam=campaignToUpdate.get(i);
            cam.Completed_Site_Visit_1__c=siteVisitOneCounter;
            cam.Completed_Site_Visit_2__c=siteVisitTwoCounter;
            cam.Completed_Site_Visit_3__c=siteVisitThreeCounter;
            cam.Completed_Site_Visit_4__c=siteVisitFourCounter;

            campaign.add(cam);

            try
            {
                update campaign;
                System.debug('Campaign update Success');
            }
            catch(Exception e)
            {
                System.debug('Failed to update campaig : '+e.getMessage());
            }
        }
    }
}


Here is my Test class
 
@isTest
public class OpportunityTriggerTest 
{

    public static testMethod void campaignUpdate()
    {
        List<User> salesExec=[select Id from user];
        Campaign campaign=new Campaign(Name='chekxx campaign',CurrencyIsoCode='INR');
        Opportunity opp=new Opportunity();
        opp.Name='Cheky Voola';
        opp.Account=new Account(id='0010l00000EhKdL');
        opp.CurrencyIsoCode='INR';
        opp.CloseDate=Date.newInstance(2018, 1, 10);
        opp.StageName='Qualification';
        opp.Rating__c='Hot';
        opp.Preferred_Project__c='Test Project';
        opp.Sales_Executive__c=salesExec.get(1).Id;
        opp.Amenities__c='Pool and Badminton';
        opp.Certifications__c='No certifications';
        opp.Brand__c='Under Armour';
        opp.Preferred_Location__c='Kavali';
        opp.Budget__c='70 Lakhs - 75 Lakhs';
        opp.Site_Visit_1__c='Completed';
        opp.CampaignId='7010l0000009iV8';
        System.debug('Campaigns in method 2 : '+campaign);
        try
        {
            insert opp;
        }
        catch(Exception e)
        {
            System.debug('Exception during insert in method 2 : '+e.getMessage());
        }
        opp.Site_visit_2__c='Completed';
        try
        {
            upsert opp;

        }
        catch(Exception e)
        {
            System.debug('Error during upsert in method 2 : '+e.getMessage());
        }


    }

}

 
I have a controller extension for a custom create child object page to take me back to the correct page after editing and to allow me to have an erorr message wthout using a validation. The controller works exactly as it should but I am having issues writing the test class for it. Iget the error "system.queryexception: list has no rows for assignment to sobject" My code is as below:
Controller:
public with sharing class createController {
	public String oppId {get;set;}
	public Opportunity opp;
	public Opportunity_Forecast__c oppf {get;set;}
	private ApexPages.StandardController stdController; 
	
    public createController(ApexPages.StandardController stdController) {
    	this.stdController = stdController;
        oppf = (Opportunity_Forecast__c)stdController.getRecord();
        String oppid = (oppf.Opportunity__c);
        String ID = ApexPages.currentPage().getParameters().get('oppid');
        opp = [select Automatic_Forecasting__c from Opportunity where Id =:ID]; 
        if (ID != null){
        	oppf.Opportunity__c= ID;   
        }   
    }
	
	public PageReference cancelAndReturn() 
    {
    	PageReference cancel = new PageReference('/' + ApexPages.currentPage().getParameters().get('oppid'));
        cancel.setRedirect(true);
 		return cancel;	
    }
	
	public PageReference saveAndReturn()
    {
        try{
        	if(opp.Automatic_Forecasting__c == true){
        		ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Upside Automation must be disabled on the opportunity page before editing forecasts.');
        		ApexPages.addMessage(myMsg);
        		return null;
        	}
        	else{
        		upsert oppf;
        		PageReference save = new PageReference('/' + ApexPages.currentPage().getParameters().get('oppid'));
        		stdController.save();
        		save.setRedirect(true);
        		return save;
        	}
        }
        catch(DMLException ex){
        	ApexPages.addMessages(ex);
        	return null;
        }
    }   
}
Test Class:
@isTest 
public with sharing class CreateControllerTest {
    static testMethod void testCreateController(){
    	
    	Account testAcct = new Account(Name='Test Create Controller');
    	insert testAcct;
    	
    	Opportunity opp = new Opportunity(Name = 'Test Opportunity1',Account = testAcct,Project_Start_Date__c = Date.newInstance(2017, 12, 15),Delivery_End_Date__c = Date.newInstance(2018, 9, 15),Forecast_Amount__c = 50000, StageName = 'Continued Development of Project',Opportunity_Region__c = 'UK',CloseDate = Date.newInstance(2011, 12, 15), Is_Test__c =TRUE, Automatic_Forecasting__c = FALSE, Test_Date__c = Date.newInstance(2017, 12, 18));
    	insert opp;
    	
    	Opportunity_Forecast__c oppf = new Opportunity_Forecast__c(Opportunity__c = opp.id, Value__c = 2000, Forecast_Category__c = 'Upside', Forecast_Period__c = 'Next Quarter');
    	insert oppf;
    	
    	Test.StartTest();
    	
    	PageReference pageRef = Page.NewForecast;
		Test.setCurrentPage(pageRef);
		pageRef.getParameters().put('id',oppf.Id);
    	ApexPages.StandardController sc = new ApexPages.StandardController(oppf);
        CreateController testOppForecast = new CreateController(sc);
 
        testOppForecast.saveAndReturn();
        Test.StopTest();
    }
}
Any ideas what I'm doing wrong? I've done some reading on the error I'm getting but most cases are where the record hasn't been created. 
I have  a piece of code where I am getting error at line 3:
public static list<Account> createaccount(Integer numberofrec){
        List<Account> accounts = new list<Account>();
        RecordType recid = New RecordType([Select Id, name From RecordType where sobjecttype = 'Account' and name ='Account_New_Page_Assignment']);
  Colleague__c colleague = new Colleague__c();
  colleague = createcolleague(1)[0];
        for (Integer i = 0; i< numberofrec; i++){
            Account account = new Account(recordtypeid = recid.Id, Name = 'Test Account' + Math.random(), Relationship_Manager__c = colleague.Id , Country__c = 'India - IN' );
   accounts.add(account);
        }
  return accounts;



Can anybody help me out ? Many thanks in advance.
Hi there I have a custom parent object that has a child object. I also allow on the Parent object 'Notes and Attachments' (Notes & Upload files). We need to have a trigger on the 'Attachements' that will fire a trigger that will create an entry on the Child object of the parent. I don't know what needs to be done (if anything) to have the Child object know the id of the parent object. I presume I need to include the Parent ID when I create the entry in the Child object.

Below is the code I have been experimenting with, but I have not been able to get it to work.
 
trigger Attachement_After_Add_Del on Attachment (after insert) {
    List<Request_Time_Entry__c> entryList = new List<Request_Time_Entry__c>();
    for(Attachment AttachmentObj : Trigger.new){
    Request_Time_Entry__c entry = new Request_Time_Entry__c();
      entry.Hours_Worked__c = '00';
      entry.Minutes_Worked__c = '15';
      entry.NAME = 'Added Attachment';
      entry.Date_Worked__C = system.Today();
      // I don't know if what I need in the following line is correct. I Don't seem to get any
      // entries created on the child object when I run this code. Or, am I using the wrong 
     // form of 'Trigger' for an 'Attachement'. 
      entry.Related_Object__c = AttachmentObj.ParentId;
      entryList.add(entry);
     }
     if(entryList.size()>0){
      insert entryList;
     }
}
Any assistance would be greatly appreciated.

Thanks!

Eric Anderson
Hello awesome devs! 

I have the followign trigger which works as intended, however when I do a mass upload or mass edit on more than 10 Lead records, I always get the "Apex CPU Time Limit Exceeded" error.  Can anyone tell me how to resolve this error in my code as if my users do a mass update of more than 10 lead records to assume ownership it throws this error and any other time an insert or update of more than 10 Lead records at a time. 

Thanks so much for any help you can provide,

Shawn

Trigger code:
 
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(ts.WhoId!=null && ts.whatId == null)
    {
        If(string.valueOf(ts.WhoId).startsWith('00Q'))
        {
        lid.add(ts.Whoid);
    }
    }
    }
    If(lid.size()>0){
    Map <id,Task > tmap = new Map <id, Task>([select id, Whoid from Task where Whoid in:lid]);
    Map <id, Lead> lmap = new Map <id, Lead>([select id,Count_Activity__c from lead where id in:lid ]);
    
        If(lmap.size()>0){
       List<Lead> llist = [SELECT Id, Count_Activity__c FROM Lead WHERE ID IN:lmap.values()]; 
    for(lead l : lmap.values())
    {
        set<id> tids = new set <id>();
        for(Task tt : tmap.values())
        {
           if(tt.WhoId== l.Id)
            tids.add(tt.id);
        }
        if(l.Count_Activity__c!=tids.size())
        l.Count_Activity__c=tids.size();
        
              tlist = [select id, Whoid from task where whoid in:lid ];
        for(lead le :llist)
        {
            for(Task te:tlist)
            {
                if(tlist.size()>0)
                le.Count_Activity__c = tlist.size();
            }
        }
        
        
    }
    If(lmap.size()>0){
    update lmap.values();
    }
    }
    }
    }
}

 
Hi,
I'm getting an error when trying to do this:
click a custom list button in a specific Accounts list view that will update the Key Account checkbox field for the selected records.

checkbox field to update: Key_Account__c
custom button behavior: execute javascript

CUSTOM BUTTON CODE:

{!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")} 

if({!Account.Key_Account__c} == false) 

var c = new sforce.SObject("Account"); 
c.id = "{!Account.Id}"; 
c.Key_Account__c = true; 
result = sforce.connection.update([c]); 
if ( result[0].getBoolean( "success" ) ) 

window.location.reload(); 

else 

alert( result[0].errors.message); 


else 

alert("Already True"); 
}

Thank you in advance!!!
Can someone explain how the we services architecture and API works in salesforce, Is it same like java??? Kindly provide with example and links.
Hi.
I'm back to working on the Superbadge Advanced Apex Specialist Superbadge, Step 4.

Putting aside my disagreement with a singular TestDataFactory god-object in general and a big WTF at the "InsertTestData" (weren't these supposed to be for UNIT tests!?!), I've populated the specified methods, but am now getting the following error when I submit:
 
Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

Here is my TestDataFactory class:
 
/**
 * @name TestDataFactory
 * @description Contains methods to construct and/or validate commonly used records
**/
public class TestDataFactory {

	private static final Id STANDARD_PRICEBOOK_ID = (Test.isRunningTest())
			? Test.getStandardPricebookId()
			: [SELECT id FROM PriceBook2 WHERE isStandard = true LIMIT 1].id;

    /**
     * @name constructCollaborationGroup
     * @description
    **/
    public static CollaborationGroup ConstructCollaborationGroup(){ 
    	return new CollaborationGroup(
    		Name = 'TEST' + Constants.INVENTORY_ANNOUNCEMENTS,
    		CanHaveGuests = false,
    		CollaborationType = 'Public',
    		IsArchived = false,
    		IsAutoArchiveDisabled = false
    	);
    }

    /**
     * @name CreateProducts
     * @description constructs a List of Product2 records for unit tests
    **/
    public static List<Product2> constructProducts(Integer cnt){
    	List<Schema.PickListEntry> familyValueList = Product2.Family.getDescribe().getPickListValues();
    	Integer possibleFamilyValues = familyValueList.size();
    	
    	List<Product2> productList = new List<Product2>();
    	for (Integer i = 0; i < cnt; i++) {
    		productList.add(new Product2(
    			Name = 'Product ' + (i + 1),
    			Family = familyValueList[Math.mod(i, possibleFamilyValues)].getValue(),
    			Initial_Inventory__c = 10,
    			IsActive = true
    		));
    	}
    	return productList;
    }

    /**
     * @name CreatePricebookEntries
     * @description constructs a List of PricebookEntry records for unit tests
    **/
    public static List<PricebookEntry> constructPricebookEntries(List<Product2> productList){
    	List<PricebookEntry> pbes = new List<PricebookEntry>();
    	for (Product2 product: productList) { 
    		pbes.add(new PricebookEntry(
    			Pricebook2Id = STANDARD_PRICEBOOK_ID,
    			Product2Id = product.id,
    			IsActive = true,
    			UnitPrice = 1
    		));
    	} 
        return pbes;
    }

    /**
     * @name CreateAccounts
     * @description constructs a List of Account records for unit tests
    **/
    public static List<Account> constructAccounts(Integer cnt){
    	List<Account> accts = new List<Account>();
    	for (Integer i = 0; i < cnt; i++) {
    		accts.add(new Account(
    			Name = 'Account ' + (i + 1)
    		));
    	}
    	return accts;
    }

    /**
     * @name CreateContacts
     * @description constructs a List of Contacxt records for unit tests
    **/
    public static List<Contact> constructContacts(Integer cnt, List<Account> accts){
    	Integer possibleAccountValues = accts.size();
    	
    	List<Contact> contactList = new List<Contact>();
    	for (Integer i = 0; i < cnt; i++) {
    		contactList.add(new Contact(
    			LastName = 'Contact ' + (i + 1),
    			AccountId = accts[Math.mod(i, possibleAccountValues)].id
    		));
    	}
    	return contactList;
    }

    /**
     * @name CreateOrders
     * @description constructs a List of Order records for unit tests
    **/
    public static List<Order> constructOrders(Integer cnt, List<Account> accts){
    	Integer possibleAccountValues = accts.size();
    	
    	List<Order> ords = new List<Order>();
    	for (Integer i = 0; i < cnt; i++) {
    		ords.add(new Order(
    			Name = 'Order ' + (i + 1),
    			AccountId = accts[Math.mod(i, possibleAccountValues)].id,
    			EffectiveDate = Date.today(),
    			Pricebook2Id = STANDARD_PRICEBOOK_ID,
    			Status = 'Draft'
    		));
    	}
    	return ords;
    }

    /**
     * @name CreateOrderItems
     * @description constructs a List of OrderItem records for unit tests
    **/
    public static List<OrderItem> constructOrderItems(Integer cnt, List<Pricebookentry> pbes, List<Order> ords){
    	Integer possiblePricebookEntryValues = pbes.size();
    	Integer possibleOrderValues = ords.size();

    	List<OrderItem> orderItemList = new List<OrderItem>();
    	for (Integer i = 0; i < cnt; i++) {
    		orderItemList.add(new OrderItem(
    			OrderId = ords[Math.mod(i, possibleOrderValues)].id,
    			PriceBookEntryId = pbes[Math.mod(i, possiblePricebookEntryValues)].id,
    			Quantity = Constants.DEFAULT_ROWS,
    			UnitPrice = 1
    		));
    	}
    	
        return orderItemList;
    }

    /**
     * @name SetupTestData
     * @description Inserts accounts, contacts, Products, PricebookEntries, Orders, and OrderItems.
    **/
    public static void InsertTestData(Integer cnt){
    	insert constructCollaborationGroup();
    	
    	List<Product2> productList = constructProducts(cnt); 
    	insert productList;
    	
    	List<PricebookEntry> pbes = constructPricebookEntries(productList);
    	insert pbes;
    	
    	List<Account> accts = constructAccounts(cnt);
    	insert accts;
    	insert constructContacts(cnt, accts);
    	
    	List<Order> ords = constructOrders(cnt, accts);
    	insert constructOrderItems(cnt, pbes, ords);
    }
}

Any idea(s) what is wrong and how to fix this?
Thanks.



 

Getting the following error when I m trying to create a MAP out of Account object.
There are many Accounts in the ORG but I need to get and Map of all so cross check a condition on trigger and update few accounts based on the conditions..

But I need to get the accounts MAP first to get the existing Account records, is there a way to get all the accounts

Sharing the code below...

Requesting please let me how to proceed with this..

 

public with sharing class AccountReleationShipTriggerHandler {    
    public static void getAccountFromTrigger(List<Account_Relationships__c>  lstAccountRelation)
    {        
        System.debug('>>>>>>> lstAccountRelation : '+lstAccountRelation.size());
        ID rtId = [SELECT Id FROM RecordType WHERE SobjectType='Account' and developerName='Site'].id;        
        Map<ID, Account> allAccountMap = new Map<ID, Account>([SELECT Id, Name, Portfolio_Type__c, Source_Zone__c, RecordTypeID FROM Account]);        

        for (Account_Relationships__c ar : lstAccountRelation)
        {
            // will perform the operations here... 
            // As here I need to refer the MAP to find the account details and update
..
            System.debug('test ar Source_Account__c : '+ ar.Source_Account__c);
            System.debug('test ar Related_Account__c : '+ ar.Related_Account__c);
            System.debug('test ar Type__c : '+ ar.Type__c);        
        }         
   }    
}

 

Getting following error : 

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger trig_AccountUpdate caused an unexpected exception, contact your administrator: trig_AccountUpdate: execution of AfterInsert caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): Class.AccountReleationShipTriggerHandler.getAccountFromTrigger: line 6, column 1

I added a trigger on Note with this scenario which works in the sandbox.  I also need a test class.  Can anyone assist?
trigger UpdateOppLastNote on Note (after insert, after update) {


List<Jr_Processing_Tasks__c> oppLstToUpdate=new List<Jr_Processing_Tasks__c>();
    if(Trigger.isInsert){
        for(Note nt : Trigger.new){
            {
                Jr_Processing_Tasks__c opp=new Jr_Processing_Tasks__c(Id=nt.parentId,Latest_Note__c=nt.Body); 
                oppLstToUpdate.add(opp);
            }   
        }
    }if(Trigger.isUpdate){
        for(Note nt : Trigger.new){
            {
                if(nt.Body != Trigger.oldMap.get(nt.Id).Body){
                   Jr_Processing_Tasks__c opp=new Jr_Processing_Tasks__c(Id=nt.parentId,Latest_Note__c=nt.Body); 
                    oppLstToUpdate.add(opp);
                }
            }
        }
    }
    if(!oppLstToUpdate.isEmpty()){
        try{
            update oppLstToUpdate;
        }catch(DmlException de ){
            System.debug(de);
        }
    }


}

 
I want the standard Event creation page to be displayed when a Lead checkbox field is checked, and the record Saved. I need a couple of the new Event fields to be prepopulated from the Lead Record. 

I tried to do this in Flow, but Flow does not support Date/Time fields, which is needed for the Event Start Date/Time and End Date/Time fields. 

My Apex coder is telling me that the standard Event creation page cannot be displayed when the Lead checkbox is checked, using an Apex Trigger. 

This does not sound right to me. Any input appreciated. 
Suppose there is parent object(A) and child object (B).When I select picklist value in parent ,picklist in child should be updated and later check box in parent should be updated.For example picklist values of A(D1,D2) and picklist values of B(Division 1,Division 2).If we select picklist values as D1 and then all the picklist value of all child objects should be Divsion 1 and later check box in parent should be checked.Could any one please post a trigger for this scenario.