• brijender singh rathore 16
  • NEWBIE
  • 25 Points
  • Member since 2017

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 7
    Replies
Hi
I have created an apex trigger to update contact address when the account address is changed. The code worked fine for already created accounts, but when I have created a new account the following error was thrown and I was not able to save the account. Please help me.

Error: updateContact: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.updateContact: line 33, column 1​
 
trigger updateContact on Account (after insert, after update) {
    List<Contact> contactsForUpsert = New List<Contact>();

    Map<Id, Contact> contactsByAccountId = new Map<Id, Contact>();
    List<Contact> contacts = [SELECT Id,
                                     AccountId,
                                     mailingstreet,
                                     mailingcity,
                                     mailingstate,
                                     mailingpostalcode
                            FROM Contact WHERE AccountId IN: Trigger.newMap.keySet()];
    for (Contact cont: contacts) {
        contactsByAccountId.put(cont.accountId, cont);
    }

    for (Account account: Trigger.new) {

        Account old;
        if (Trigger.isUpdate) {
            old = Trigger.oldMap.get(account.Id);
        }

        Boolean isShippingAddressChangedOrNew = Trigger.isInsert ? true :
                                                (   account.ShippingStreet != old.ShippingStreet
                                                 || account.ShippingCity != old.ShippingCity
                                                 || account.ShippingState != old.ShippingState
                                                 || account.ShippingPostalCode != old.ShippingPostalCode
                                                 || account.ShippingCountry != old.ShippingCountry) ? true : false;

        if (isShippingAddressChangedOrNew) {
            Contact relatedContact = contactsByAccountId.get(account.Id);
           
            relatedContact.mailingstreet     = account.Shippingstreet;
            relatedContact.mailingcity       = account.Shippingcity;
            relatedContact.mailingstate      = account.Shippingstate;
            relatedContact.mailingpostalcode = account.shippingpostalcode;
            contactsForUpsert.add(relatedContact);
        

    }

    try {
        upsert contactsForUpsert;
    } catch(Dmlexception e) {
        System.debug(LoggingLevel.ERROR, 'Contact insert from createopp.trigger has failed with message:' + e.getMessage());
    }
}
}

 
  • January 23, 2018
  • Like
  • 0
We have a customer community set up, and we are sharing custom objects based on a lookup to account. We created a sharing set - selected the correct profile and then we added sharing based on user.account = customObject__c.Account__c
Now on the same custom object, we have another lookup to account to specify a third party and we want to give users which belong to that account also access to that same record.
But it seems that this is not possible without creating a new profile, which of course we want to avoid as much as possible. Otherwise a user who have access to his own records and records linked to the other lookup would need to switch profiles before viewing the other records.
Is there a way we can handle this in a more elegant way? One profile with a sharing set that looks at 2 lookups.
Is there a way that if I send a customer an email from SF and she reply via outlook, her response comes back into SF??? If customer is using outlook desktop app with lighting sync app installed in it which sync the e-mail from outlook is there a way to define group of contacts who every interaction from outlook is synced to Salesforce.???
I HAVE TO COVER CODE (PART OF CODE).MY TEST CLASS FUNCTION COVERING FIRST THREE LINES.
static testMethod void myUnitTest() {
    Test.startTest();
    account acc= new account(Name = 'testtng');
    insert acc;  
    Country__c oCountry = new Country__c(Name = 'United States');
    insert oCountry;
    Country__c oCountry1 = new Country__c(Name = 'Canada');
    insert oCountry1;
    State_Providence__c pcSP = new State_Providence__c(Name='test', Abbreviation__c = 'te');
    insert pcSP;
    Contact pcContact = new Contact(LastName = 'tester', FirstName = 'test');
    insert pcContact;
    Background_Check_Service_Package__c bcsp = new Background_Check_Service_Package__c(HISTORIC_Package_Code__c = 'testing');
    insert bcsp;
    List<Contact> lstContact1 = new List<Contact>();
    BGC_Order__c bo = new BGC_Order__c(Subject_has_Multiple_Names__c = true, Subject_Zip_Code__c = '95256', State_Providence__c = pcSP.Id, Account__c = acc.id, BGC_Service_Package__c = bcsp.id);
    insert bo;

   // String orderid = ApexPages.currentPage().getParameters().put('tfa_2935', bo.Id);
    String orderid = ApexPages.currentPage().getParameters().put('tfa_2935', bo.Id);
    ApexPages.currentPage().getParameters().put('tfa_2181', '2');
    ApexPages.currentPage().getParameters().put('tfa_2187', '3');
    ApexPages.currentPage().getParameters().put('tfa_2964', '2');
    ApexPages.currentPage().getParameters().put('tfa_2920', '4');
    ApexPages.currentPage().getParameters().put('tfa_6793', '5');
    ApexPages.currentPage().getParameters().put('tfa_6776', '4');
    
    QuickBackgroundCheckOrderCl oQuickBackgroundCheck = new QuickBackgroundCheckOrderCl();
    oQuickBackgroundCheck.iDegCount = integer.valueof(ApexPages.currentPage().getParameters().get('tfa_2181'));
    oQuickBackgroundCheck.sOrderId = orderid;
    list<BGC_Order__c> oBGC = [SELECT Id, Subject_First_Name__c,Subject_Last_Name__c, Subject_Middle_Name__c, Government_ID_Type__c, Government_ID_Number__c,Subject_Email__c,Subject_Phone_Number__c,Subject_of_Order__c,Subject_Address__c,Subject_City__c,Subject_Date_of_Birth__c,Subject_Zip_Code__c,Subject_Country__c, State_Providence__c, Account__c, Notes_to_Pre_Employ__c, Order_Status__c, BGC_Service_Package__c FROM BGC_Order__c WHERE Id =: orderid limit 1];
	insert oBGC; 
    BGC_Degree_Intake__c oBGCDegree1 = new BGC_Degree_Intake__c(Background_Check_Order__c = bo.id, School_Country__c = oCountry.id) ;
    insert oBGCDegree1;
    BGC_Degree_Intake__c oBGCDegree = new BGC_Degree_Intake__c(Background_Check_Order__c = bo.id, School_Country__c = oCountry.id) ;
    insert oBGCDegree;
    BGC_Reference_Intake__c oBGCReference = new BGC_Reference_Intake__c(Background_Check_Order__c = bo.id, Is_Reference_Searches_Creation_Pending__c = true) ;
    insert oBGCReference;
    BGC_License_Intake__c oBGC_License_Intake = new BGC_License_Intake__c(Background_Check_Order__c = bo.id, Is_License_Searches_Creation_Pending__c = true) ;
    insert oBGC_License_Intake;
    String orderid11 = ApexPages.currentPage().getParameters().put('tfa_2935', bo.Id);
    List<BGC_Degree_Intake__c> lstBGCDegreeList1 = new List<BGC_Degree_Intake__c>();
    List<BGC_Reference_Intake__c> lstBGCRefList1 = new List<BGC_Reference_Intake__c>();
    List<BGC_License_Intake__c> lstBGCLicList1 = new List<BGC_License_Intake__c>();
    oQuickBackgroundCheck.getGovIdType();
    oQuickBackgroundCheck.getDegree();
    oQuickBackgroundCheck.getItems();
    oQuickBackgroundCheck.getItem();
    oQuickBackgroundCheck.getState();
    oQuickBackgroundCheck.getDLState();
    oQuickBackgroundCheck.getitemcontact();
    oQuickBackgroundCheck.getCountries();
    oQuickBackgroundCheck.scountry = oCountry.id;
    oQuickBackgroundCheck.sState = pcSP.id;
    oQuickBackgroundCheck.sDLNumber = '123';
    oQuickBackgroundCheck.sLastName = 'test';
    oQuickBackgroundCheck.sFirstName = 'test';
    oQuickBackgroundCheck.sGovermentIdType = 'test';
    oQuickBackgroundCheck.sGovermentIdNumber = 'test';
    oQuickBackgroundCheck.sEmail = 'test@dsfsd.com';
    oQuickBackgroundCheck.sPhoneNumber = 'test';
    oQuickBackgroundCheck.sAddress = 'test';
    oQuickBackgroundCheck.sDegreestate = 'test';
    oQuickBackgroundCheck.sNotesPreEmlpoy = 'test';
    oQuickBackgroundCheck.sLastAlterName = 'test';
    oQuickBackgroundCheck.sDegree = 'test';
    oQuickBackgroundCheck.sDegreeCountry = 'test';
    oQuickBackgroundCheck.sAnnualSalary = '12340';
    oQuickBackgroundCheck.bCreditReport = 'true';
    oQuickBackgroundCheck.sCity = 'test';
    oQuickBackgroundCheck.sZipCode = 'test';
    oQuickBackgroundCheck.sService = 'test';
    oQuickBackgroundCheck.bYes = true;
    oQuickBackgroundCheck.bLicCount = true;
    oQuickBackgroundCheck.bDegCount = true;
    oQuickBackgroundCheck.bEmpCount = true;
    oQuickBackgroundCheck.bRefCount = true;
    oQuickBackgroundCheck.sMiddleName = 'test';
    oQuickBackgroundCheck.lstContact = lstContact1;
    oQuickBackgroundCheck.sFirstAlterName = 'test';
    oQuickBackgroundCheck.sCurrentEmployer = 'test';
    oQuickBackgroundCheck.sEmployCountry = 'test';
    oQuickBackgroundCheck.sEmploystate = 'test';
    oQuickBackgroundCheck.sAttendance = 'test';
    oQuickBackgroundCheck.sCommonform = 'test';
    oQuickBackgroundCheck.dDateOfBirth = null;
    oQuickBackgroundCheck.lstBGCDegreeList = lstBGCDegreeList1;
    oQuickBackgroundCheck.lstBGCReferenceList = lstBGCRefList1;
    oQuickBackgroundCheck.lstBGCLicenseList = lstBGCLicList1;
    oQuickBackgroundCheck.iTotalInternationalLicense = 2;
    oQuickBackgroundCheck.bFCRAEmploymentRelatedChecks = 'true';
    oQuickBackgroundCheck.bFCRAInvestigativeConsumerReports = 'true';
    oQuickBackgroundCheck.bCertificationRegardingNoLegalAdvice = 'true';
    oQuickBackgroundCheck.sUnitNumber = '12345';
    oQuickBackgroundCheck.sUnitNumberMailing = '54321';
    oQuickBackgroundCheck.sAddressMailing = 'Test';
    oQuickBackgroundCheck.sCityMailing = 'Test';
    oQuickBackgroundCheck.stateMailing = pcSP.id;
    oQuickBackgroundCheck.sZipCodeMailing = '12345';
    oQuickBackgroundCheck.sCountryMailing = oCountry.id;
    bo.FCRA_Employment_Related_Checks__c = true;
    bo.FCRA_Investigative_Consumer_Reports__c = true;
    bo.Certification_Regarding_No_Legal_Advice__c = true;
    bo.Annual_Salary__c = 12;
    bo.Credit_History_Information_Requested__c = true;
    bo.FCRA_Certification_of_Permissible_Purpos__c = 'true';
    bo.Subject_First_Name__c = 'test';
    bo.Subject_Last_Name__c = 'test';
    bo.Subject_Email__c = 'savdf@sad.cod';
    update bo;
    pcContact.Background_Check_Order__c = orderid11;
    update pcContact;
    oQuickBackgroundCheck.placeorder();
    update pcContact;
    Test.stopTest();
  }

public PageReference placeorder(){
    Alternate_Names__c oAlternateNames = new Alternate_Names__c();
    contact ocon = new contact();
    if(sOrderId != null){
      if(sUnitNumber != null && sUnitNumber != '') {
        sAddress = sAddress + ', ' + sUnitNumber;
      }
      if(sAddressMailing != null && sAddressMailing != '') {
        List<Zip_Code__c> lstZipCounty = [SELECT Id, Zip_Code__c, AssociatedCounty__c FROM Zip_Code__c WHERE Zip_Code__c = :sZipCode LIMIT 1];
        Additional_Address__c oAdditionalAddress = new Additional_Address__c();
        oAdditionalAddress.Address__c = sAddress;
        oAdditionalAddress.Background_Check_Order__c = sOrderId;
        oAdditionalAddress.City__c = sCity;
        oAdditionalAddress.Country__c = scountry;
        if(lstZipCounty.size() > 0 && lstZipCounty.get(0).AssociatedCounty__c != null) {
          oAdditionalAddress.County__c = lstZipCounty.get(0).AssociatedCounty__c;
        }
        oAdditionalAddress.State_Providence__c = sState;
        oAdditionalAddress.Type_of_Address__c = 'Other';
        oAdditionalAddress.Zip_Code__c = sZipCode;
        insert oAdditionalAddress;
        if(sUnitNumberMailing != null && sUnitNumberMailing != '') {
          sAddressMailing = sAddressMailing + ', ' + sUnitNumberMailing;
        }
        sAddress = sAddressMailing;
        sCity = sCityMailing;
        scountry = sCountryMailing;
        sState = stateMailing;
        sZipCode = sZipCodeMailing;
      }
      
      if(sFirstAlterName != null && sFirstAlterName != '' && sLastAlterName != null && sLastAlterName != '')
      {
        oAlternateNames.Alternate_First_Name__c = sFirstAlterName;
        oAlternateNames.Alternate_last_Name__c = sLastAlterName;
        oAlternateNames.Background_Check_Order__c = sOrderId;
        insert oAlternateNames;
      }
      ocon.mailingcity = sCity;
      ocon.MailingStreet = sAddress;
      ocon.State__c = sState;
      ocon.Government_ID_Number__c = sGovermentIdNumber;
      ocon.FirstName = sFirstName;
      ocon.LastName = sLastName;
      ocon.mailingpostalcode = sZipCode;
      ocon.mailingcountry = scountry;
      ocon.Birthdate = dDateOfBirth;
      ocon.MobilePhone = sPhoneNumber;
      ocon.Email = sEmail;
      ocon.Unauthenticated_Government_ID_Number__c = sGovermentIdNumber;
      ocon.Background_Check_Order__c = sOrderId;
      List<User> lstUser = [SELECT Id, Name FROM User WHERE NAME = 'Tara Noble' LIMIT 1];
      if(lstUser.size() > 0) {
        ocon.OwnerId = lstUser.get(0).Id; //--Set Tara Noble's Id as contact owner in the scope of T-28033: Defect ID: 8659
      }
      lstContact = [SELECT Id FROM contact WHERE Background_Check_Order__c =: sOrderId limit 1];
      if(lstContact.size() > 0){
        ocon.id = lstContact.get(0).id;
        update ocon;
      }
      else{
        insert ocon;
      }
      List<RecordType> lstRecordType = [SELECT Id, Name, SobjectType, IsActive FROM RecordType WHERE Name = 'Pending' AND SobjectType = 'BGC_Order__c' LIMIT 1];
      lstBGCOrder = [SELECT Id, Subject_First_Name__c,Subject_Last_Name__c, Subject_Middle_Name__c, Government_ID_Type__c, Government_ID_Number__c,Subject_Email__c,Subject_Phone_Number__c,Subject_of_Order__c,Subject_Address__c,Subject_City__c,Subject_Date_of_Birth__c,Subject_Zip_Code__c, Subject_Country__c, State_Providence__c, Account__c, Notes_to_Pre_Employ__c, Order_Status__c, BGC_Service_Package__c, Method_of_Data_Supply__c, DL_or_ID_Number__c, FCRA_Certification_of_Permissible_Purpos__c, Credit_History_Information_Requested__c, Annual_Salary__c, Certification_Regarding_No_Legal_Advice__c, FCRA_Investigative_Consumer_Reports__c, FCRA_Employment_Related_Checks__c, Joe_s_Account__c, Subject_has_Multiple_Names__c, Drivers_License_ID_State__c, County__c, Package_A_Name__c FROM BGC_Order__c WHERE Id =: sOrderId limit 1];
      if(lstBGCOrder.size() > 0){
        lstBGCOrder.get(0).Subject_First_Name__c = sFirstName;
        lstBGCOrder.get(0).Subject_Last_Name__c = sLastName;
        lstBGCOrder.get(0).Subject_Middle_Name__c= sMiddleName;
        lstBGCOrder.get(0).Subject_Email__c = sEmail;
        lstBGCOrder.get(0).Subject_Phone_Number__c = sPhoneNumber;
        lstBGCOrder.get(0).Subject_Address__c = sAddress;
        lstBGCOrder.get(0).Subject_City__c = sCity;
        lstBGCOrder.get(0).Subject_of_Order__c = ocon.id;
        lstBGCOrder.get(0).Subject_Date_of_Birth__c = dDateOfBirth;
        lstBGCOrder.get(0).Subject_Zip_Code__c = sZipCode;
        lstBGCOrder.get(0).Subject_Country__c = scountry;
        lstBGCOrder.get(0).State_Providence__c = sState;
        if(lstRecordType.size() > 0) {
          lstBGCOrder.get(0).RecordTypeId = lstRecordType.get(0).Id;  // 012800000003oG3
        }
        lstBGCOrder.get(0).Government_ID_Number__c = sGovermentIdNumber;
        lstBGCOrder.get(0).Government_ID_Type__c = sGovermentIdType;
        lstBGCOrder.get(0).Notes_to_Pre_Employ__c = sNotesPreEmlpoy;
        lstBGCOrder.get(0).Account__c = sAccountId;
        lstBGCOrder.get(0).Drivers_License_or_ID_State__c = sDLState;
        lstBGCOrder.get(0).Order_Status__c = 'Approved for Formation';
        lstBGCOrder.get(0).Method_of_Data_Supply__c = 'Client - Manual Data Entry';
        lstBGCOrder.get(0).DL_or_ID_Number__c = sDLNumber;
        lstBGCOrder.get(0).Subject_has_Multiple_Names__c = bYes;
        lstBGCOrder.get(0).Joe_s_Account__c = sAccountId;
        lstBGCOrder.get(0).FCRA_Employment_Related_Checks__c = boolean.valueof(bFCRAEmploymentRelatedChecks);
        lstBGCOrder.get(0).FCRA_Investigative_Consumer_Reports__c = boolean.valueof(bFCRAInvestigativeConsumerReports);
        lstBGCOrder.get(0).Certification_Regarding_No_Legal_Advice__c = boolean.valueof(bCertificationRegardingNoLegalAdvice);
        lstBGCOrder.get(0).Annual_Salary__c = integer.valueof(sAnnualSalary);
        lstBGCOrder.get(0).Credit_History_Information_Requested__c = boolean.valueof(bCreditReport);
        lstBGCOrder.get(0).FCRA_Certification_of_Permissible_Purpos__c = bFCRAPermissble;
        if(lstBGCOrder.get(0).County__c == null && sZipCode != null && sZipCode != '') {
          List<Zip_Code__c> lstAssociatedCounty = [SELECT Id, Zip_Code__c, AssociatedCounty__c FROM Zip_Code__c WHERE Zip_Code__c = :sZipCode LIMIT 1];
          if(lstAssociatedCounty.size() > 0 && lstAssociatedCounty.get(0).AssociatedCounty__c != null) {
            lstBGCOrder.get(0).County__c = lstAssociatedCounty.get(0).AssociatedCounty__c;
          }
        }
        update lstBGCOrder;

Thanks in advance
 
User-added image

I WANT TO MAKE CITY FIELD REQUIRED AND I HAVE MAKE IT REQUIRED BY ADDING THE CODE ON LINE 704 AND 705 BUT WHEN WE ARE ADDING ONLY  BLANK SPACES ON THE FIELD IT IS TAKING THEM AS A TEXT AND CREATING RECORD.SO PLEASE HELP.

POSTING THE CODE I USED


 
                <td class="ColLabel"><apex:outputText escape="false"  value="City"/><span class="required">*</span></td>
                <td class="ColValue"><apex:inputText value="{!sEmpCity}" maxlength="50" required="true"/></td>
              </tr>
I want regex for this format and filter out 123456 if match the current format
PO # 123456
PO# 123456
PO #123456
P.O. # 123456
P.O.# 123456
P.O. #123456

We have to filter substring from string notes__c field. my regex is only working for PO #123456 and P.O. #123456
tried PO# (\\S+)\\s not working
Matcher rm = r.matcher(oOrder.Notes__c); 
Pattern r = Pattern.compile('PO #(\\S+)\\s'); 

if(rm.find()) {
 string res2 = rm.group(1); 
oOrder.test__c = res2; 
}

 
This class is written for a VF page which will search contacts from contact objects when search button is clicked and when contact is selected it will display dispensory items which are in lookup with contacts (API - patient__c).when one or multiple dispensory items are selected by checkboxes and clicked on submit button  it will perform some operations.

CONTROLLER CLASS

 
public class SearchController {
  public List<contact> searchResults {get; set;}
  public Contact oContact {get; set;}
  public Dispensary_Item__c oDispensaryItem {get; set;}
  public List<string> lstProductId {get; set;}
  public List<string> lstOppId {get; set;}
  public boolean isList {get; set;}
  public string sPatientLastName {get; set;}
  public string sPatientAccountId {get; set;}

  public SearchController(ApexPages.StandardController controller) {
    oDispensaryItem = new Dispensary_Item__c();
    lstProductId = new List<string>();
    SearchResults = new List<contact>();
    SearchResults.clear();
    lstOppId = new List<string>();
    isList = false;
    sPatientLastName = '';
  }

  public PageReference search() {
    SearchResults.clear();
    sPatientLastName = '';
    sPatientAccountId = '';
    SearchResults = [SELECT Id, Name, LastName, FirstName,account.id, Accountid, (SELECT Id, Name, IsChecked__c, Opportunity__c, Practice__c, Product__c, Quantity__c, Price__c FROM Dispensary_Items__r) FROM contact WHERE Id = :oDispensaryItem.Patient__c Order By Name LIMIT 1];
    if(SearchResults.size() > 0) {
      List<Dispensary_Item__c> lstTempDispensaryItem = new List<Dispensary_Item__c>();
      lstTempDispensaryItem.addAll(SearchResults.get(0).Dispensary_Items__r);
      sPatientLastName = SearchResults.get(0).LastName;
      sPatientAccountId = SearchResults.get(0).AccountId;
      if(lstTempDispensaryItem.size() > 0) {
        isList = true;
        for(Dispensary_Item__c oDispItem : lstTempDispensaryItem) {
          oDispItem.IsChecked__c = false;
        }
      }
      else {
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Related Dispensary Item not found.'));
      }
    }
    else {
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'No record found.'));
      SearchResults.clear();
    }
    return null;
  }

  public PageReference processSelected() {
    string sInsertedOpp = '';
    List<string> lstDispensaryItemId = new List<string>();
    List<Dispensary_Item__c> lstTempDispensaryItem = new List<Dispensary_Item__c>();
    for(Contact oContact : SearchResults) {
      lstTempDispensaryItem.addAll(oContact.Dispensary_Items__r);
    }
    List<Dispensary_Item__c> lstDispensaryItem = new List<Dispensary_Item__c>();
    for(Dispensary_Item__c oDispensaryItem : lstTempDispensaryItem){
      if(oDispensaryItem.IsChecked__c) {
        lstDispensaryItem.add(oDispensaryItem);
        lstDispensaryItemId.add(oDispensaryItem.Id);
        lstProductId.add(oDispensaryItem.Product__c);
        lstOppId.add(oDispensaryItem.Opportunity__c);
      }
    }
    Set<string> setProduct = new Set<string>();
    setProduct.addAll(lstProductId);
    if(setProduct.size() != lstProductId.size()) {
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please select unique Dispensary Product Item.'));
      lstProductId.clear();
      return null;
    }
    if(lstDispensaryItem.size() > 0) {
      String sQuery = 'SELECT Id';
      Set<String> lstFields = new Set<String>();
      Map<String,Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
      Schema.SObjectType sobjType = schemaMap.get('Opportunity');
      Schema.DescribeSObjectResult r = sobjType.getDescribe();
      Map <String, Schema.SObjectField> fieldMap = r.fields.getMap();
      for(Schema.SObjectField sfield : fieldMap.Values()){
        schema.describefieldresult dfield = sfield.getDescribe();
        if(dfield.isCreateable()) {
          lstFields.add(String.valueOf(dfield.getname()));
          sQuery = sQuery + ', ' + String.valueOf(dfield.getname());
        }
      }
      sQuery = sQuery + ' FROM Opportunity WHERE Id in (';
      if(lstOppId.size() > 0) {
        integer intCount = 1;
        for(string oString : lstOppId) {
          if(intCount < lstOppId.size()) {
            sQuery = sQuery + '\''+oString+'\',';
          }
          else {
            sQuery = sQuery + '\''+oString+'\')';
          }
          intCount = intCount + 1;
        }
      }
      sQuery = sQuery + ' Order By CreatedDate DESC LIMIT 1';
      List<SObject> lstOpportunity = Database.query(sQuery);
      Sobject oOppnew = sobjType.newSobject();
      if(lstOpportunity.size() > 0) {
        SObject oOpportunity = lstOpportunity.get(0);
        for(String sField : lstFields) {
          if(sField != 'OwnerId' && sField != 'Amount' && sField != 'Create_Dispensary_Items__c'  && sField != 'Dispensary_Items_Created__c' && sField != 'StageName' && sField != 'Priority__c' && sField != 'Name' && sField != 'Source__c' && sField != 'CloseDate' && sField != 'Tracking_Number__c' && sField != 'AccountId') {
            oOppnew.put(sField, oOpportunity.get(sField));
          }
          else if(sField == 'Create_Dispensary_Items__c') {
            oOppnew.put('Create_Dispensary_Items__c', false);
          }
          else if(sField == 'Priority__c') {
            oOppnew.put('Priority__c', 'Other');
          }
          else if(sField == 'Name') {
            oOppnew.put('Name', sPatientLastName);
          }
          else if(sField == 'Source__c') {
            oOppnew.put('Source__c', '');
          }
          else if(sField == 'CloseDate') {
            oOppnew.put('CloseDate', Date.valueOf(System.now()));
          }
          else if(sField == 'StageName') {
            oOppnew.put('StageName', 'Order Received');
          }
          else if(sField == 'Tracking_Number__c') {
            oOppnew.put('Tracking_Number__c', '');
          }
          else if(sField == 'AccountId') {
            oOppnew.put('AccountId', sPatientAccountId);
          }
        }
        oOppnew.put('IsRefillOpportunity__c', true);
        insert oOppnew;
        if(oOppnew.id != null) {
          sInsertedOpp = oOppnew.Id;
          List<Opportunity> lstOpportunityPriceBook = [SELECT Id, Pricebook2Id FROM Opportunity WHERE Id = :oOppnew.Id AND Pricebook2Id != null LIMIT 1];
          if(lstOpportunityPriceBook.size() > 0) {
            List<PricebookEntry> lstPricebookEntry = [SELECT Id, Name, Pricebook2Id, Product2Id FROM PricebookEntry where  IsActive = true AND Product2Id in: lstProductId AND Pricebook2Id =: lstOpportunityPriceBook.get(0).Pricebook2Id];
            if(lstPricebookEntry.size() > 0) {
              Map<string, string> mapPriEntry = new Map<string, string>();
              for(PricebookEntry oPricebookEntry : lstPricebookEntry) {
                mapPriEntry.put(oPricebookEntry.Product2Id, oPricebookEntry.Id);
              }
              if(!mapPriEntry.isEmpty()) {
                List<OpportunityLineItem> lstOppItemnew = new List<OpportunityLineItem>();
                for(Dispensary_Item__c oDispensaryItem : lstDispensaryItem) {
                  OpportunityLineItem oOpportunityLineItem = new OpportunityLineItem();
                  oOpportunityLineItem.OpportunityId = oOppnew.Id;
                  if(mapPriEntry.containsKey(oDispensaryItem.Product__c)) {
                    oOpportunityLineItem.PricebookEntryId = mapPriEntry.get(oDispensaryItem.Product__c);
                  }
                  oOpportunityLineItem.UnitPrice = oDispensaryItem.Price__c;
                  oOpportunityLineItem.Quantity = oDispensaryItem.Quantity__c;
                  lstOppItemnew.add(oOpportunityLineItem);
                }
                if(lstOppItemnew.size() > 0) {
                  insert lstOppItemnew;
                }
                oOppnew.put('Create_Dispensary_Items__c', true);
                update oOppnew;
              }
            }
          }
        }
      }
    }
    if(sInsertedOpp != null && sInsertedOpp != '') {
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Opportunity has been created: '+sInsertedOpp));
    }
    return null;
  }
}
NAME OF VF PAGE - Refill_for_Patients

MY TEST CLASS WITH ONY 36% CODE COVERAGE.
 
@isTest (SeeAllData = true)
private class SearchController_Test{
  static void setupTestData(){
    test.startTest();
    String strRecordTypeId = [Select Id From RecordType Where SobjectType = 'account' and Name = 'Practice'].Id;
    account acc = new Account(Name='Test Account', Type = 'Customer', BillingCity = 'California', BillingPostalCode = '90001', BillingState = 'California', BillingStreet = 'Test', ShippingCity = 'California', ShippingPostalCode = '90001', ShippingState = 'California', ShippingStreet = 'Test', NPI__c = '123456', DEA__c = '1234567');
    insert acc;
    String conRecordTypeId = [Select Id From RecordType Where SobjectType = 'contact' and Name = 'Patient'].Id;
    Contact contact_Obj = new Contact(AccountId = acc.id, LastName = 'LastName515', RecordTypeId = conRecordTypeId);
    Insert contact_Obj;
    Opportunity oOpportunity = new Opportunity(Name = 'test', AccountId = acc.Id, New_or_Existing_Business__c = 'New Business', Patient__c = contact_Obj.Id, Doctor__c = acc.Id, Priority__c = 'Other', Bill_To_del2__c = 'BillToChooseClinic', Ship_To_del1__c = 'ShipToChooseClinic', Shipping_Preference__c = 'Medallian Free 1', StageName = 'Order Received', CloseDate = Date.Today(), Bill_To_del1__c = acc.Id, Ship_To_Clinic__c = acc.Id, Clinic__c = acc.Id, Pharmacy_Printed__c = true);
    insert oOpportunity;
    Dispensary_Item__c dispensary_item_Obj = new Dispensary_Item__c(DOB__c = Date.today(), NPI__c = 'NPI__c489', StickIt_Label_Printed__c = false, Opportunity__c = oOpportunity.id, Patient_History_Reviewed__c = false, Patient_Gender__c = 'Male', Pharmacy_Printed__c = false, Non_CPC_Requested__c = false, PT_Refused_Counseling__c = false, IsAllergy__c = false, Prescription_s_Attached__c = false, Awaiting_Information_Send_Notification__c = false, On_Backorder_Send_Notification__c = false, Too_Soon_To_Refill_Send_Notification__c = false, Awaiting_Payment_Send_Notification__c = false, IsChecked__c = true);
    Insert dispensary_item_Obj; 
    test.stopTest();
  }
  static testMethod void test_search_UseCase1(){
    List<Contact> contact_Obj  =  [SELECT AccountId,LastName from Contact];
    System.assertEquals(true,contact_Obj.size()>0);
    List<Dispensary_Item__c> dispensary_item_Obj  =  [SELECT DOB__c,NPI__c,StickIt_Label_Printed__c,Opportunity__c,Patient_History_Reviewed__c,Patient_Gender__c,Pharmacy_Printed__c,Non_CPC_Requested__c,PT_Refused_Counseling__c,IsAllergy__c,Prescription_s_Attached__c,Awaiting_Information_Send_Notification__c,On_Backorder_Send_Notification__c,Too_Soon_To_Refill_Send_Notification__c,Awaiting_Payment_Send_Notification__c, Patient__c, IsChecked__c from Dispensary_Item__c];
    System.assertEquals(true,dispensary_item_Obj.size()>0);
    SearchController obj01 = new SearchController(new ApexPages.StandardController(contact_Obj[0]));
    obj01.searchResults = contact_Obj;
    obj01.oContact = contact_Obj[0];
    obj01.oDispensaryItem = dispensary_item_Obj[0];
    obj01.lstProductId = new List<string>();
    obj01.search();
  }
  static testMethod void test_processSelected_UseCase1(){
    List<Contact> contact_Obj  =  [SELECT AccountId,LastName from Contact];
    System.assertEquals(true,contact_Obj.size()>0);
    List<Dispensary_Item__c> dispensary_item_Obj  =  [SELECT DOB__c,NPI__c,StickIt_Label_Printed__c,Opportunity__c,Patient_History_Reviewed__c,Patient_Gender__c,Pharmacy_Printed__c,Non_CPC_Requested__c,PT_Refused_Counseling__c,IsAllergy__c,Prescription_s_Attached__c,Awaiting_Information_Send_Notification__c,On_Backorder_Send_Notification__c,Too_Soon_To_Refill_Send_Notification__c,Awaiting_Payment_Send_Notification__c from Dispensary_Item__c where IsChecked__c = false];
    System.assertEquals(true,dispensary_item_Obj.size()>0);
    SearchController obj01 = new SearchController(new ApexPages.StandardController(contact_Obj[0]));
    obj01.searchResults = contact_Obj;
    obj01.oContact = contact_Obj[0];
    obj01.oDispensaryItem = dispensary_item_Obj[0];
    obj01.lstProductId = new List<string>();
    obj01.processSelected();
    
  }
 
  
}


 
THIS CODE IS WRITTEN TO SEARCH CONTACTS BY LASTNAME THROUGH SEARCH BOX IN VF PAGE.WHEN CONTACT DISPLAY IT ALSO SHOW ALL THE RELATED DISPENSORY ITEMS.MOTIVE IS TO ADD CHECKBOX BESIDE EVERY DISPENSORY ITEM AND WHEN I SELECT SOME OF THEM AND CLICK ON SUMBIT BUTTON IT WILL PERFORM AN OPERATION.

User-added image



so far my code


public class SearchController {
  public Boolean SelectedRecord {get;set;}  
  private apexpages.standardController controller {get; set; }
  private contact l;
  public set<id> conid;
  public List<contact> searchResults {get; set;}
  public List<Dispensary_Item__c> Results {get; set;}

  public string searchText {
    get{
      if (searchText==null) searchText = '';
        return searchText;
    }
    set;
  }
  public SearchController(ApexPages.StandardController controller) {
    this.controller = controller;
    this.l = (contact) controller.getRecord();
    this.SelectedRecord = false;
  }

  public PageReference search() {
    if(SearchResults == null) {
      SearchResults = new List<contact>();
  }
    else{
      SearchResults.Clear();
    }
    String qry = 'SELECT Id, LastName, FirstName,account.id,Accountid, (SELECT Name FROM Dispensary_Items__r) FROM contact WHERE LastName like \'%'+searchText+'%\' Order By LastName';
    SearchResults = Database.query(qry);
    conid = (new Map<Id,contact>(SearchResults)).keySet();
    system.debug('contactList' +conid);

    return null;
  }

  public List<cContact> contactList {get; set;}

  public List<cContact> getContacts() {
        system.debug('contactList' +conid);
 
    if(contactList == null) {
      contactList = new List<cContact>();

      for(Dispensary_Item__c c: [SELECT  Id, Name FROM Dispensary_Item__c WHERE patient__c in : conid ]) {
        contactList.add(new cContact(c,SelectedRecord));
      }
      system.debug('contactList' +contactList);
    }
      return contactList;
  }

  public PageReference processSelected() {
            system.debug('contactList' +conid);

    List<Dispensary_Item__c> selectedContacts = new List<Dispensary_Item__c>();
      for(cContact cCon: getContacts()) {
        if(cCon.selected == true) {
          selectedContacts.add(cCon.con);
        }
      }
    System.debug('These are the selected items...'+selectedContacts.size());
    for(Dispensary_Item__c con: selectedContacts) {
      system.debug(con);
    }
    contactList=null;
    return null;
  }
  public class cContact {
    public Dispensary_Item__c con {get; set;}
    public Boolean selected {get; set;}
    public cContact(Dispensary_Item__c c) {
      con = c;
      selected = false;
    }
   }  
}
                                                                                      VF
_______________________________________________________________________________________________________



<apex:page standardController="Contact" extensions="SearchController">
 <apex:form id="searchForm">
  <apex:PageBlock mode="edit">        
    <apex:pageblockSection id="searchBlockSection">
        <apex:pageBlockSectionItem id="searchBlockSectionItem">
            <apex:outputLabel >Enter Patient lastname</apex:outputLabel>
            <apex:panelGroup >
                <apex:inputtext id="searchTextBox" value="{!searchText}">
                    
                </apex:inputtext>
                <strong><apex:commandButton Id="btnSearch" action="{!search}" rerender="renderBlock" status="status" title="Search" value="Search"></apex:commandButton></strong>                    
            </apex:panelGroup>
        </apex:pageBlockSectionItem>
    </apex:pageblockSection>
    <apex:actionStatus id="status" startText="Searching... please wait..."/>        
    <apex:pageBlocksection id="renderBlock" >
    
      <apex:repeat value="{!SearchResults}" var="o"   rendered="{!NOT(ISNULL(SearchResults))}">
         <apex:pageBlock title="{!o.lastname}">
        <apex:pageBlockSection >
        <apex:outputField value="{!o.FirstName}"/>
        <apex:outputField value="{!o.Accountid}"/>
        <apex:outputField value="{!o.id}"/>
         </apex:pageBlockSection>
         </apex:PageBlock>

      
        <apex:pageBlockSection >
        <apex:pageBlockTable value="{!o.Dispensary_Items__r}" var="c">
            <apex:column value="{!c.Name}"/>
                 <apex:column headerValue="Select">
                     <apex:inputCheckbox value="{!SelectedRecord}" />   
         </apex:column>
          <apex:outputField value="{!o.FirstName}"/>
        </apex:pageBlockTable>
       <apex:commandButton action="{!processSelected}" value="Submit"/>

        </apex:pageBlockSection>
    </apex:repeat>
    
           </apex:pageBlocksection>
        </apex:PageBlock>
        </apex:form>
        </apex:page>
THIS CODE IS WRITTEN TO SEARCH CONTACTS BY LASTNAME THROUGH SEARCH BOX IN VF PAGE.WHEN CONTACT DISPLAY IT ALSO SHOW ALL THE RELATED DISPENSORY ITEMS.MOTIVE IS TO ADD CHECKBOX BESIDE EVERY DISPENSORY ITEM AND WHEN I SELECT SOME OF THEM AND CLICK ON SUMBIT BUTTON IT WILL PERFORM AN OPERATION.


User-added image



so far my code


public class SearchController {
  public Boolean SelectedRecord {get;set;}  
  private apexpages.standardController controller {get; set; }
  private contact l;
  public set<id> conid;
  public List<contact> searchResults {get; set;}
  public List<Dispensary_Item__c> Results {get; set;}

  public string searchText {
    get{
      if (searchText==null) searchText = '';
        return searchText;
    }
    set;
  }
  public SearchController(ApexPages.StandardController controller) {
    this.controller = controller;
    this.l = (contact) controller.getRecord();
    this.SelectedRecord = false;
  }

  public PageReference search() {
    if(SearchResults == null) {
      SearchResults = new List<contact>();
  }
    else{
      SearchResults.Clear();
    }
    String qry = 'SELECT Id, LastName, FirstName,account.id,Accountid, (SELECT Name FROM Dispensary_Items__r) FROM contact WHERE LastName like \'%'+searchText+'%\' Order By LastName';
    SearchResults = Database.query(qry);
    conid = (new Map<Id,contact>(SearchResults)).keySet();
    system.debug('contactList' +conid);

    return null;
  }

  public List<cContact> contactList {get; set;}

  public List<cContact> getContacts() {
        system.debug('contactList' +conid);
 
    if(contactList == null) {
      contactList = new List<cContact>();

      for(Dispensary_Item__c c: [SELECT  Id, Name FROM Dispensary_Item__c WHERE patient__c in : conid ]) {
        contactList.add(new cContact(c,SelectedRecord));
      }
      system.debug('contactList' +contactList);
    }
      return contactList;
  }

  public PageReference processSelected() {
            system.debug('contactList' +conid);

    List<Dispensary_Item__c> selectedContacts = new List<Dispensary_Item__c>();
      for(cContact cCon: getContacts()) {
        if(cCon.selected == true) {
          selectedContacts.add(cCon.con);
        }
      }
    System.debug('These are the selected items...'+selectedContacts.size());
    for(Dispensary_Item__c con: selectedContacts) {
      system.debug(con);
    }
    contactList=null;
    return null;
  }
  public class cContact {
    public Dispensary_Item__c con {get; set;}
    public Boolean selected {get; set;}
    public cContact(Dispensary_Item__c c) {
      con = c;
      selected = false;
    }
   }  
}
                                                                                      VF
_______________________________________________________________________________________________________



<apex:page standardController="Contact" extensions="SearchController">
 <apex:form id="searchForm">
  <apex:PageBlock mode="edit">        
    <apex:pageblockSection id="searchBlockSection">
        <apex:pageBlockSectionItem id="searchBlockSectionItem">
            <apex:outputLabel >Enter Patient lastname</apex:outputLabel>
            <apex:panelGroup >
                <apex:inputtext id="searchTextBox" value="{!searchText}">
                    
                </apex:inputtext>
                <strong><apex:commandButton Id="btnSearch" action="{!search}" rerender="renderBlock" status="status" title="Search" value="Search"></apex:commandButton></strong>                    
            </apex:panelGroup>
        </apex:pageBlockSectionItem>
    </apex:pageblockSection>
    <apex:actionStatus id="status" startText="Searching... please wait..."/>        
    <apex:pageBlocksection id="renderBlock" >
    
      <apex:repeat value="{!SearchResults}" var="o"   rendered="{!NOT(ISNULL(SearchResults))}">
         <apex:pageBlock title="{!o.lastname}">
        <apex:pageBlockSection >
        <apex:outputField value="{!o.FirstName}"/>
        <apex:outputField value="{!o.Accountid}"/>
        <apex:outputField value="{!o.id}"/>
         </apex:pageBlockSection>
         </apex:PageBlock>

      
        <apex:pageBlockSection >
        <apex:pageBlockTable value="{!o.Dispensary_Items__r}" var="c">
            <apex:column value="{!c.Name}"/>
                 <apex:column headerValue="Select">
                     <apex:inputCheckbox value="{!SelectedRecord}" />   
         </apex:column>
          <apex:outputField value="{!o.FirstName}"/>
        </apex:pageBlockTable>
       <apex:commandButton action="{!processSelected}" value="Submit"/>

        </apex:pageBlockSection>
    </apex:repeat>
    
           </apex:pageBlocksection>
        </apex:PageBlock>
        </apex:form>
        </apex:page>
THIS CODE IS WRITTEN TO SEARCH CONTACTS BY LASTNAME THROUGH SEARCH BOX IN VF PAGE.WHEN CONTACT DISPLAY IT ALSO SHOW ALL THE RELATED DISPENSORY ITEMS.MOTIVE IS TO ADD CHECKBOX BESIDE EVERY DISPENSORY ITEM AND WHEN I SELECT SOME OF THEM AND CLICK ON SUMBIT BUTTON IT WILL PERFORM AN OPERATION.



User-added image



NOW when i select the checkbox and click on submit i get nothing(check by debug) So motive is when i select the checkbox and click on submit i will be able to get that Dispensory item so that i can perform some operation from that by submit function

here is the controller class

public class SearchController {
  public Boolean SelectedRecord {get;set;}  
  private apexpages.standardController controller {get; set; }
  private contact l;
  public List<contact> searchResults {get; set; }
  public string searchText {
    get{
      if (searchText==null) searchText = '';
        return searchText;
    }
    set;
  }
  public SearchController(ApexPages.StandardController controller) {
    this.controller = controller;
    this.l = (contact) controller.getRecord();
    this.SelectedRecord = false;
  }

  public PageReference search() {
    if(SearchResults == null) {
      SearchResults = new List<contact>();
  }
    else{
      SearchResults.Clear();
    }
    String qry = 'SELECT Id, LastName, FirstName,account.id,Accountid, (SELECT Name FROM Dispensary_Items__r) FROM contact WHERE LastName like \'%'+searchText+'%\' Order By LastName';
    SearchResults = Database.query(qry);
    return null;
  }

  public List<cContact> contactList {get; set;}

  public List<cContact> getContacts() {
    if(contactList == null) {
      contactList = new List<cContact>();
      for(Dispensary_Item__c c: [SELECT  Id, Name FROM Dispensary_Item__c WHERE Id =: SearchResults[0].id]) {
        contactList.add(new cContact(c));
      }
      system.debug('contactList' +contactList);
    }
      return contactList;
  }

  public PageReference processSelected() {
    List<Dispensary_Item__c> selectedContacts = new List<Dispensary_Item__c>();
      for(cContact cCon: getContacts()) {
        if(cCon.selected == true) {
          selectedContacts.add(cCon.con);
        }
      }
    System.debug('These are the selected items...'+selectedContacts.size());
    for(Dispensary_Item__c con: selectedContacts) {
      system.debug(con);
    }
    contactList=null;
    return null;
  }
  public class cContact {
    public Dispensary_Item__c con {get; set;}
    public Boolean selected {get; set;}
    public cContact(Dispensary_Item__c c) {
      con = c;
      selected = false;
    }
   }  
}

here is the vf page

<apex:page standardController="Contact" extensions="SearchController">
 <apex:form id="searchForm">
  <apex:PageBlock mode="edit">        
    <apex:pageblockSection id="searchBlockSection">
        <apex:pageBlockSectionItem id="searchBlockSectionItem">
            <apex:outputLabel >Enter Patient lastname</apex:outputLabel>
            <apex:panelGroup >
                <apex:inputtext id="searchTextBox" value="{!searchText}">
                    
                </apex:inputtext>
                <strong><apex:commandButton Id="btnSearch" action="{!search}" rerender="renderBlock" status="status" title="Search" value="Search"></apex:commandButton></strong>                    
            </apex:panelGroup>
        </apex:pageBlockSectionItem>
    </apex:pageblockSection>
    <apex:actionStatus id="status" startText="Searching... please wait..."/>        
    <apex:pageBlocksection id="renderBlock" >
    
      <apex:repeat value="{!SearchResults}" var="o"   rendered="{!NOT(ISNULL(SearchResults))}">
         <apex:pageBlock title="{!o.lastname}">
        <apex:pageBlockSection >
        <apex:outputField value="{!o.FirstName}"/>
        <apex:outputField value="{!o.Accountid}"/>
        <apex:outputField value="{!o.id}"/>
         </apex:pageBlockSection>
         </apex:PageBlock>

      
        <apex:pageBlockSection >
        <apex:pageBlockTable value="{!o.Dispensary_Items__r}" var="c">
            <apex:column value="{!c.Name}"/>
                 <apex:column headerValue="Select">
                     <apex:inputCheckbox value="{!SelectedRecord}" />   
         </apex:column>
          <apex:outputField value="{!o.FirstName}"/>
        </apex:pageBlockTable>
       <apex:commandButton action="{!processSelected}" value="Submit"/>

        </apex:pageBlockSection>
    </apex:repeat>
    
           </apex:pageBlocksection>
        </apex:PageBlock>
        </apex:form>
        </apex:page>

 
Product  AND Inventory_Change__c HAVE LOOKUP RELATIONSHIP.PRODUCT IS THE PARENT OF Inventory_Change__c .TRIGGER IS UPDATEING In_Stock__c FIELD ON THE BASIS OF RECORD TYPE CHANGE.
____________________________________________________________________________________________________________________
_____________________________________TRIGGER_______________________________________________________________________
trigger InventoryChangeTrigger on Inventory_Change__c (after update) {
  if(Trigger.isAfter && Trigger.isUpdate) {
    for (Inventory_Change__c oIC : Trigger.new){
      Product2  oP = [SELECT Id, In_Stock__c  FROM Product2 WHERE Id = :oIC.Product__c];
      Id Rid = Schema.SObjectType.Inventory_Change__c.getRecordTypeInfosByName().get('Reduction').getRecordTypeId();
      Id Aid = Schema.SObjectType.Inventory_Change__c.getRecordTypeInfosByName().get('Addition').getRecordTypeId();
      if(trigger.oldmap.get(oIC.id).RecordTypeid != trigger.newmap.get(oIC.id).RecordTypeid){
        if(oIC.RecordTypeid == Rid ){
          oP.In_Stock__c = oP.In_Stock__c - oIC.Quantity__c;
        }
        if(oIC.RecordTypeid == Aid ){
          oP.In_Stock__c = oP.In_Stock__c + oIC.Quantity__c;
        }
      }
    update oP;
    }
  }
}
PRODUCT IS A STANDARD OBJECT AND Inventory_Change__c IS A CUSTOM OBJECT WITH ONLY ONE FIELD REQUIRED THAT IS "RECORD TYPE"

__________________________________________________________________________________________________________________________
                                                                                           TEST CLASS
____________________________________________________________________________________________________________________________


@isTest
public class InventoryChangeTrigger_Test{
  static testMethod void test_Inventory_ChangeTrigger(){
    test.startTest();
    product2 product2_Obj  = new product2(Name = 'Name735', IsActive = true, In_Stock__c = 19, Out_of_Stock__c = false);
    insert product2_Obj;
    Inventory_Change__c inventory_change_Obj = new Inventory_Change__c(RecordTypeId = '01236000000STHgAAO',Quantity__c = 16,product__c = product2_Obj.id );
    Insert inventory_change_Obj;
    product2 product2_Obj1 = [select id,Name,In_Stock__c from product2 where Name = 'Name735'  LIMIT 1];
    product2_Obj1.name= 'xyz';
    product2_Obj1.In_Stock__c = 3;
    update product2_Obj1;
     
    test.stopTest();
  }
}
PLZ HELP ME HOW GET ConvertedAccountid TO WHICH LEAD IS GEETING CONVERTED
IT IS SHOWING NULL IN SYSTEM DEBUG.
trigger converted on Lead (after insert)
{
set<id> s= new set<id>();
list<account> acc = new list<account>();
list<contact> cs = new list<contact>();
list<task> tsk = new list<task>();
list<opportunity> ops = new list<opportunity>();
for (lead ls:trigger.new)
{

s.add(ls.id);

}
for(lead l:[select id,ConvertedAccountId,company from lead where id in:s])
{
 system.debug('*************ConvertedAccountId************'+l.ConvertedAccountId);
account a = new account();
a.id = l.ConvertedAccountId;
a.name = l.company;

acc.add(a);
system.debug('@@@@@@'+a);
opportunity o = new opportunity();
o.name = l.company;
o.accountid = l.ConvertedAccountId;
o.StageName = 'Prospecting';
o.CloseDate = system.today();

ops.add(o);
system.debug('@@@@@@'+o);
task t = new task();
t.subject = 'converted lead task';
t.whatid = l.ConvertedAccountId;
t.priority = 'Normal';
t.status = 'Not Started';

tsk.add(t);
system.debug('@@@@@@'+t);
contact c = new contact();
c.lastname = l.company;
c.accountid = l.ConvertedAccountId;

cs.add(c);
system.debug('@@@@@@'+c);
}
insert acc;
insert cs;
insert tsk;
insert ops;


}
latest__c is rollup summary field = max(opportunity).This trigger is mapping latest opportunity amount into account field (acc.opty_amount__c).
trigger latest on Account (after update)  {    
  if(checkRecursive.runOnce())  
  {    set<id> acctid =new set<id>();    
  list<account> accnt=new list<account>();  
  for(account acc:trigger.new)  
  {       acctid.add(acc.id);           }          
  for(account acc : [select id,name,opty_amount__c,latest__c(select id,amount,CreatedDate from opportunities) from account where id  in:acctid])    {    list <opportunity> oppo = acc.opportunities;    
for(opportunity op:oppo)   
 {    if(acc.latest__c == op.CreatedDate)    
      {    acc.opty_amount__c=op.amount;  
      }
 
  }          
    accnt.add(acc);    
  }    
 update accnt;  
}
THIS TEST CLASS IS GIVING 80% COVERAGE PLZ HELP ME TO CONVERT IT TO 100%.
@isTest
private class UpdateAccount_Test
{  public static testMethod void TestUpdateAccount() 
  {        Account acc = new Account();           
         acc.Name = 'Test';              
         insert acc;         
         opportunity oppo = new opportunity();          
         oppo.accountid  =acc.id;     
         oppo.amount = 50000.00;                        
        update acc;    
        }  
 }
I want regex for this format and filter out 123456 if match the current format
PO # 123456
PO# 123456
PO #123456
P.O. # 123456
P.O.# 123456
P.O. #123456

We have to filter substring from string notes__c field. my regex is only working for PO #123456 and P.O. #123456
tried PO# (\\S+)\\s not working
Matcher rm = r.matcher(oOrder.Notes__c); 
Pattern r = Pattern.compile('PO #(\\S+)\\s'); 

if(rm.find()) {
 string res2 = rm.group(1); 
oOrder.test__c = res2; 
}

 
Product  AND Inventory_Change__c HAVE LOOKUP RELATIONSHIP.PRODUCT IS THE PARENT OF Inventory_Change__c .TRIGGER IS UPDATEING In_Stock__c FIELD ON THE BASIS OF RECORD TYPE CHANGE.
____________________________________________________________________________________________________________________
_____________________________________TRIGGER_______________________________________________________________________
trigger InventoryChangeTrigger on Inventory_Change__c (after update) {
  if(Trigger.isAfter && Trigger.isUpdate) {
    for (Inventory_Change__c oIC : Trigger.new){
      Product2  oP = [SELECT Id, In_Stock__c  FROM Product2 WHERE Id = :oIC.Product__c];
      Id Rid = Schema.SObjectType.Inventory_Change__c.getRecordTypeInfosByName().get('Reduction').getRecordTypeId();
      Id Aid = Schema.SObjectType.Inventory_Change__c.getRecordTypeInfosByName().get('Addition').getRecordTypeId();
      if(trigger.oldmap.get(oIC.id).RecordTypeid != trigger.newmap.get(oIC.id).RecordTypeid){
        if(oIC.RecordTypeid == Rid ){
          oP.In_Stock__c = oP.In_Stock__c - oIC.Quantity__c;
        }
        if(oIC.RecordTypeid == Aid ){
          oP.In_Stock__c = oP.In_Stock__c + oIC.Quantity__c;
        }
      }
    update oP;
    }
  }
}
PRODUCT IS A STANDARD OBJECT AND Inventory_Change__c IS A CUSTOM OBJECT WITH ONLY ONE FIELD REQUIRED THAT IS "RECORD TYPE"

__________________________________________________________________________________________________________________________
                                                                                           TEST CLASS
____________________________________________________________________________________________________________________________


@isTest
public class InventoryChangeTrigger_Test{
  static testMethod void test_Inventory_ChangeTrigger(){
    test.startTest();
    product2 product2_Obj  = new product2(Name = 'Name735', IsActive = true, In_Stock__c = 19, Out_of_Stock__c = false);
    insert product2_Obj;
    Inventory_Change__c inventory_change_Obj = new Inventory_Change__c(RecordTypeId = '01236000000STHgAAO',Quantity__c = 16,product__c = product2_Obj.id );
    Insert inventory_change_Obj;
    product2 product2_Obj1 = [select id,Name,In_Stock__c from product2 where Name = 'Name735'  LIMIT 1];
    product2_Obj1.name= 'xyz';
    product2_Obj1.In_Stock__c = 3;
    update product2_Obj1;
     
    test.stopTest();
  }
}
PLZ HELP ME HOW GET ConvertedAccountid TO WHICH LEAD IS GEETING CONVERTED
IT IS SHOWING NULL IN SYSTEM DEBUG.
trigger converted on Lead (after insert)
{
set<id> s= new set<id>();
list<account> acc = new list<account>();
list<contact> cs = new list<contact>();
list<task> tsk = new list<task>();
list<opportunity> ops = new list<opportunity>();
for (lead ls:trigger.new)
{

s.add(ls.id);

}
for(lead l:[select id,ConvertedAccountId,company from lead where id in:s])
{
 system.debug('*************ConvertedAccountId************'+l.ConvertedAccountId);
account a = new account();
a.id = l.ConvertedAccountId;
a.name = l.company;

acc.add(a);
system.debug('@@@@@@'+a);
opportunity o = new opportunity();
o.name = l.company;
o.accountid = l.ConvertedAccountId;
o.StageName = 'Prospecting';
o.CloseDate = system.today();

ops.add(o);
system.debug('@@@@@@'+o);
task t = new task();
t.subject = 'converted lead task';
t.whatid = l.ConvertedAccountId;
t.priority = 'Normal';
t.status = 'Not Started';

tsk.add(t);
system.debug('@@@@@@'+t);
contact c = new contact();
c.lastname = l.company;
c.accountid = l.ConvertedAccountId;

cs.add(c);
system.debug('@@@@@@'+c);
}
insert acc;
insert cs;
insert tsk;
insert ops;


}
trigger trigger52 on India__c (after insert) {
  list<san_francisco__c> con =new list<san_francisco__c>();  

    for(India__c h : trigger.new){
     san_francisco__c s = new san_francisco__c();
      s.Name=h.Name;
        s.Company__c=h.Company__c;
        s.Mobile__c=h.Mobile__c;
           s.Email__c=h.Email__c;
        con.add(s);
        
        
    }
    insert con;
}
latest__c is rollup summary field = max(opportunity).This trigger is mapping latest opportunity amount into account field (acc.opty_amount__c).
trigger latest on Account (after update)  {    
  if(checkRecursive.runOnce())  
  {    set<id> acctid =new set<id>();    
  list<account> accnt=new list<account>();  
  for(account acc:trigger.new)  
  {       acctid.add(acc.id);           }          
  for(account acc : [select id,name,opty_amount__c,latest__c(select id,amount,CreatedDate from opportunities) from account where id  in:acctid])    {    list <opportunity> oppo = acc.opportunities;    
for(opportunity op:oppo)   
 {    if(acc.latest__c == op.CreatedDate)    
      {    acc.opty_amount__c=op.amount;  
      }
 
  }          
    accnt.add(acc);    
  }    
 update accnt;  
}
THIS TEST CLASS IS GIVING 80% COVERAGE PLZ HELP ME TO CONVERT IT TO 100%.
@isTest
private class UpdateAccount_Test
{  public static testMethod void TestUpdateAccount() 
  {        Account acc = new Account();           
         acc.Name = 'Test';              
         insert acc;         
         opportunity oppo = new opportunity();          
         oppo.accountid  =acc.id;     
         oppo.amount = 50000.00;                        
        update acc;    
        }  
 }
Hi
I have created an apex trigger to update contact address when the account address is changed. The code worked fine for already created accounts, but when I have created a new account the following error was thrown and I was not able to save the account. Please help me.

Error: updateContact: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.updateContact: line 33, column 1​
 
trigger updateContact on Account (after insert, after update) {
    List<Contact> contactsForUpsert = New List<Contact>();

    Map<Id, Contact> contactsByAccountId = new Map<Id, Contact>();
    List<Contact> contacts = [SELECT Id,
                                     AccountId,
                                     mailingstreet,
                                     mailingcity,
                                     mailingstate,
                                     mailingpostalcode
                            FROM Contact WHERE AccountId IN: Trigger.newMap.keySet()];
    for (Contact cont: contacts) {
        contactsByAccountId.put(cont.accountId, cont);
    }

    for (Account account: Trigger.new) {

        Account old;
        if (Trigger.isUpdate) {
            old = Trigger.oldMap.get(account.Id);
        }

        Boolean isShippingAddressChangedOrNew = Trigger.isInsert ? true :
                                                (   account.ShippingStreet != old.ShippingStreet
                                                 || account.ShippingCity != old.ShippingCity
                                                 || account.ShippingState != old.ShippingState
                                                 || account.ShippingPostalCode != old.ShippingPostalCode
                                                 || account.ShippingCountry != old.ShippingCountry) ? true : false;

        if (isShippingAddressChangedOrNew) {
            Contact relatedContact = contactsByAccountId.get(account.Id);
           
            relatedContact.mailingstreet     = account.Shippingstreet;
            relatedContact.mailingcity       = account.Shippingcity;
            relatedContact.mailingstate      = account.Shippingstate;
            relatedContact.mailingpostalcode = account.shippingpostalcode;
            contactsForUpsert.add(relatedContact);
        

    }

    try {
        upsert contactsForUpsert;
    } catch(Dmlexception e) {
        System.debug(LoggingLevel.ERROR, 'Contact insert from createopp.trigger has failed with message:' + e.getMessage());
    }
}
}

 
  • January 23, 2018
  • Like
  • 0