Thursday, June 30, 2016

Check Duplicate Email Using Trigger

/*This code is check Duplicate Emil, if in the records email already exits and again you want to enter same email id then it prevent to save record and show Email Already Exits Error Message */


trigger duplicate_Email_Check on Contact (before insert, before update) {
         set<String> emailAdd = new set<String>();
         
         for(Contact con : Trigger.New){
               emailAdd.add(con.Email);    
         }
         
         List<Contact> conList = [SELECT id, Email FROM Contact where Email IN : emailAdd];
     
        if(Trigger.isUpdate){
            for(Contact con : Trigger.New){
                 if(con.Email!=null && conList.size()>0 && Trigger.oldmap.get(con.id).Email!=con.Email) {
                     con.Email.addError('Email AlReady Exits');
                  }
             }
        }
     
        if(Trigger.isInsert){
            for(Contact con : Trigger.New){
                 if(con.Email!=null && conList.size()>0) {
                     con.Email.addError('Email AlReady Exits');
                 }
            }
        }    
}

//******************************************************************************//
//If You want to Undelete Event also here is code 
trigger duplicate_Email_Check on Contact (after undelete, before insert, before update) {
    Set<String> emailAdd = new Set<String>();

    Integer contactThreshHold;

    Map<String, Integer> emailToNoOfContactsMap = new Map<String, Integer>();


    for(Contact con : Trigger.New){
        emailAdd.add(con.Email);    
    }

    for(Contact existingContact : [SELECT id, Email FROM Contact where Email IN : emailAdd]) {
        if(!emailToNoOfContactsMap.containsKey(existingContact.Email)) {
            emailToNoOfContactsMap.put(existingContact.Email, 0);
        }

        Integer emailRelatedContactCount = emailToNoOfContactsMap.get(existingContact.Email);
        emailRelatedContactCount = emailRelatedContactCount + 1;
        emailToNoOfContactsMap.put(existingContact.Email, emailRelatedContactCount);
    }


    private void checkDuplicateEmail(List<Contact> contactsList, Integer conThreshHold) {
        for(Contact con : contactsList){
            if(con.Email!=null && emailToNoOfContactsMap.get(con.Email) > conThreshHold) {
                con.Email.addError('Email already Exits');
            }
        }
    }

    if(Trigger.isInsert ) {
        checkDuplicateEmail(Trigger.New, 0);
    }

    if(Trigger.isUpdate ) {
        checkDuplicateEmail(Trigger.New, 0);
    }

    if(Trigger.isUnDelete) {
        checkDuplicateEmail(Trigger.New, 1);
    }
}

Wednesday, June 29, 2016

Number of Child Record Count on Parent Record Using Trigger

Number of Child Record Count on Parent Record Using Trigger

I use Account (this is parent) and Contact (this is chlid of Parent object which is Account)
this trigger work for all event like insert , update ,delete and undelete

Trigger ContactCountTrigger on Contact(After insert, After Delete, After Undelete, After Update)
{
  Set<Id> setAccountIds = new Set<Id>();

  if(Trigger.isInsert || Trigger.isUndelete){
for(Contact con : Trigger.new){
if(con.AccountID != Null)
            setAccountIds.add(con.AccountId);
    }
  }

  if(Trigger.isDelete){
     for(Contact con : Trigger.old){
    if(con.AccountID != Null){
                 setAccountIds.add(con.AccountId);
             }
     }
  }

  if(Trigger.isUpdate){
     for(Contact con : Trigger.New){
    if(con.AccountID != Null){
                 setAccountIds.add(con.AccountId);
     }
            if(Trigger.oldMap.get(con.Id).AccountId != null){
                 setAccountIds.add(Trigger.oldMap.get(con.Id).AccountId);
            }
      }
  }

 List<Account> listAccs = [SELECT id,name,number_of_contacts__c ,(Select id from contacts) FROM Account WHERE Id in : setAccountIds];

//number_of_contacts__c this is Number type Field  on account object
//contacts is a child relationship name
  for(Account acc :listAccs){
      acc.number_of_contacts__c = acc.contacts.size();
  }
  update listAccs;
}

Thursday, February 25, 2016

Using Field Set on Visual Force Page and Controller

We can dynamically bind fields on our visual force page using Field Set. It is very useful when we are working with managed package. We can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page without modifying any code. Field sets are available for Visualforce pages on APIversion 21.0 or above. You can have up to 50 field sets referenced on a single page.

step 1

Create Custom Object Name  Fieldset Demo , API name is Fieldset_Demo__c

step 2
create Custom Field
(a) First Name (text 80)
(b) Last Name(text 80)
(c) Email(Email)
(d) phone(phone)
API Name and size also shown in below image.

Step 3
   Mouse over on the Field Sets of Current Custom object. its show dialog box with new button. click on the new . see below image
Yellow Colour highlighted

Step 4

Click on the new button it will display a window which is shown in below image. fill all the field and save it












Step 5
 Drag and drop field on "In the Field Set"  like Firstname lastname email and phone i want to show on the page.
see below image
After that click on the save button

Step 6

Click and open your Custom object (
Fieldset Demo) and save 3-4 records

Step 7
create class (controller)

public class FieldsetController {    
    public List <Fieldset_Demo__c> fList{get;set;}
    public String fields = '';
    
        public FieldsetController() {
        fList = new List<Fieldset_Demo__c>();
        for(Schema.FieldSetMember f : SObjectType.Fieldset_Demo__c.FieldSets.My_Fieldset.getFields()) {
            fields += f.getFieldPath() + ',';
        }
        fields = fields.removeEnd(',');
        String queryString = 'SELECT '+fields+' FROM Fieldset_Demo__c';
        fList = Database.query(queryString);
        
        }
}

NOTE: 
Fieldset_Demo__c this is API name of object      My_Fieldset this is fieldset name    
Step 8
Create page
<apex:page controller="FieldsetController ">
<apex:pageBlock>
  <apex:pageBlockTable value="{!fList}" var="templist" rules="rows"> 
                 <apex:repeat value="{!$ObjectType.Fieldset_Demo__c.FieldSets.My_Fieldset}" var="f"> 
                     <apex:column headervalue="{!f.label}">
                        <apex:outputField value="{!templist[f.fieldPath]}"> </apex:outputField>
                     </apex:column>  
                    </apex:repeat>
              
           </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

Result 





Thanks
Vipin Indora







Extract Signature image and text from received email


Example suppose you get received an Email From Some one
Hi cloudy,
                 Nice to meet you.

--

Thanks & Regards
Salesforce
9876543210
Salesforce Developer

Bold Letter text is signature

global class ProcessContactApplicantEmail implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
     
        Contact contact = new Contact();
        contact.FirstName = email.fromname.substring(0,email.fromname.indexOf(' '));
        contact.LastName = email.fromname.substring(email.fromname.indexOf(' '));
        contact.Email = envelope.fromAddress;
        contact.from__c = email.subject;
 
        string bodystr = email.htmlBody;
        string bodymsg = bodystr.substringBeforeLast('--');
        contact.MainBodyEmail__c = bodymsg;
        string signature = bodystr.substringAfterLast('--');
        contact.MainBodyEmailArea__c = signature;
        //System.debug('++++ '+contact.Signature__c);
        insert contact;
   
        System.debug('====> Created contact==> '+contact.Id);
     
        if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
          for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
            Attachment attachment = new Attachment();
            // attach to the newly created contact record
            attachment.ParentId = contact.Id;
            attachment.Name = email.binaryAttachments[i].filename;
            attachment.Body = email.binaryAttachments[i].body;
            insert attachment;
            system.debug('---> '+attachment.name+' @@@@ '+attachment.body);
          }
    }
       return result;
    }
 
 
 
}
Bulk insert on Contact Standard Object

Controller

public class BulkInsertController{
    public List<contact> contacts{get;set;}
    //Constructor
    public BulkInsertController(){
        initialize();
    }
    public void initialize(){
        contacts = new List<contact>();
        contacts.add(new contact());
       contacts.add(new contact());
      contacts.add(new contact());
    }
    public void save(){
        insert contacts;
    }
}

Page
<apex:page controller="BulkInsertController">
<apex:form>
    <apex:pageBlock title="Bulk Contact Insert">
        <apex:pageBlockTable value="{!contacts}" var="con">
            <apex:column headerValue="First Name">
                <apex:inputField value="{!con.firstname}"/>
            </apex:column>
            <apex:column headerValue="Last Name">
                <apex:inputField value="{!con.lastname}" required="false"/>
            </apex:column>
            <apex:column headerValue="Email">
                <apex:inputField value="{!con.email}"/>
            </apex:column>
            <apex:column headerValue="Phone">
                <apex:inputField value="{!con.phone}"/>
            </apex:column>
        </apex:pageBlockTable>
        <apex:commandButton action="{!save}" value="Save" immediate="true"/>
    </apex:pageBlock>
</apex:form>

</apex:page>