+ Start a Discussion
Satish RamananSatish Ramanan 

Regarding triggers

Hi, I am trying to develop a trigger which will insert a unique value for a text field for the newly entered record. The value to the text field should be assigned depending on the value of the another Picklist field. The trigger is as follows.

trigger PPCIDtrigger on Lead (before insert, before update)
{    
    if(Trigger.isInsert || Trigger.isUpdate)
    {
        for(Lead a: Trigger.new)
        {
            if (a.Lead_Type__c == 'Paisapak Consumer')
            {
                a.PPC_ID__c='WS' +  ;        
            }
        }
    }
}


Here Lead Type is a pick list and PPC ID is a unique text field. I want to assign a value in PPC ID field only when Lead Type = "Paisapak Consumer". One more thing I want to add after "WS" text in PPC ID field is sequence number which shall start by 001 for the first record whose Lead Type is "Paisapak Consumer" and then shall be increased by 1 for every next new record whose Lead Type is "Paisapak Consumer". Will be grateful if I get assistance for this.

Thanks.

Anoop AsokAnoop Asok

Try this:

 

trigger PPCIDtrigger on Lead (before insert, before update)
{  
    if(Trigger.isInsert || Trigger.isUpdate)
    {
        integer recordCount = [select count() from Lead where Lead_Type__c = 'Paisapak Consumer'];
        
        for(Lead a: Trigger.new)
        {
            if (a.Lead_Type__c == 'Paisapak Consumer')
            {
                String strCount = String.valueOf(recordCount);
                if (recordCount < 10){
                    strCount = '00'+strCount;
                }else if (recordCount <100){
                    strCount = '0' + strCount;
                }
                a.PPC_ID__c='WS' + strCount ;
                recordCount++;
            }
        }
    }
}

 

Thanks,

Anoop