+ Start a Discussion
Best Answer chosen by myseo article
myseo articlemyseo article
Successful Women in Business Need a Personal Brand (http://myseoarticle.com/successful-women-in-business-need-a-personal-brand/)

When you’re building a following, whether for a business or as an individual, you need to look the part. But personal branding is so much more than this. As a female, typically breaking through can be harder than for their male counterparts, so you need to do whatever it takes to get an edge.
 
Here are some ideas on how a woman can improve their personal brand.
 
Have An Elevator Pitch Ready
 
Having a one minute spiel that tells people what you do and why you do it is crucial for business success. But having a generic boring pitch that doesn’t raise eyebrows won’t get the desired traction. Frame your pitch in a way that is unique, powerful and shows what you are doing to make a difference for the recipient. How are you helping to eliminate their pain points?
 
Take Ownership of Your Success
 
For people to take you to celebrate your success, you need to celebrate it yourself. It’s easy to get caught up in the “head to the grindstone” mentality and simply work hard with no accolades. But taking time to celebrate your success is an important part of moving forward. Your achievements should be commended, and when you commend them, so will others.
 
Discuss What You’re Passionate About
 
Personal branding isn’t just talking about your specific work, but it should also involve your hobbies and passions. They are part of who you are and just as important when it comes to your brand. Celebrate your passions too and don’t be afraid to talk about them.
 
Style Your Wardrobe Accordingly
 
Portraying the right image is key to success but first, you need to define what that is. The best way is by reverse engineering the process. Decide who your target audience is, and what resonates with them, and then plan your style accordingly. A personal branding expert with specialties in fashion styling can assist greatly with this.
 
The work you put in comes out the other end tenfold, so it’s important to invest in your brand.

http://myseoarticle.com/successful-women-in-business-need-a-personal-brand/
 
Rahul Tandekar 1Rahul Tandekar 1 
here i have created two lightning component 
1. OpportunityOnAccount.cmp which shows all opportunity on the accout record page with add Opportunity button
2. OpportunityOfAccount.cmp which shows all opportunity of current account on account record page this component also have Component event handler which is get fired from OpportunityOnAccount.cmp controller
<--! OpportunityComponentContainer.cmp-->
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	
        <c:OpportunityOnAccount recordId="{!v.recordId}"/>    
    <c:OpportunityOfAccount recordId="{!v.recordId}"/>

</aura:component>
this is my main component which is calling both my component
 
<!--OpportunityOnAccount.cmp-->
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global"  controller = 'OpportunityOfContactHandler'>
    <!-- attributes -->
    <aura:attribute name = "allOpportunity" type = "List"/>
    <aura:attribute name="recordId" type="string" />
    <!--Event regster-->
    <aura:registerEvent name = "registerOppOfAcc"  type = "c:OpportunityOfAccountEvt"></aura:registerEvent>
<!-- handlers-->
    <aura:handler name="init" value="{! this }" action="{! c.doInit }"/>
    <aura:handler event="c:searchOppoertunity" action="{!c.handleOpportunitySearchEvent}"  />
<!-- <aura:handler name = "removerIndexOfOpportunity" event = "c:OppIndexRemover" action = "{!c.handleOpportunityRemove}" />
 				-->
        <lightning:card title="All Opportunities on Account" iconName="standard:opportunity" footer="All Opportunity End">
     <div class="slds-box">
        <table>
    	 <thead>
               <tr class="slds-text-heading--label"> 
                   <div class="slds-p-left_small">
                       <th scope="col"><div class="slds-truncate" title="Name">Opportunity Name</div></th>
                   </div>
             </tr>
         </thead>
         <tbody>
            <aura:iteration items="{!v.allOpportunity}" var ="x">
                <tr>
                    <td>
                        <div class="slds-p-top_x-small">
                            <div class="slds-p-left_medium">
                                <div class="slds-truncate" title="">{!x.Name}</div>
                            </div>
                        </div>
                    </td>
                    <td>      
                        <div class="slds-p-top_x-small">
                            <div class="slds-p-left_medium">
                                <div class="slds-truncate" title="">
                                    <lightning:button variant="brand"  label="Add Opportunity" name="Add"  value="{!x}" onclick="{! c.handleRowAction }"/>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
             </aura:iteration>
         </tbody>
    </table>
        </div>
    </lightning:card>    
</aura:component>
<!--OpportunityOnAccountController.js-->

({
    doInit: function (component, event, helper) {
     //   var ContactRecordId = component.get("v.recordId");
        helper.fetchData(component);
    },

    handleRowAction: function (cmp, event, helper) {
        var action =  event.getSource().get('v.name');
        var row = event.getSource().get('v.value');

          //alert('Adding Opportunity: ' + JSON.stringify(row));
  			console.log('Adding Row Detail->'+JSON.stringify(row));
                helper.addRecord(cmp,row);
    },
    handleOpportunitySearchEvent: function(cmp, event) { 
    console.log("Searching Opportunities in handler....!");
    var x = event.getParam("searchOpp"); 
        //Set the handler attributes based on event data 
        cmp.set("v.allOpportunity", x);     
    } ,
    handleOpportunityRemove : function (cmp, event, helper) {
        var rows = cmp.get('v.data');
        var indexObj = event.getParam('opportunityObj');
        console.log('Index obj handleOpportunityRemove '+indexObj.Name);
        var rowIndex = rows.indexOf(indexObj);
        rows.splice(rowIndex, 1);
        cmp.set('v.data', rows);
    },
});
<!--OpportunityOnAccountHelper.js-->
({ 
    fetchData: function (component) {
       var action = component.get("c.getAllOpportunityOnAccount");
             // Load all contact data
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                component.set('v.allOpportunity', result);
            }
            else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
            }
                else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    addRecord: function(component,row){
                console.log("Add Event fire succsess...! "+row);
        var opportunityOnContacEvt = component.getEvent("registerOppOfAcc");
        opportunityOnContacEvt.setParams({
            opp : row
        });
        opportunityOnContacEvt.fire();
    },
})
<!--OpportunityOfAccount.cmp-->
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" controller = 'OpportunityOfContactHandler'>
  <!--  -->
    <!-- attributes -->
    	<!--List of all the opprtunity-->
     <aura:attribute name="opportunities" type="list"/>
    <aura:attribute name="recordId" type="string" />

    <aura:handler name = "registerOppOfAcc" event = "c:OpportunityOfAccountEvt" action = "{!c.handleOppOfAccEvent}" />

    <aura:registerEvent name = "removerIndexOfOpportunity"  type = "c:OppIndexRemover"></aura:registerEvent>

    <!-- handlers-->
    <aura:handler name="init" value="{! this }" action="{! c.Init }"/>
       {!v.recordId}
    <lightning:card variant="Narrow" title="Account Opportunities" iconName="standard:Opportunity" footer="Opportunity of Current Accountr">
     <div class="slds-box">
		<table>
    	 <thead>
               <tr class="slds-text-heading--label">
                   <div class="slds-p-left_small">
                       <th scope="col"><div class="slds-truncate" title="Name">Opportunity Name</div></th>
                   </div>
             </tr>
         </thead>
         <tbody>
            <aura:iteration items="{!v.opportunities}" var ="x">
                <tr>
                    <td>                   
                        <div class="slds-p-left_medium">
                            <div class="slds-p-top_x-small">
                                <div class="slds-truncate" title="">{!x.Name}</div>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="slds-p-top_x-small">
                            <div class="slds-truncate" title="">
                                <lightning:button variant="brand"  label="Remove Opportunity" name="delete"  value="{!x}" onclick="{! c.handleRowAction }" />
                            </div>
                        </div>
                    </td>
                </tr>
                <tr><td>  <p></p></td></tr>
  
             </aura:iteration>
         </tbody>
    </table>
        </div>
    </lightning:card>
</aura:component>
<!--OpportunityOfAccountController.js-->
({
    Init: function (component, event, helper) {
       
        var AccountRecordId = component.get("v.recordId");
        console.log('ID RECORD->'+AccountRecordId);
    //     component.set('v.opportunities', component.get("v.opportunities").splice(0,component.get("v.opportunities").length));
        helper.fetchData(component, AccountRecordId);
    },

    handleRowAction: function (cmp, event, helper) {
		console.log("On row Action...!");
        var action =  event.getSource().get('v.name');
        var row =  event.getSource().get('v.value');
        console.log('Date : '+JSON.stringify(row)+' Action : '+action);
                helper.removeOpportunity(cmp, row);
         },
    handleOppOfAccEvent: function(Component,event,helper)    {
        console.log('Here Handeling Event...!');
        var AccountRecordId = Component.get("v.recordId");
         var Opp = event.getParam('opp');
         helper.updateOpportunity(Component,Opp,AccountRecordId);
        console.log('My Data -> '+Opp.Name+' RecordId -> '+ AccountRecordId);
        
      /*   var removeOpportunity = Component.getEvent("removerIndexOfOpportunity");
        removeOpportunity.setParams({
            opportunityObj : Opp
        });
        removeOpportunity.fire();
        */

    }
});
<!--OpportunityOFAccountHelper.js-->
({
    removeOpportunity: function (cmp, row) {
        var rows = cmp.get('v.opportunities');
        var rowIndex = rows.indexOf(row);
        rows.splice(rowIndex, 1);
        cmp.set('v.opportunities', rows);
    },
        fetchData: function (component, AccountRecordId) {
       var action = component.get("c.getOpportunityOfAccount");
             // Load all contact data
             console.log('Record Id '+AccountRecordId);
        action.setParams({"acccountId" : AccountRecordId});
            
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                //Set event attribute value
             	  var result = response.getReturnValue();
                console.log("Return Result... "+response.getReturnValue());
                  component.set('v.opportunities',result );
            }
            else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
            }
                else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
     updateOpportunity: function (Component,Opp,AccountRecordId) {
         console.log('Updating Opportunity....! '+Opp.Id+' '+AccountRecordId+' Stringfy ->'+JSON.stringify(AccountRecordId));
       var action = Component.get("c.updateOpportunity");
       action.setParams( 
           {accouhtId : AccountRecordId,
            oppObj : Opp.Id}
       );
           
       action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
				  var oldOpp=Component.get("v.opportunities");
    		oldOpp.push(response.getReturnValue());
        	Component.set("v.opportunities", oldOpp);
                console.log('update Succsess....!'+response.getState());
             	console.log('Updated Object-> '+JSON.stringify(response.getReturnValue()));
             
              
            }
            else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
            }
                else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    
})
<!--EVENT-->
<aura:event type="COMPONENT">
    <aura:attribute name = 'opp' type = 'Object'/>    
</aura:event>

After adding into Account page

User-added imageEvent is firing but it is not handeling in another component 
so plase help me with that 
what is the problem with that 
is it because of my container component ?

and when i use two seperate component why it doesn't work with component event 



 
Best Answer chosen by Rahul Tandekar 1
shailesh_rawteshailesh_rawte
Hi Rahul,

A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event.

In your case, both components are same level, and componenet event does not available for within an application,

Instead of component event use Application event.

Regards,
Shailesh Rawte
 
azhar khasimazhar khasim 
Hello Everyone,

I had an issue with Commandbutton which I need to redirect the page from the Visualforce page to some other company Website Contact Us page.

Here is my CommandButton code and Controller class code.

VF Page CommandButton:

 <apex:commandButton style="color:white; background-color:red; background-image:none; width:150px; height:35px" action="{!Cancel}" value="Cancel"  />

Controller Class:

 public PageReference Cancel(){
        PageReference pr = new PageReference('/www.bren.com/residential/contact');
        pr.setRedirect(true);
        return pr;
    }


Please help me with this issue.

Thanks and Regards,
Azar Khasim.
Best Answer chosen by azhar khasim
Maharajan CMaharajan C
Hi Azar,

Try the below change in method it will work:

Public pagereference Cancel()
{
        PageReference pr = new PageReference('https://www.bren.com/residential/contact');
        pr.setRedirect(true);
        return pr;
}


Thanks,
Maharajan.C
Jan Kopejtko 2Jan Kopejtko 2 
Hey, I have object A.

A has lookup to Account. All records on A have the same owner.

I need to change the owner of A records to the owner of the Account in lookup.

Example: John owns 10 records of object A. All of those records have lookup to an Account called McDonalds. Owner of the McDonalds record is user McDonald. I need to change ownership of John's records to the user in related Account (that might not only be McDonald, but others...).

I'm experiencing difficulties with my code:

List <TestObj__c> list1 = New List<TestObj__c>();
list1 = [SELECT id, NAME From TestObj__c WHERE (OwnerId = '0052o000009Stq8')];
for(TestObj__c a :list1) {
   
    /**
   /* variable a;
   /* variable a = [Select AccountOwner from Account where (TestObj__c.lookupToAccount equals AccountId];
    /* a.Owner = a;
    /*
                                                          
}

The for look works, but I don't know what to put inside, because it gives me errors, so I just deleted it and put something vague inside and commented it. How do I do this?
Best Answer chosen by Jan Kopejtko 2
Anthony McDougaldAnthony McDougald
Good Evening Jan,
Hope that your day is off to an amazing start. The code below will query all object A records where the related Account record's owner is not the same (this is under the assumption that the record owner API name of object A is OwnerId). It will then loop through the results, change the record owner of object A to the record owner of the related Account record. It will add each record to another list and update all the records at once with DML so you follow best practices and don't hit any governor limits. Please test and report back when you get the chance. Hope this helps and may God bless you abundantly.
List <TestObj__c> list1 = [SELECT Id, Name, Account__r.OwnerId, OwnerId From TestObj__c WHERE OwnerId != Account__r.OwnerId];
List <TestObj__c> list2 = New List<TestObj__c>();
 for(TestObj__c a :list1){
	a.OwnerId = a.Account__r.OwnerId;
	list2.add(a);
}
update list2;

Best Regards,
Anthony McDougald​​​​​​​ 
Ajay S SolankiAjay S Solanki 
Hi All,

We are trying to upload file greater than 4 MB using lightning component. We don't want to go through lightning:fileUpload due to certain requirement needs.

Any help will be appreciated. Thanks
Best Answer chosen by Ajay S Solanki
Ajay S SolankiAjay S Solanki
We have identified the solution for this. We have achieved this using making callouts from XMLHttpRequest using ligthning component.
balaji karthikbalaji karthik 
Hi Everyone,

If Anyone have idea please help me on this issue.

Here my Scenairo was we have one task page when user are creating for the sales team.How can i create a follow up time for task object and with a link of follow up date with apex controller class also.i need to get the reminder popup window notification alert before 15 mintues of due time for that user to completed the task.
In this way i dont want to use workflow r task reminders is there any different way to achieve this.if anyone have idea please help me on this issue.

thanks inadvance,
p.balu
Best Answer chosen by balaji karthik
Danish HodaDanish Hoda
Hi Balaji,
You will find this in developer console under task.obj
User-added image
DeepikareddyDeepikareddy 
public class test5 {

  public list<string> lststatename{get;set;}
  public list<string> lstrating{get;set;}
  
  public list<string> lstactive{get;set;}
  public map<string, string> statemap{get;set;}

public map<string, string> activestatusmap{get;set;}

 public set<string> mapkey{get;set;}
 
    public list<string> mapvalue{get;set;}
 public test5(){
 
 
    string  jsonexample1 =  ' { "overalldata": [ {"stateName": "Andrapradesh",  "rating": "5.0" , "active": "yes" }, { "stateName": "Telangana",  "rating": "4.0" ,"active": "no" }, {"stateName": "Banglore",  "rating": "5.0" ,"active": "no"} , {"stateName": "Maharastra",  "rating": "4.5" ,"active": "no" }  ] } ';

   
     map<string,object>  metadatamap= (map<string,object>)json.deserializeuntyped(jsonexample1); 
     
      list<object>  values1= (list<object>)metadatamap.get('overalldata');
        
        
         lststatename= new list<string>();
         lstrating= new list<string>();
         statemap= new map<String, string>();
         
          for(object parsed : values1){
          map<string,object>  values = (map<string,object>)parsed;
          string statename = string.valueof(values.get('stateName'));
          
          string rating= string.valueof(values.get('rating'));
          
          lststatename.add(statename);
             
          lstrating.add(rating);
             
             statemap.put(statename,rating);
             
             }
            
 }
}
Visual force page:
 
<apex:page controller="test5" >

 <apex:form >
   <apex:repeat value="{!statemap}" var="a">
    <apex:selectList >   
               <apex:selectOptions value="{!a}">{!a}</apex:selectOptions>
         </apex:selectList>
   
   </apex:repeat>
            
                                          
      
 
 </apex:form>
 
</apex:page>

Hi..! can any body bind data to the selectlist with statename as itemlabel and rating  as the itemvalue in visualforce page
.. Thank you..!
Best Answer chosen by Deepikareddy
Soyab HussainSoyab Hussain
Hi Deepika,

Use this code this will help you.

Apex Class:
public class test5 {     
    public list<string> lststatename{get;set;}
    public list<string> lstrating{get;set;} 
    public list<string> lstactive{get;set;}
    public map<string, string> statemap{get;set;}   
    public map<string, string> statemapCopy{get;set;}   
    public map<string, string> activestatusmap{get;set;}     
    public set<string> mapkey{get;set;} 
    public list<string> mapvalue{get;set;}
    public string selectedOption{get;set;} 
    public string displymessage{get;set;}
    public test5(){ 
        string  jsonexample1 =  ' { "overalldata": [ {"stateName": "Andrapradesh",  "rating": "5.0" , "active": "yes" }, { "stateName": "Telangana",  "rating": "4.0" ,"active": "no" }, {"stateName": "Banglore",  "rating": "5.0" ,"active": "no"} , {"stateName": "Maharastra",  "rating": "4.5" ,"active": "no" }  ] } ';
        map<string,object>  metadatamap= (map<string,object>)json.deserializeuntyped(jsonexample1); 
        list<object>  values1= (list<object>)metadatamap.get('overalldata'); 
        lststatename= new list<string>();
        lstrating= new list<string>();
        statemap= new map<String, string>();
        statemapCopy = new map<String, string>();
        for(object parsed : values1){ 
            map<string,object>  values = (map<string,object>)parsed;
            string statename = string.valueof(values.get('stateName')); 
            string rating= string.valueof(values.get('rating')); 
            lststatename.add(statename); 
            lstrating.add(rating); 
            statemap.put(statename ,   rating); 
            statemapCopy.put(rating, statename);
        }
        
    }
    
    public void showmessage(){  
        displymessage = 'you have selected :'+statemapCopy.get(selectedOption)+' the value of the selected name is '+selectedOption;
    }
}

VisualForce Page:
 
<apex:page controller="test5" > 
    <apex:form > 
        <apex:selectList size="1" value="{!selectedOption}"  >   
            <apex:selectOptions value="{!statemap}"></apex:selectOptions>
            
            <apex:actionSupport event="onchange" action="{!showmessage}" reRender="s"/>
        </apex:selectList>  
        
        <apex:outputLabel id="s" value="{!displymessage}"></apex:outputLabel>
    </apex:form> 
</apex:page>

Regards,
Soyab
 
kavya T 5kavya T 5 
Hi All,
   I am new to Salesforce and i tried test class for below trigger but i got code coverage only 35%.

whenever An Account is created with number_of_Employees__c(custom field)>99 create 10 opportunities for Account.

trigger CreateTenOpportunity on Account (after insert)
{
    List<Opportunity> oppList=new List<Opportunity>();
    for(Account acc:trigger.new)
    {
        if(acc.Number_of_Employees__c>99)
        {
            for(integer i=0;i<10;i++)
            {
              opportunity opp=new opportunity();
              opp.Name=acc.Name+ i;
              opp.AccountId=acc.Id;
              opp.StageName='Prospecting';
              opp.CloseDate=Date.today()+15;
              oppList.add(opp);  
            }
        }
    }
    if(oppList.size()!=0){
        insert oppList;
    }
}

 
Best Answer chosen by kavya T 5
Maharajan CMaharajan C
Hi Kavya,

In the Trigger you are using the custom Number_of_Employees__c Field but in the Test Class you reffered wrongly the Standard NumberOfEmployees Field from Account Object instead of cutome field to insert the Account  .  Change the test class like below it will work.

@isTest
private class CreateTenOpportunityTest {
    @isTest
    static void createOpportunityAfterAccount(){
        account acc=new account();
        acc.name='Test';
        acc.Number_of_Employees__c=100;           
        insert acc;
        
        List<Opportunity> opplist=[select name,AccountId from opportunity where AccountId=:acc.Id];
        system.assertEquals(10, opplist.size());
        
    }

}

Thanks,
Maharajan.C
DiegoT.DiegoT. 
Hi everyone, i am new with Apex and i have a question.
I want to update the Contact object field location_boat__c and that the location__c fields of the Boat object be updated also be updated My test is incompleted. i want test my trigger UpdateLocationand i dont know how do it
the object Boat field name Contac__c have relationship lookup with the Contact (Object standard)
My test is wrong but i can not how resolve this problem
trigger UpdateLocation on Contact (after update) { if (trigger.isAfter
&& Trigger.isUpdate) {
     List<Boat__c> boats = new List<Boat__c>();
     for (Contact c : [
                 SELECT location_boat__c, (SELECT Id FROM Boats__r)
                 FROM Contact
                 WHERE Id = :trigger.new
             ]) {
         for (Boat__c b : c.Boats__r) {
             b.location__c = c.location_boat__c;
             boats.add(b);
         }
     }
     update(boats); }}
 
@isTest
public class PruebaBotes {
@isTest static void TestActualizar() {

            Boat__c b1  = new Boat__c(Name='bote uno' ,Price__c=20, Type__c='Velero', location__c='Argentina');
            Boat__c b2  = new Boat__c(Name='bote dos' ,Price__c=50, Type__c='Yate', location__c='Brasil');
            Boat__c b3  = new Boat__c(Name='bote tres' ,Price__c=125, Type__c='Catamaran', location__c='España');
            Boat__c b4  = new Boat__c(Name='bote cuatro' ,Price__c=700, Type__c='Velero', location__c='India');

            insert b1;
            insert b2;
            insert b3;
            insert b4;   

            Contact a1 = new Contact(Lastname='Pepe',  location_boat__c = 'Brasil');
            Contact a2 = new Contact(Lastname='Jose',  location_boat__c = 'Argentina');
            Contact a3 = new Contact(Lastname='Maria', location_boat__c = 'India');
            Contact a4 = new Contact(Lastname='Ana',   location_boat__c = 'Argentina');

            insert a1;
            insert a2;
            insert a3;
            insert a4;    

            Contact updateLocation;
            updateLocation = [SELECT location_boat__c FROM Contact WHERE location_boat__c = 'Argentina' LIMIT 1];
            updateLocation.location_boat__c = 'India';
            update updateLocation;

Test.startTest();
    Contact afterUpdate = [SELECT  location_boat__c FROM Contact WHERE 
    Id=:updateLocation.Id];
    System.assertEquals('India', afterUpdate.location_boat__c);

    Test.stopTest();


    }
    }

 
Best Answer chosen by DiegoT.
Nayana KNayana K
Please notice the first line :( you have written before insert. 
It should be after update (As per the code you have shared in the question).

please change it
SFDC GuestSFDC Guest 
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;
  }

 
Best Answer chosen by SFDC Guest
Nayana KNayana K
I guess below should work:
Trigger updatePrimaryCheckbox2 on Contact(after insert, after update) {
	Map < Id, Id > accConMap = new Map < Id, Id > ();
	List < Contact > conList = new List < Contact > ();
	
		for (Contact cont: Trigger.New) {
			if (cont.AccountId != null && cont.IsPrimaryContact__c && (Trigger.isInsert || (Trigger.isUpdate && !Trigger.oldMap.get(cont.Id).IsPrimaryContact__c))) {
				accConMap.put(cont.AccountId, cont.Id);
			}
		}
		if(!accConMap.isEmpty()) {
			for (Contact con: [select Id, IsPrimaryContact__c from contact
								where accountid IN: accConMap.keyset()
								AND Id NOT IN: accConMap.values()
								AND IsPrimaryContact__c = true
								]) {
				con.IsPrimaryContact__c = false;
				conList.add(con);
			}
			if(!conList.isEmpty()) {
				update conList;
			}
		}
  }


However, I suggest to have seperate handler class and trigger pattern like below:
public class ContactTriggerHandler {
	public void onAfterInsert(Map<Id, Contact> mapContactOld, List<Contact> lstContactNew) {
		updatePrimaryContactCheckbox(mapContactOld, lstContactNew);
	}
	
	public void onAfterUpdate(Map<Id, Contact> mapContactOld, List<Contact> lstContactNew) {
		updatePrimaryContactCheckbox(mapContactOld, lstContactNew);
	}
	
	private void updatePrimaryContactCheckbox(Map<Id, Contact> mapContactOld, List<Contact> lstContactNew) {
		List<Contact> lstConToUpdate = new List<Contact>();
		Map<Id, Id> mapAccIdToPrimaryConId = new Map<Id, Id>();
		
		for(lstContactNew objContact : lstContactNew) {
			if((Trigger.isInsert || (Trigger.isUpdate && !mapContactOld.get(objContact.Id).IsPrimaryContact__c)) && objContact.AccountId != null && objContact.IsPrimaryContact__c) {
				mapAccIdToPrimaryConId.put(objContact.AccountId, objContact.Id);
			}
		}
		
		if(!mapAccIdToPrimaryConId.isEmpty()) {
			for (Contact objContact : [SELECT Id, IsPrimaryContact__c FROM Contact
								WHERE AccountId IN: mapAccIdToPrimaryConId.keyset()
								AND Id NOT IN: mapAccIdToPrimaryConId.values()
								AND IsPrimaryContact__c = true
								]) {
				objContact.IsPrimaryContact__c = false;
				lstConToUpdate.add(con);
			}
			if(!lstConToUpdate.isEmpty()) {
				update lstConToUpdate;
			}
		}
	}
}
 
trigger updatePrimaryCheckbox2 on Contact(after insert, after update) {
	ContactTriggerHandler objHandler = new ContactTriggerHandler();
	if(Trigger.isAfter) {
		if(Trigger.isInsert) {
			objHandler.onAfterInsert(Trigger.OldMap, Trigger.New);
		}
		else if(Trigger.isUpdate) {
			objHandler.onAfterUpdate(Trigger.OldMap, Trigger.New);
		}
	}
}