• SFDC Guest
  • NEWBIE
  • 178 Points
  • Member since 2015
  • SFDC Developer
  • Accenture Services Pvt Ltd, Hyderabad


  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 36
    Questions
  • 65
    Replies
Hi
 
I have below code where I am trying to use inline editing for Status field. Inline editing is not working.
Can anybody help me where I am going wrong.
 
<apex:form >
                <apex:pageBlock >
               <apex:pageBlockTable value="{!caseList}" var="ca">
               <apex:commandButton action="{!edit}" id="editButton" value="Edit"/>
                <apex:commandButton action="{!save}" id="saveButton" value="Save"/>
                <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
               <apex:column value="{!ca.CaseNumber}"/>
                 <apex:column headerValue="Status">
                       <apex:outputField value="{!ca.status}">
                           <apex:inlineEditSupport showOnEdit="saveButton, cancelButton" hideOnEdit="editButton" event="ondblclick" changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>
 
                      </apex:outputField>
 
                   </apex:column>
 
                  </apex:pageBlockTable>
           <apex:commandbutton value="save" action="{!save1}"/>
 
      
           </apex:pageBlock>
            </apex:form>
 
Thanks & Regards
Sushmita Sikha
 
I have written trigger to create a contact and assign it community user before user is created. But I am getting mixed DML issue due to the insertion setup&non setup objects in one transation.
Please show me how to move below logic in future method of helper class. We cant pass List<User> as parameter in future method. Plz let me know how to pass ids or strings in below logic.

Here is the trigger:
 
trigger CreateContact on User (before insert) {

   List<User> listUser = new List<User>();  
   for (User usr : trigger.new)   
   {  
     if (String.isBlank(usr.contactId))   
     {  
       listUser.add(usr);  
     }  
   }  
   if (listUser.size() > 0)   
   {  
    List<Contact> newContacts = new List<Contact>();  
    Map<String, User> userNameMap = new Map<String, User>();  
     //Create Contact For Each User  
     for (User usr : listUser)   
     {  
       String contactLastName = usr.lastname;  
       userNameMap.put(contactLastName,usr);  
       Contact con = new Contact(LastName = contactLastName);  
       newContacts.add(con);  
     }  
     Insert newContacts;  
     for (Contact con : newContacts)   
     {  
       //Put Contact Id's on Contacts  
       if (userNameMap.containsKey(con.LastName))   
       {  
         userNameMap.get(con.LastName).contactId = con.Id;  
       }  
     }  
   }   
 }

 
I have written a trigger to create a contact and assign it to Customer Community user as user.contactId whenever user is created from data loader. But I am getting mixed DML issue. I know that non setup and setup objects cannot be inserted. But please help how to convert below logic into future method in helper class. Thanks in advance.
 
trigger CreateContact on User (before insert) {

   List<User> listUser = new List<User>();  
   for (User usr : trigger.new)   
   {  
     if (String.isBlank(usr.contactId))   
     {  
       listUser.add(usr);  
     }  
   }  
   if (listUser.size() > 0)   
   {  
    List<Contact> newContacts = new List<Contact>();  
    Map<String, User> userNameMap = new Map<String, User>();  
     //Create Contact For Each User  
     for (User usr : listUser)   
     {  
       String contactLastName = usr.lastname;  
       userNameMap.put(contactLastName,usr);  
       Contact con = new Contact(LastName = contactLastName, Description = 'this is created by AutoCreateAccount trigger');  
       newContacts.add(con);  
     }  
     Insert newContacts;  
     for (Contact con : newContacts)   
     {  
       //Put Contact Id's on Contacts  
       if (userNameMap.containsKey(con.Name))   
       {  
         userNameMap.get(con.Name).contactId = con.Id;  
       }  
     }  
   }   
 }

Thanks.
Please let me know how to set timeout in lightning component controller. Thanks in advance.

     
Lightning javascript controller:

        openModel: function(component, event, helper) {
          var selectedItem = event.currentTarget;
           var index = selectedItem.dataset.record;
           var action = component.get("c.getRec");
           action.setParams({"caseValue": index});
           
           action.setCallback(this, function(response) {
                var state = response.getState();
               //alert(' data is:' + JSON.stringify(response.getReturnValue()));
                if (state === "SUCCESS") {
                    component.set("v.recObj", response.getReturnValue());
                }
                else {
                    console.log("Failed with state: " + state);
                }
            });
            $A.enqueueAction(action);
        
           // Set isModalOpen attribute to true
          component.set("v.isModalOpen", true);
           
          //find modal using aura id
        var modal = component.find("myModal");
        var modalBackdrop = component.find("myModal-Back");
    
       // Now add and remove class
        $A.util.addClass(modal, 'slds-fade-in-open');
        $A.util.addClass(modalBackdrop, 'slds-fade-in-open');
    }

 
Hi All,

I have written lightning component to display accounts. Can you please let me know how to display popup modal (with Account Name, Description) when keeping the mouse hover on Account name using overlay library component. recordviewform component should be called and displayed as modal when keeping mouse on account name.  Thanks in advance.
 
AccountListController.cmp

<aura:component controller="AccountListController"
                implements="flexipage:availableForAllPageTypes,lightning:actionOverride,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:appHostable" >
    
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"/>
    
</aura:component>


JS Controller:

({
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
                {label: 'Industry', fieldName: 'Industry', type: 'text'},
                {label: 'Type', fieldName: 'Type', type: 'Text'}
            ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})


Server Side Controller:

public class AccountListController {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
    }
    
}

recordviewform.cmp:

<aura:component>
    <lightning:recordViewForm recordId="{recordId}" objectApiName="Account">
        <div class="slds-box">
            <lightning:outputField fieldName="Name" />
            <lightning:outputField fieldName="Description" />
        </div>
    </lightning:recordViewForm>
</aura:component>

 
Hi All. I have written a lightning component to search records based on input given.

Please let me know to how to search records based on picklist value selected like if new cases picklist value selected then cases with new status should be displayed, if closed cases picklistvalue selected then closed cases should be displayed. Please help. Thanks in advance.
 
Controller:

public class caseList1 {
	@AuraEnabled
    public static List<sObject> fetchData() {
        //Query and return list of Contacts
        List<SObject> objRecords = [SELECT Status, Subject from Case LIMIT 10];
        return objRecords;
    }
}
 
Lightning component:

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" 
                controller="caseList1">
    <!-- attributes -->
    <aura:attribute name="data" type="Map"/>
    <aura:attribute name="filteredData" type="Map"/>
    <aura:attribute name="columns" type="List"/>


    <!-- handlers-->
    <aura:handler name="init" value="{!this }" action="{!c.init }"/>

    	<span>
        	<lightning:input onchange="{!c.searchTable}" type="search" label="Searh" variant="label-hidden" placeholder="Enter search term" aura:id="SearchBox"/>
        </span>
    	<br/>
               
                <lightning:datatable
            columns="{!v.columns}"
            data="{!v.filteredData}"
            keyField="id"
        />
    
</aura:component>

js
({
    init: function (cmp, event, helper) {
        cmp.set('v.columns', [
            { label: 'Status', fieldName: 'Status', type: 'text' },
            { label: 'Subject', fieldName: 'Subject', type: 'text' }
        ]);
        var action = cmp.get("c.fetchData");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set("v.data", response.getReturnValue());
                cmp.set("v.filteredData", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    searchTable : function(cmp,event,helper) {
        var allRecords = cmp.get("v.data");
        var searchFilter = event.getSource().get("v.value").toUpperCase();
        
        var tempArray = [];
        var i;

        for(i=0; i < allRecords.length; i++){
            if((allRecords[i].Status && allRecords[i].Status.toUpperCase().indexOf(searchFilter) != -1) ||
               (allRecords[i].Subject && allRecords[i].Subject.toUpperCase().indexOf(searchFilter) != -1 ))
            {
                tempArray.push(allRecords[i]);
            }
        }
        cmp.set("v.filteredData",tempArray);
    }
})

controller
Hi All,
My requirement is update previous contact as non primary if new contact is primary..
Can you please help me what to write in below trigger. Thanks in advance.
 
Trigger updatePrimaryCheckbox2 on Contact(after insert, after update) {
   Map < Id, Contact > accConMap = new Map < Id, Contact > ();
   List < Contact > conList = new List < Contact > ();
   if (Trigger.isInsert || Trigger.isUpdate) {
    for (Contact cont: Trigger.New) {
     if (cont.AccountId != null && cont.IsPrimaryContact__c == true) {
      accConMap.put(cont.AccountId, cont);
     }
    }
   }
   for (Contact con: [select id, AccountId, IsPrimaryContact__c, Description from contact
     where accountid IN: accConMap.keyset()
    ]) {
    if (con != null && accConMap.containsKey(con.AccountId)) {
    // here logic
    // logic
     conList.add(con);
    }
   }
   update conList;
  }

 
Hi All, can u please help me with below trigger. Thanks in advance.

Req: Parent object have two child objects.They are child1, child2. If child1 is inserted then child2 Description field should be updated with child1 Description.

Objects: ParentObj
Child1 object ==> fields Name, Description
Child2 object ==> fields Name, Description
Hi. Can you please keep below trigger into helper class.
 
trigger InvoiceSum on Invoice_Items__c (after insert, after delete, after undelete, after update) {
    set<Id> invIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Invoice_Items__c invItem: Trigger.new){
			if(Trigger.isInsert || Trigger.isUndelete || (invItem.Amount__c != Trigger.oldMap.get(invItem.Id).Amount__c || invItem.InvoiceFK__c != Trigger.oldMap.get(invItem.Id).InvoiceFK__c))
				invIdSet.add(invItem.InvoiceFK__c);            
        }
    }    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Invoice_Items__c invItem: Trigger.old){
            if(Trigger.isDelete || (invItem.Amount__c != Trigger.newMap.get(invItem.Id).Amount__c || invItem.InvoiceFK__c != Trigger.newMap.get(invItem.Id).InvoiceFK__c))
				invIdSet.add(invItem.InvoiceFK__c);
        }
    }       
    List<Invoice__c> invList = [select id, Ammount__c, (Select Id, Amount__c from Invoice_Items__r) from Invoice__c Where ID IN: invIdSet];    
    for(Invoice__c inv : invList){
        
        inv.Ammount__c = 0;
        for(Invoice_Items__c invItem : inv.Invoice_Items__r) {
			inv.Ammount__c += invItem.Amount__c;
        }
    }
    update invList;
}

​​​​​​​
Hi All, Can you please help me to convert below logic into helper class. I am getting exception as attempt to deference null object.  Thanks.
 
trigger contactAmountSum on Contact (after insert, after delete, after undelete, after update) {
    set<Id> accIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Contact conObj: Trigger.new){
			if(Trigger.isInsert || Trigger.isUndelete || (conObj.Amounts__c != Trigger.oldMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.oldMap.get(conObj.Id).AccountId))
				accIdSet.add(conObj.AccountId);            
        }
    }    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Contact conObj: Trigger.old){
            if(Trigger.isDelete || (conObj.Amounts__c != Trigger.newMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.newMap.get(conObj.Id).AccountId))
				accIdSet.add(conObj.AccountId);
        }
    }       
    List<Account> accList = [select id, Amounts__c, (Select Id, Amounts__c from contacts) from Account Where ID IN: accIdSet];    
    for(Account acc : accList){
        
        acc.Amounts__c = 0;
        for(Contact conObj : acc.contacts) {
			acc.Amounts__c += conObj.Amounts__c;
        }
    }
    update accList;
}

Below is the helper class:
 
public class contactAmountSumHelperClass
{
    public static void updateContactCountonAccount(Map<Id, Contact> newContactMap, Map<Id, Contact> oldContactMap)
    {
        Set<Id> accIdSet = new set<Id>();
                
        for(Contact con: newContactMap.values())
        {
            if(con.AccountId != null){
                if(con.Amounts__c != oldContactMap.get(con.Id).Amounts__c ||
                    con.AccountId != oldContactMap.get(con.Id).AccountId){
                    accIdSet.add(con.AccountId);
                }
            }
        }
        
        List<Account> accList = [select id, Amounts__c,Description, (Select Id, Amounts__c from contacts ) from Account 
                                 Where ID IN: accIdSet ];    
        for(Account acc : accList)
        {        
            acc.Amounts__c = 0;
            for(Contact conObj : acc.contacts)
            {  
                acc.Amounts__c += conObj.Amounts__c; 
            }
        }
        update accList; 
    }
}

 
Hi All,

Can someone please help me resolve this issue.
I am getting error as "SampleClass.cls Method sampleMethod at line 3 of classes\SampleClass.cls gets user input from the strVar element. This element’s value then flows through the code without being properly sanitized or validated, and is eventually used in a database query in method sampleMethod at line 3 of classes\SampleClass.cls. This may enable an SOQL Injection attack. line no: 2, 5, 6" in checkmarx report. Thanks in advance.

Below is code:
 
public class SampleClass {
public String strVar {get; set;};
public void sampleMethod(){
if(strVar != null){     
    strVar = strVar.trim();
    List<String> varList = strVar.split(' ');   
    //logic
    String str1;
    String qString =  'select id, Description FROM Account';
    if(varList.size()==1){
        str1 = varList.get(0);
        queryStr+= ' and (Account.Name like \'%' + str1 + '%\')'; 
    }
}
}
}
Issue at below piece of code:

public String strVar {get; set;};
public void sampleMethod(){
if(strVar != null){
strVar = strVar.trim();
List<String> varList = strVar.split(' ');

 
Hi All,

I am using below trigger to update child records. Can someone please convert logic into helper class and call it from trigger. Thanks in advance.
 
trigger ContactUpdate on Account (after update) {
    Map < Id,  Account > mapAccount = new Map < Id, Account >();
    List<Contact> listContact = new List<Contact>();
   
    for(Account acct : trigger.new)
        mapAccount.put(acct.Id, acct);
   
    listContact = [ SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
   
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
        }
        update listContact;
    }
}


 
Hi All,

Please help me to write test class for below class. I have wrote test class but it's not covering.
 
public class eventClass{

// Method to validate start and End Time on events
    public static void ValidateStartEndTime(List<Event> evts) {
        for(Event ev: evts)
        {
            if(ev.StartDateTime.time() < Time.newInstance(7, 30, 0, 0))
            {
                ev.StartDateTime.addError('Start time should be greater than or equals to 7:30 AM');
            }
            if(ev.EndDateTime.time() > Time.newInstance(18, 00, 0, 0))
            {
                ev.EndDateTime.addError('End time should be less than or equals to 6 PM');
            }
        }
    }
}

Test class:
 
@isTest
public class eventClass_Test {

    static testMethod void testMethod1(){
       
        Event e = new Event();
        e.StartDateTime = Datetime.newInstance(2019, 1, 1, 08, 30, 00);
		e.EndDateTime = Datetime.newInstance(2019, 1, 1, 17, 30, 00);
        e.Subject = 'Meeting'; 
        insert e; 
              
        List<Event> eventRecs = new List<Event>();
        eventRecs.add(e);
        eventClass.ValidateStartEndTime(eventRecs);
      
    }

​​​​​​​Thanks
Hi All, Please let me know how to associate Standard Surveys with Case objects. I have created Survey using Surveys tab to collect feedback from users. I want to track that survey for closed cases. 

For associating surveys with cases, I have created a lookup field to Case object from SurveyResponse object.

I would like to know how to pass Case parameters in survey link.
Below is the sample survey link:

https://sample-dev-ed.my.salesforce.com/survey/runtimeApp.app?invitationId=0Ki6F0000001Lig&surveyName=sample_survey&UUID=656929be-435f-4e02-a2f3-d6daf1d57b19
I am trying to get the two values of two picklist values for one controlling field. Example if Country is Controlling field then State Names and State Code code should be fetched but I am getting only one dependent values for state names picklist field. Please help me.
 
public class CustomController{

   @AuraEnabled 
    public static Map<String, List<String>> getDependentMap(sObject objDetail, string contrfieldApiName,string depfieldApiName, string depfieldApiName2) {
        String controllingField = contrfieldApiName.toLowerCase();
        String dependentField = depfieldApiName.toLowerCase();

        Map<String,List<String>> objResults = new Map<String,List<String>>();

        //Schema.sObjectType objType = objDetail.getSObjectType().getDescribe().getName();
        /*if (objType==null){
            return objResults; 
        }*/
        Map<String, Schema.SObjectField> objFieldMap = objDetail.getSObjectType().getDescribe().fields.getMap();

        if (!objFieldMap.containsKey(controllingField) || !objFieldMap.containsKey(dependentField)){
            return objResults;     
        }

        Schema.SObjectField theField = objFieldMap.get(dependentField);
        System.debug('theField --->' +theField);
        Schema.SObjectField ctrlField = objFieldMap.get(controllingField);

        List<Schema.PicklistEntry> contrEntries = ctrlField.getDescribe().getPicklistValues();
        System.debug('contrEntries ----->'+contrEntries);
        List<PicklistEntryWrapper> depEntries = wrapPicklistEntries(theField.getDescribe().getPicklistValues());
        System.debug('depEntries ----> '+depEntries);
        List<String> controllingValues = new List<String>();

        for (Schema.PicklistEntry ple : contrEntries) {
            String label = ple.getLabel();
            objResults.put(label, new List<String>());
            controllingValues.add(label);
        }
        System.debug('controllingValues --->'+controllingValues);

        for (PicklistEntryWrapper plew : depEntries) {
            String label = plew.label;
            String validForBits = base64ToBits(plew.validFor);
            for (Integer i = 0; i < validForBits.length(); i++) {
                String bit = validForBits.mid(i, 1);
                if (bit == '1') {
                    objResults.get(controllingValues.get(i)).add(label);
                }
            }
        }
        system.debug(objResults+'****objResults');
        return objResults;

    }


    public static String decimalToBinary(Integer val) {
        String bits = ''; 
        while (val > 0) {
            Integer remainder = Math.mod(val, 2);
            val = Integer.valueOf(Math.floor(val / 2));
            bits = String.valueOf(remainder) + bits;
        }
        return bits;
    }

    public static String base64ToBits(String validFor) {
        if (String.isEmpty(validFor)) return '';

        String validForBits = '';

        for (Integer i = 0; i < validFor.length(); i++) {
            String thisChar = validFor.mid(i, 1);
            Integer val = base64Chars.indexOf(thisChar);
            String bits = decimalToBinary(val).leftPad(6, '0');
            validForBits += bits;
        }

        return validForBits;
    }

    private static final String base64Chars = '' +
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
        'abcdefghijklmnopqrstuvwxyz' +
        '0123456789+/';


    private static List<PicklistEntryWrapper> wrapPicklistEntries(List<Schema.PicklistEntry> PLEs) {
        return (List<PicklistEntryWrapper>)
            JSON.deserialize(JSON.serialize(PLEs), List<PicklistEntryWrapper>.class);
    }

    public class PicklistEntryWrapper{
        public String active {get;set;}
        public String defaultValue {get;set;}
        public String label {get;set;}
        public String value {get;set;}
        public String validFor {get;set;}
        public PicklistEntryWrapper(){            
        }

    }


}



 
Hi, I have created a detail custom button of url type and passing Opportunity Date as shown below.

/apex/vfpage?oliId={!OpportunityLineItem.Id} && oppDate={!Opportunity.customDate__c}

And in apex constructor i am receiving the custom date value as below.

customDate = Date.valueOf(ApexPages.currentPage().getParameters().get('oppDate'));
But I am receiving error as
"Argument cannot be null. An unexpected error has occurred. Your development organization has been notified. "

How to pass the oppDate from url to constructor.
 
I am trying to display below lightning form in modal popup using overlay library. Please let me know how to do. 
I have overrided below form with Contact New button. Thanks.
    
    <aura:component implements="force:appHostable,lightning:actionOverride" access="global" >
    <aura:attribute name="recordId" type="String" /> <lightning:overlayLibrary aura:id="popuplib"/>
    <div class="slds-p-bottom_large slds-p-left_large" style="width:500px">
        <lightning:recordEditForm objectApiName="Contact" onsuccess="{!c.handleSuccess}">
            <lightning:messages />
            <lightning:inputField fieldName="FirstName" />
            <lightning:inputField fieldName="LastName" />
            <lightning:inputField fieldName="Birthdate" />
            <lightning:inputField fieldName="Phone" />
            <lightning:button aura:id="submit" type="submit" label="Save record" class="slds-m-top_medium" />
            </lightning:recordEditForm>
    </div>  
</aura:component>

Client side controller:

({
    handleSuccess : function(component, event, helper) {
        
        var contactRec = event.getParams().response;
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
           "recordId": contactRec.id,
           "slideDevName": "related"
       });
        
       navEvt.fire();
    }  
})
Hi All,

I need a trigger to update Contact Description and Contact related Case object Description whenever Account Description is updated.
Below trigger working fine for updating Contact Description when Account Description is updated. But I need to update Case records of Contact as well.

Here Account is ---> Parent,
Contact is ---> Child,
Case is ---> grand child

trigger ContactDescriptionUpdate on Account (after update) {
    Map < Id,  Account > mapAccount = new Map < Id, Account >();
    List<Contact> listContact = new List<Contact>();
    
    for(Account acct : trigger.new)
        mapAccount.put(acct.Id, acct);
    
    listContact = [ SELECT Description, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
    
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.Description = mapAccount.get(con.AccountId).Description;
        }
        update listContact;
    }
}

Thanks in advance.
Hi All,

Please let me know how to cover the Map in test class.

Map<Id,Id> mapIdString = new Map<Id,Id>();

for(sObject sObj: ObjList){
            Id sLastMod = (Id)sObj.get(Label.LastModifiedById);
            mapIdString.put(sObj.Id,sLastMod);
        }

Thanks.
Hi All.

Below class is used to create feeditem when application log is created/ updated.It's working fine when I am inserting/updating single record but it's creating only one record when multiple multiple records are created. Please let me know how to make this class to support multiple records. Thanks.

public class ApplicationLogTriggerHandler{
    public void LogHandlerMethod(List<Application_Log__c> appLogs){
        List<SObject> ObjList = new List<SObject>();
        String ObjType ='';
        String ObjID='';
        String Description = '';
        List<String> ObjTypeList = new List<String>();
        String LinkToRecord = '';
        List<Application_Log__c> LogList = new List<Application_Log__c>([Select ID, ObjectType__c, Name, Link_To_Record__c, 
                                                                         Record_Id__c, Description__c from 
                                                                         Application_Log__c where ID IN : appLogs ]);
        System.debug('LogList--->' +LogList);
        for(Application_Log__c app : LogList){
            if(app.Id!=null){
                ObjType = app.ObjectType__c;
                ObjID = app.Record_Id__c;
                Description = app.Description__c;
                LinkToRecord  = app.Link_To_Record__c;
                ObjTypeList.add(ObjType);
            }
        }
        system.debug('---->ObjTypeList'+ObjTypeList);
        System.debug('LogList--->' +LogList);
        String Query='Select Id, Name, LastModifiedById from '+ ObjType + ' WHERE ID =:ObjID';
        ObjList =database.query(Query); 
        System.debug('ObjList'+ ObjList);
        List<FeedItem> feedList = new List<FeedItem>();
            for(SObject record : ObjList){
            record.get('LastModifiedById');
            record.get('Name');
            System.debug((String) record.get('LastModifiedById'));
            FeedItem post = new FeedItem();
            post.ParentId = String.valueOf(record.get('LastModifiedById')); //eg. Opportunity id, custom object id..
            post.Body = 'An error has been logged for the opportunity: '+ record.get('Name') +  ' with the details: ' + Description + '\n' + 'Record ID: ' + LinkToRecord  ;
            feedList.add(post);
        }
        Database.insert(feedList, false);
        System.debug('feedList ------->' +feedList);
    }
}
Hi All. I have a custom object - name "Error_Log__c" and a custom text field - "Record_Id__c". Here Record_Id__c is the id of sobject Id (like opportunity, or account or contact or any object record id). When a Error_Log__c record is created then, a chatter post should be created and it should be posted to user "LastModifiedBy.Name" of sobject (account or contact or opportunity) record.

There is no relation between sobjects and Error_Log__c, but the custom text field - "Record_Id__c" is the id of sobject record id ( like account or contact or Opportunity record id, etc.).

Please let me know how to send the chatter post using dynamic soql for this. Thanks
I have written trigger to create a contact and assign it community user before user is created. But I am getting mixed DML issue due to the insertion setup&non setup objects in one transation.
Please show me how to move below logic in future method of helper class. We cant pass List<User> as parameter in future method. Plz let me know how to pass ids or strings in below logic.

Here is the trigger:
 
trigger CreateContact on User (before insert) {

   List<User> listUser = new List<User>();  
   for (User usr : trigger.new)   
   {  
     if (String.isBlank(usr.contactId))   
     {  
       listUser.add(usr);  
     }  
   }  
   if (listUser.size() > 0)   
   {  
    List<Contact> newContacts = new List<Contact>();  
    Map<String, User> userNameMap = new Map<String, User>();  
     //Create Contact For Each User  
     for (User usr : listUser)   
     {  
       String contactLastName = usr.lastname;  
       userNameMap.put(contactLastName,usr);  
       Contact con = new Contact(LastName = contactLastName);  
       newContacts.add(con);  
     }  
     Insert newContacts;  
     for (Contact con : newContacts)   
     {  
       //Put Contact Id's on Contacts  
       if (userNameMap.containsKey(con.LastName))   
       {  
         userNameMap.get(con.LastName).contactId = con.Id;  
       }  
     }  
   }   
 }

 
I have written a trigger to create a contact and assign it to Customer Community user as user.contactId whenever user is created from data loader. But I am getting mixed DML issue. I know that non setup and setup objects cannot be inserted. But please help how to convert below logic into future method in helper class. Thanks in advance.
 
trigger CreateContact on User (before insert) {

   List<User> listUser = new List<User>();  
   for (User usr : trigger.new)   
   {  
     if (String.isBlank(usr.contactId))   
     {  
       listUser.add(usr);  
     }  
   }  
   if (listUser.size() > 0)   
   {  
    List<Contact> newContacts = new List<Contact>();  
    Map<String, User> userNameMap = new Map<String, User>();  
     //Create Contact For Each User  
     for (User usr : listUser)   
     {  
       String contactLastName = usr.lastname;  
       userNameMap.put(contactLastName,usr);  
       Contact con = new Contact(LastName = contactLastName, Description = 'this is created by AutoCreateAccount trigger');  
       newContacts.add(con);  
     }  
     Insert newContacts;  
     for (Contact con : newContacts)   
     {  
       //Put Contact Id's on Contacts  
       if (userNameMap.containsKey(con.Name))   
       {  
         userNameMap.get(con.Name).contactId = con.Id;  
       }  
     }  
   }   
 }

Thanks.
Hi All. I have written a lightning component to search records based on input given.

Please let me know to how to search records based on picklist value selected like if new cases picklist value selected then cases with new status should be displayed, if closed cases picklistvalue selected then closed cases should be displayed. Please help. Thanks in advance.
 
Controller:

public class caseList1 {
	@AuraEnabled
    public static List<sObject> fetchData() {
        //Query and return list of Contacts
        List<SObject> objRecords = [SELECT Status, Subject from Case LIMIT 10];
        return objRecords;
    }
}
 
Lightning component:

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" 
                controller="caseList1">
    <!-- attributes -->
    <aura:attribute name="data" type="Map"/>
    <aura:attribute name="filteredData" type="Map"/>
    <aura:attribute name="columns" type="List"/>


    <!-- handlers-->
    <aura:handler name="init" value="{!this }" action="{!c.init }"/>

    	<span>
        	<lightning:input onchange="{!c.searchTable}" type="search" label="Searh" variant="label-hidden" placeholder="Enter search term" aura:id="SearchBox"/>
        </span>
    	<br/>
               
                <lightning:datatable
            columns="{!v.columns}"
            data="{!v.filteredData}"
            keyField="id"
        />
    
</aura:component>

js
({
    init: function (cmp, event, helper) {
        cmp.set('v.columns', [
            { label: 'Status', fieldName: 'Status', type: 'text' },
            { label: 'Subject', fieldName: 'Subject', type: 'text' }
        ]);
        var action = cmp.get("c.fetchData");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set("v.data", response.getReturnValue());
                cmp.set("v.filteredData", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    searchTable : function(cmp,event,helper) {
        var allRecords = cmp.get("v.data");
        var searchFilter = event.getSource().get("v.value").toUpperCase();
        
        var tempArray = [];
        var i;

        for(i=0; i < allRecords.length; i++){
            if((allRecords[i].Status && allRecords[i].Status.toUpperCase().indexOf(searchFilter) != -1) ||
               (allRecords[i].Subject && allRecords[i].Subject.toUpperCase().indexOf(searchFilter) != -1 ))
            {
                tempArray.push(allRecords[i]);
            }
        }
        cmp.set("v.filteredData",tempArray);
    }
})

controller
Hi All,
My requirement is update previous contact as non primary if new contact is primary..
Can you please help me what to write in below trigger. Thanks in advance.
 
Trigger updatePrimaryCheckbox2 on Contact(after insert, after update) {
   Map < Id, Contact > accConMap = new Map < Id, Contact > ();
   List < Contact > conList = new List < Contact > ();
   if (Trigger.isInsert || Trigger.isUpdate) {
    for (Contact cont: Trigger.New) {
     if (cont.AccountId != null && cont.IsPrimaryContact__c == true) {
      accConMap.put(cont.AccountId, cont);
     }
    }
   }
   for (Contact con: [select id, AccountId, IsPrimaryContact__c, Description from contact
     where accountid IN: accConMap.keyset()
    ]) {
    if (con != null && accConMap.containsKey(con.AccountId)) {
    // here logic
    // logic
     conList.add(con);
    }
   }
   update conList;
  }

 
Hi. Can you please keep below trigger into helper class.
 
trigger InvoiceSum on Invoice_Items__c (after insert, after delete, after undelete, after update) {
    set<Id> invIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Invoice_Items__c invItem: Trigger.new){
			if(Trigger.isInsert || Trigger.isUndelete || (invItem.Amount__c != Trigger.oldMap.get(invItem.Id).Amount__c || invItem.InvoiceFK__c != Trigger.oldMap.get(invItem.Id).InvoiceFK__c))
				invIdSet.add(invItem.InvoiceFK__c);            
        }
    }    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Invoice_Items__c invItem: Trigger.old){
            if(Trigger.isDelete || (invItem.Amount__c != Trigger.newMap.get(invItem.Id).Amount__c || invItem.InvoiceFK__c != Trigger.newMap.get(invItem.Id).InvoiceFK__c))
				invIdSet.add(invItem.InvoiceFK__c);
        }
    }       
    List<Invoice__c> invList = [select id, Ammount__c, (Select Id, Amount__c from Invoice_Items__r) from Invoice__c Where ID IN: invIdSet];    
    for(Invoice__c inv : invList){
        
        inv.Ammount__c = 0;
        for(Invoice_Items__c invItem : inv.Invoice_Items__r) {
			inv.Ammount__c += invItem.Amount__c;
        }
    }
    update invList;
}

​​​​​​​
Hi All, Can you please help me to convert below logic into helper class. I am getting exception as attempt to deference null object.  Thanks.
 
trigger contactAmountSum on Contact (after insert, after delete, after undelete, after update) {
    set<Id> accIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Contact conObj: Trigger.new){
			if(Trigger.isInsert || Trigger.isUndelete || (conObj.Amounts__c != Trigger.oldMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.oldMap.get(conObj.Id).AccountId))
				accIdSet.add(conObj.AccountId);            
        }
    }    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Contact conObj: Trigger.old){
            if(Trigger.isDelete || (conObj.Amounts__c != Trigger.newMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.newMap.get(conObj.Id).AccountId))
				accIdSet.add(conObj.AccountId);
        }
    }       
    List<Account> accList = [select id, Amounts__c, (Select Id, Amounts__c from contacts) from Account Where ID IN: accIdSet];    
    for(Account acc : accList){
        
        acc.Amounts__c = 0;
        for(Contact conObj : acc.contacts) {
			acc.Amounts__c += conObj.Amounts__c;
        }
    }
    update accList;
}

Below is the helper class:
 
public class contactAmountSumHelperClass
{
    public static void updateContactCountonAccount(Map<Id, Contact> newContactMap, Map<Id, Contact> oldContactMap)
    {
        Set<Id> accIdSet = new set<Id>();
                
        for(Contact con: newContactMap.values())
        {
            if(con.AccountId != null){
                if(con.Amounts__c != oldContactMap.get(con.Id).Amounts__c ||
                    con.AccountId != oldContactMap.get(con.Id).AccountId){
                    accIdSet.add(con.AccountId);
                }
            }
        }
        
        List<Account> accList = [select id, Amounts__c,Description, (Select Id, Amounts__c from contacts ) from Account 
                                 Where ID IN: accIdSet ];    
        for(Account acc : accList)
        {        
            acc.Amounts__c = 0;
            for(Contact conObj : acc.contacts)
            {  
                acc.Amounts__c += conObj.Amounts__c; 
            }
        }
        update accList; 
    }
}

 
Hi All,

I am using below trigger to update child records. Can someone please convert logic into helper class and call it from trigger. Thanks in advance.
 
trigger ContactUpdate on Account (after update) {
    Map < Id,  Account > mapAccount = new Map < Id, Account >();
    List<Contact> listContact = new List<Contact>();
   
    for(Account acct : trigger.new)
        mapAccount.put(acct.Id, acct);
   
    listContact = [ SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
   
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
        }
        update listContact;
    }
}


 
Hi All,

I need a trigger to update Contact Description and Contact related Case object Description whenever Account Description is updated.
Below trigger working fine for updating Contact Description when Account Description is updated. But I need to update Case records of Contact as well.

Here Account is ---> Parent,
Contact is ---> Child,
Case is ---> grand child

trigger ContactDescriptionUpdate on Account (after update) {
    Map < Id,  Account > mapAccount = new Map < Id, Account >();
    List<Contact> listContact = new List<Contact>();
    
    for(Account acct : trigger.new)
        mapAccount.put(acct.Id, acct);
    
    listContact = [ SELECT Description, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
    
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.Description = mapAccount.get(con.AccountId).Description;
        }
        update listContact;
    }
}

Thanks in advance.
Hi All.

Below class is used to create feeditem when application log is created/ updated.It's working fine when I am inserting/updating single record but it's creating only one record when multiple multiple records are created. Please let me know how to make this class to support multiple records. Thanks.

public class ApplicationLogTriggerHandler{
    public void LogHandlerMethod(List<Application_Log__c> appLogs){
        List<SObject> ObjList = new List<SObject>();
        String ObjType ='';
        String ObjID='';
        String Description = '';
        List<String> ObjTypeList = new List<String>();
        String LinkToRecord = '';
        List<Application_Log__c> LogList = new List<Application_Log__c>([Select ID, ObjectType__c, Name, Link_To_Record__c, 
                                                                         Record_Id__c, Description__c from 
                                                                         Application_Log__c where ID IN : appLogs ]);
        System.debug('LogList--->' +LogList);
        for(Application_Log__c app : LogList){
            if(app.Id!=null){
                ObjType = app.ObjectType__c;
                ObjID = app.Record_Id__c;
                Description = app.Description__c;
                LinkToRecord  = app.Link_To_Record__c;
                ObjTypeList.add(ObjType);
            }
        }
        system.debug('---->ObjTypeList'+ObjTypeList);
        System.debug('LogList--->' +LogList);
        String Query='Select Id, Name, LastModifiedById from '+ ObjType + ' WHERE ID =:ObjID';
        ObjList =database.query(Query); 
        System.debug('ObjList'+ ObjList);
        List<FeedItem> feedList = new List<FeedItem>();
            for(SObject record : ObjList){
            record.get('LastModifiedById');
            record.get('Name');
            System.debug((String) record.get('LastModifiedById'));
            FeedItem post = new FeedItem();
            post.ParentId = String.valueOf(record.get('LastModifiedById')); //eg. Opportunity id, custom object id..
            post.Body = 'An error has been logged for the opportunity: '+ record.get('Name') +  ' with the details: ' + Description + '\n' + 'Record ID: ' + LinkToRecord  ;
            feedList.add(post);
        }
        Database.insert(feedList, false);
        System.debug('feedList ------->' +feedList);
    }
}
Hi All. I have a custom object - name "Error_Log__c" and a custom text field - "Record_Id__c". Here Record_Id__c is the id of sobject Id (like opportunity, or account or contact or any object record id). When a Error_Log__c record is created then, a chatter post should be created and it should be posted to user "LastModifiedBy.Name" of sobject (account or contact or opportunity) record.

There is no relation between sobjects and Error_Log__c, but the custom text field - "Record_Id__c" is the id of sobject record id ( like account or contact or Opportunity record id, etc.).

Please let me know how to send the chatter post using dynamic soql for this. Thanks
Hi All,

I have created batch apex class to create multiple customers if account has no customers. Below is the code which creates one customer after running batch apex. 
But my requirement is to create 7 customers from Date given in Account record. 
Example: If Date__c in Account is 25-10-2017, then 7 customers. 1st customer should be created with Date__c = 25-10-2017, 2nd customer should be created with Date__c = 26-10-2017 till 7 days.


Below batch class creates a single customer for Account which has no customer:

global class batchContactCreate implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
       return Database.getQueryLocator([
                select Name, Date__c from Account where ID NOT IN (SELECT Account__c from S1_Customer__c)]);  
    }
    
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         List<S1_Customer__c> cList = new List<S1_Customer__c>();
         for(Account a : scope)
         {
            S1_Customer__c cust = new S1_Customer__c(Name =a.Name, Account__c = a.Id, Phone__c = '1212121232');
            cList.add(cust); 
                   
         }
         insert cList;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}

Thanks in advance
Hi, Please let me know how to cover EmailMessaging class in below code:

Class:
global class UpdateLastWorkedDate_onContactBatch implements Database.Batchable<sObject>, Schedulable {
     public EmailTemplate et{get;set;}
      
    global DataBase.QueryLocator start(Database.BatchableContext bc){
                       system.debug('>>>>');

        return DataBase.getQueryLocator([select id,owner.email,TR1__Candidate_Status__c,Last_Day_Worked__c,TRSCHED__Compliance_Owner__r.email from contact where Last_Day_Worked__c!=null]);
        }
    global void execute(Database.BatchableContext BC, List<contact> scope)
       {
                      system.debug('>>>>');

       list<contact> conlist=new list<contact>();
       et=[select id,Name FROM EmailTemplate where Name='3monthsgap' Limit 1];
       list<string> to=new list<string>();
       List<Messaging.SingleEmailMessage> mailsList = new List<Messaging.SingleEmailMessage>();

       for(contact c:scope){
               system.debug('>>>>');

        integer i;
        //i=system.today().monthsBetween(c.Last_Day_Worked__c);
        i=c.Last_Day_Worked__c.monthsBetween(system.today());

        system.debug('>>>>'+i);
        if(i==3){
        c.TR1__Candidate_Status__c='InActive';
        conlist.add(c);
        }
        if(i==2)
        {
                       system.debug('>>>>');

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               to.add(c.owner.email);
                 to.add(c.TRSCHED__Compliance_Owner__r.email);

                 mail.setTargetObjectId(c.id);
                 mail.setSaveAsActivity(false);
                 mail.setTreatTargetObjectAsRecipient(false);
                 mail.setTemplateId(et.id);
                 //mail.setWhatId(AQ.id);
                 mail.setToAddresses(to);
          mailsList.add(mail);
        
        }
       }
      if(conlist.Size()>0){

       update conlist;
       }
        if(mailsList.Size()>0){
                       system.debug('>>>>');

            Messaging.sendEmail(mailsList);
            }  
       
       }   
    
    global void finish(Database.BatchableContext BC){
        }
       global void execute(SchedulableContext sc) {
        UpdateLastWorkedDate_onContactBatch b1 = new UpdateLastWorkedDate_onContactBatch();
        ID batchprocessid = Database.executeBatch(b1,200);    
    }
    
}

Test class: 59% coverage

@isTest
public class Test_UpdateLastWorkedDate_onContactBatch {
public static testMethod void test() 
     {
   /*   Profile p = [SELECT Id FROM Profile WHERE Name='system administrator'];
         
    User us = new User(Alias='Admin',Email='test@gamil.com',LastName='Testing',Username='standardus@testorg.com',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id, 
           TimeZoneSidKey='America/Los_Angeles',EmailEncodingKey='UTF-8');
    insert us;*/
   User us = [Select id from User where Id = :UserInfo.getUserId()];
         
    Account acc = new Account(Name = 'test13');
    insert acc;
    
    Contact con = new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-90), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id);
    insert con;
         
 //     EmailTemplate eT = new EmailTemplate (developerName = 'X3monthsgap', subject='test', FolderId = UserInfo.getUserId(), TemplateType= 'Text', Name = '3monthsgap'); 
     //    insert eT;
   System.runAs(us)
   {
   Test.startTest();
     UpdateLastWorkedDate_onContactBatch obj = new UpdateLastWorkedDate_onContactBatch();
     DataBase.executeBatch(obj); 
         
   Test.stopTest();
   }  
    }
    
}

Below code not covered:

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               to.add(c.owner.email);
                 to.add(c.TRSCHED__Compliance_Owner__r.email);

                 mail.setTargetObjectId(c.id);
                 mail.setSaveAsActivity(false);
                 mail.setTreatTargetObjectAsRecipient(false);
                 mail.setTemplateId(et.id);
                 //mail.setWhatId(AQ.id);
                 mail.setToAddresses(to);
          mailsList.add(mail);
       
 global void execute(SchedulableContext sc) {
        UpdateLastWorkedDate_onContactBatch b1 = new UpdateLastWorkedDate_onContactBatch();
        ID batchprocessid = Database.executeBatch(b1,200);    
    
Thanks
Hi All,

I am trying to display vf pages based on record type selected from standard salesforce page. I have two record types API Names are - RecordType1, RecordType2. Customer__c is object api name. After selecting record type and clicking on next button, i am getting below error.


Visualforce Error
Help for this Page
System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!redirectToNewVFPage}' in component <apex:page> in page recordtypepage: Class.NewCustomerExtension.redirectToNewVFPage: line 13, column 1
Class.NewCustomerExtension.redirectToNewVFPage: line 13, column 1

Below is the code.

public with sharing class NewCustomerExtension {

    public String recordTypeId;

    public NewCustomerExtension (ApexPages.StandardController std) {

    }

    public Pagereference redirectToNewVFPage(){
        Pagereference pg = null;
        if(ApexPages.CurrentPage().getParameters().get('RecordType') != null){
            recordTypeId = ApexPages.CurrentPage().getParameters().get('RecordType');
            if(recordTypeId == Schema.SObjectType.Customer__c.getRecordTypeInfosByName().get('RecordType1').getRecordTypeId()){
               // pg = new Pagereference('/apex/Page1');
               pg = Page.Page1;   
            }else if(recordTypeId == Schema.SObjectType.Customer__c.getRecordTypeInfosByName().get('RecordType2').getRecordTypeId()){
               // pg = new Pagereference('/apex/Page2'); // Add Parameters to Page if Needed
               pg= Page.Page2;
            }
            pg.setRedirect(true);
            return pg;
        }
        return null;
    }
}

Page Name: RecordTypePage
<apex:page standardController="Customer__c" extensions="NewCustomerExtension" action="{!redirectToNewVFPage}">
</apex:page>

PageName: Page1:
<apex:page standardController="Customer__c" >
   Page 1
</apex:page>

PageName: page2
<apex:page standardController="Customer__c" >
  <h1>Congratulations</h1>
  This is your new Page
</apex:page>

I have overrided New button with page: RecordTypePage.

Plz let me know how to redirect to their respective pages. Thanks in advance.

 
Hi All,
I have created custom meta data account_mdt with picklist field "Category", with two picklist values. they are "Avaialbale" and "NotAvailable". I want to use these picklist values in below if condition. plz provide the syntax

if(Account.Type==(here i want to use account_mdt.category.Available value') 
{
}
Here, standard object "Account" type is equal to value of custom meta data account_mdt with picklist field "Category" - value=Avaialbale.
Hi, I am updating parent accountnumber in child object contact. But i want to update the field contact - accountnumber field only when accountnumber in contact is null. if we provide any new value in accountnumber of contact field, then new value should be updated not parent account-accountnumber.
Below is class which will update accountnumber of Account in contact even we are providing other value in Contact object.
I mean if we are providing any value in contact-accountnumber field, then new should be updated, it should not override with parent account-accountnumber. Please help.


public class accountnamepopualtion
{
public static void popualteacc(List<Contact> coonlist)
{
set<Id> accountids= new set<Id>();
Map<id,string> accmap= new Map<id,string>();
for(contact con:coonlist)
{
 
accountids.add(con.accountid);
}
for(Account acc:[select id,accountnumber from account where id in:accountids])
{
accmap.put(acc.id,acc.accountnumber );
 
}
for(contact con:coonlist)
{
if(accmap.containskey(con.accountid) && con.Account_Number__c==null)
{
con.Account_Number__c=accmap.get(con.accountid);
}
}
}
}


trigger contactTrigger on contact(before insert, before update, after insert, after update )
{
 if (Trigger.isBefore)
      {
            if (Trigger.isInsert  )
            {
              accountnamepopualtion.setAccountName(trigger.new);
             }

}
}

Thanks in advance