Auto complete text box in Salesforce

Auto completion of text box is an important feature to be added in many projects.
Use the below codes in your project for auto completion of text box in Salesforce.

Apex Class:

Name: autoCompleteController

global class autoCompleteController 
{
    @RemoteAction
    global static SObject[] findSObjects(string obj, string qry, string addFields, string profilename) 
    {
        /* More than one field can be passed in the addFields parameter
           Split it into an array for later use */
        List<String> fieldList=new List<String>();
        if (addFields != '')  
        fieldList = addFields.split(',');
        
        /* Check whether the object passed is valid */
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        Schema.SObjectType sot = gd.get(obj);
        if (sot == null) 
        {
            return null;
        }
        
        /* Creating the filter text */
        String filter = ' like \'%' + String.escapeSingleQuotes(qry) + '%\'';
        
        /* Begin building the dynamic soql query */
        String soql = 'SELECT Name';
        
        /* If any additional field was passed, adding it to the soql */
        if (fieldList.size()>0) 
        {
            for (String s : fieldList) 
            {
                soql += ', ' + s;
            }
        }
        
        /* Adding the object and filter by name to the soql */
        soql += ' from ' + obj + ' where name' + filter;
        
        if(profilename!='')
        {
            //profile name and the System Administrator are allowed
            soql += ' and Profile.Name like \'%' + String.escapeSingleQuotes(profilename) + '%\'';
            system.debug('Profile:'+profilename+' and SOQL:'+soql);
        }
        
        /* Adding the filter for additional fields to the soql */
        if (fieldList != null) 
        {
            for (String s : fieldList) 
            {
                soql += ' or ' + s + filter;
            }
        }
        
        soql += ' order by Name limit 20';
        
        system.debug('Qry: '+soql);
        
        List<sObject> L = new List<sObject>();
        try 
        {
            L = Database.query(soql);
        }
        catch (QueryException e) 
        {
            system.debug('Query Exception:'+e.getMessage());
            return null;
        }
        return L;
   }
}

Apex Component:


Name: autoComplete

<apex:component controller="autoCompleteController">

  <!-- JQuery Files -->

  <apex:includeScript value="{!URLFOR($Resource.jqueryui18, 'js/jquery-1.7.1.min.js')}" />

  <apex:includeScript value="{!URLFOR($Resource.jqueryui18, 'js/jquery-ui-1.8.18.custom.min.js')}" />

  <apex:stylesheet value="{!URLFOR($Resource.jqueryui18,'css/smoothness/jquery-ui-1.8.18.custom.css')}"/>

  <!-- Attributes Required For Component -->

  <apex:attribute name="objectname" description="The object name you want to look for." type="String" required="true"/>

  <apex:attribute name="additionalfield" description="Any additional fields you'd like to search and include in the display." type="String" required="false"/>

  <apex:attribute name="profilename" description="To filter on the basis of profile name and include in the display." type="String" required="false"/>

  <apex:attribute name="autocomplete_textbox" description="The ID for the Autocomplete List Textbox." type="String" required="true"/>

   <!-- CSS Style -->

  <style>

    .ui-autocomplete-loading {background: white url({!$Resource.loadingIcon}) right center no-repeat;}

  </style>

  <!-- Javascript -->

  <script type="text/javascript">

    var j$ = jQuery.noConflict();

    j$(document).ready(function()

    {

        var sObjects;

        var queryTerm;

        j$(esc('{!autocomplete_textbox}')).autocomplete({

            minLength: 1,

            source: function(request, response) {

                        queryTerm = request.term;

                        autoCompleteController.findSObjects("{!objectname}", request.term, "{!additionalfield}", "{!profilename}", function(result, event){

                            if(event.type == 'exception')

                            {

                                  alert(event.message);

                            } else

                            {

                                 sObjects = result;

                                 response(sObjects);

                            }

                        });

                   },

            focus: function( event, ui ) {

                    j$(esc('{!autocomplete_textbox}')).val( ui.item.Name );

                    return false;

                    },

            select: function( event, ui ) {

                        j$(esc('{!autocomplete_textbox}')).val( ui.item.Name );

                        j$(esc('{!autocomplete_textbox}_lkid')).val( ui.item.Id );

                        j$(esc('{!autocomplete_textbox}_lkold')).val( ui.item.Name );

                        if (event.keyCode == 13) {

                            event.preventDefault();

                        }

                        return false;

                    },

         })

         .data( "autocomplete" )._renderItem = function( ul, item ) {

            var entry = item.Name;

            if("{!additionalfield}" !='')

            {

                j$.each("{!additionalfield}".split(",") , function(key, value) {

                    entry = entry + " " + item[value];

                });

            }

            //entry = entry + "</a>";

            //entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");

            entry = entry.replace( new RegExp( "(" + queryTerm + ")" , "gi" ), "<strong>$1</strong>" );

            return j$( "<li></li>" )

                .data( "item.autocomplete", item )

                .append( "<a>" + entry + "</a>")

                .appendTo( ul );

        };

    });

    function esc(myid)

    {

           return '#' + myid.replace(/(:|\.)/g,'\\\\$1');

    }

  </script>

</apex:component>


Static Resource:


Add a gif format loading image in Static resources with the name 'loadingIcon'.




Download jqueryui18 file from the below link

http://www.4shared.com/file/9o5DuyQy/jqueryui18.html


which is to be added in Static Resources.

Visualforce Pages examples:

Example for <apex:inputText>:


<apex:inputText value="{!memName}" id="membNam" >
<c:autoComplete autocomplete_textbox="{!$Component.membNam}" objectname="Member__c" />
</apex:inputText> 

Example for <apex:inputfield>:


<apex:inputfield value="{!Member__c.Name}" id="memNam">
        <c:autoComplete autocomplete_textbox="{!$Component.memNam}" objectname="Member__c" />
</apex:inputfield> 



Cheers!!!

Types of test databases in Database.com

There are two types of test databases in Database.com. They are
1. QA database
2. Staging database

A QA test database is a copy of your current production database configuration and code, but no data. A staging test database replicates all of your data as well.

Cheers!!!

Database.com


Database.com is a cloud database that makes it easy to build collaborative, mobile enterprise applications. Secure sharing of data is at the heart of collaborative enterprise applications.

The sophisticated identity and access management capabilities in Database.com ensure that you can get the right data, to the right people, at the right time, with the right access permissions.

For more details, visit www.database.com/workbook.


Cheers!!!

Closing window in Salesforce

Note: Disable the development mode.

<apex:page showChat="false" wizard="true" sidebar="false" >
<!-- Javascript -->
<script type = "text/javascript">
    function winClose()
    {
        self.close();
    }
</script>
<!-- End of Javascript-->

<apex:commandButton onComplete = "winClose();">

</apex:page>


Cheers!!!

Dynamically deleting rows in apex pageBlock

Visualforce page:

<apex:page showChat="false" wizard="true" sidebar="false" controller="MemberPopup" >
<!-- Javascript -->
<script type = "text/javascript">
    function winClose()
    {
        self.close();
    }
</script>
<!-- End of Javascript-->
<apex:form >
    <apex:pageBlock >
        <apex:pageblockSection >
            <apex:pageblocktable value="{!memberList}" var="mem">
                <apex:column title="Name" value="{!mem.Name}"/>
                <apex:column title="eMail Id" value="{!mem.E_Mail_Id__c}"/>
            </apex:pageblocktable>
        </apex:pageblockSection>
    </apex:pageBlock>
   
    <apex:variable var="rowNum" value="{!0}"  />
   
    <apex:pageBlock id="membAdd" >  
    <apex:variable var="rowNum" value="{!0}"  />              
        <apex:pageblockSection >
            <apex:pageBlockTable value="{!memberAddList}" var="memb">
                <apex:facet name="footer">
                    <apex:commandLink value="Add Row" action="{!addRow}" reRender="membAdd"/>
                </apex:facet>
                <apex:column headerValue="No." style="width:20px; text-align:center;" headerClass="centertext">
                    <apex:outputText value="{0,number, ###}" style="text-align:center;">  
                        <apex:param value="{!rowNum+1}" />  
                    </apex:outputText>
                </apex:column>           
                <apex:column headerValue="Member Name">
                    <apex:inputField value="{!memb.Name}"/>
                </apex:column>
                <apex:column headerValue="Mobile Number">
                    <apex:inputField value="{!memb.Mobile_Number__c}"/>
                </apex:column>
                <apex:column headerValue="eMail Id">
                    <apex:inputField value="{!memb.E_Mail_Id__c}"/>
                </apex:column>
                <apex:column headerValue="Delete" >
                    <apex:commandLink style="font-size:15px; font-weight:bold; text-align:center;color:red;" value="X" action="{!delRow}" reRender="membAdd,temp" rendered="{!rowNum>0}">
                        <apex:param value="{!rowNum}" name="index" />
                    </apex:commandLink>
                    <apex:variable var="rowNum" value="{!rowNum+1}"/>
                </apex:column>               
            </apex:pageBlockTable>                   
        </apex:pageblockSection>       
        <apex:pageblockSection columns="1" >
            <apex:pageblockSectionItem >
                <apex:commandButton value="Save" action="{!saveMemb}" onComplete="winClose();"/>
                <apex:commandButton value="Cancel" onclick="winClose();" />
            </apex:pageblockSectionItem>        
        </apex:pageblockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex controller:

public class MemberPopup

{
    public List<Member__c> memberList {get;set;}
    public List<Member__c> memberAddList {get;set;}
    public String memberName {get;set;}
    public Integer rowNum{get;set;}
   
    public MemberPopup()
    {
        String sql = 'SELECT Name, E_Mail_Id__c FROM Member__c';
        memberList = Database.Query(sql);
        memberAddList = new List<Member__c>();
        memberAddList.add(new Member__c());
    }
       
    public void AddRow()
    {
        memberAddList.add(new Member__c());
    }
   
    public void delRow()
    {
        rowNum = Integer.valueOf(apexpages.currentpage().getparameters().get('index'));
        memberAddList.remove(rowNum);  
    }   
   
    public void saveMemb()
    {
        insert memberAddList;
    }
}

MVC (Model - View - Controller) Pattern in Salesforce


M - Model(Object, Fields, Relationships, Apex Classes)
V - View(Visualforce page, Pagelayouts, Record Types, Force.com Sites, Components)
C - Controller(Validation Rules, Controllers in a Visualforce page)

Model
  1. The database layer
  2. Contains objects, fields, and security
Controller
  1. The business logic layer
  2. Links the Model to the View
  3. Contains Workflow, Validation Rules, Apex
View
  1. The user interface layer
  2. Tabs, Page Layouts, Visual Force

Dynamically adding rows in apex pageBlock

Visualforce code:

<apex:page sidebar="false" controller="MemberPopup" >
<apex:form >
    <apex:pageBlock id="membAdd" >                 
        <apex:pageblockSection >
            <apex:pageBlockTable value="{!memberAddList}" var="memb">
                <apex:column headerValue="Member Name">
                    <apex:inputField value="{!memb.Name}"/>
                </apex:column>
                <apex:column headerValue="Mobile Number">
                    <apex:inputField value="{!memb.Mobile_Number__c}"/>
                </apex:column>
                <apex:column headerValue="eMail Id">
                    <apex:inputField value="{!memb.E_Mail_Id__c}"/>
                </apex:column>
            </apex:pageBlockTable>
            <br/><apex:commandLink value="Add Row" action="{!addRow}" reRender="membAdd"/>       
        </apex:pageblockSection>       
        <apex:pageblockSection columns="1" >
            <apex:pageblockSectionItem >
                <apex:commandButton value="Save" />
                <apex:commandButton value="Cancel" />
            </apex:pageblockSectionItem>        
        </apex:pageblockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Code:

public class MemberPopup
{
    public List<Member__c> memberList {get;set;}
    public List<Member__c> memberAddList {get;set;}
    public String memberName {get;set;}  
    
    public MemberPopup()
    {
        String sql = 'SELECT Name, E_Mail_Id__c FROM Member__c';
        memberList = Database.Query(sql);
        memberAddList = new List<Member__c>();
        memberAddList.add(new Member__c());
    }
   
    public void AddRow()
    {
        memberAddList.add(new Member__c());
    } 
}


Before adding rows:





After adding rows:

Approval through email in Salesforce

1. Go to App setup --> Create --> Workflow & Approvals


2. Check Enable Email Approval response and select the user.


Sample eMail:


Sample reply:


Packages in Salesforce

Step 1: Create a custom App.
Add an image to the Documents and make it externally available. Use the image as logo to the custom application.


Make your application visible in App menu.


Step 2: Create Packages.



Add Components to the Package.



Add custom app to the Package.


We can also add other components to our Package.


Step 3: Upload your package.
If your package contains any Apex Code (Classes or Triggers), you must ensure at least 75% of your Apex scripts are covered by unit tests, and all of those tests complete successfully.




Step 4: Register your Package.
Registering your package is the first step to making your app available publicly on the AppExchange. Registering your package creates a Private listing and URL that you can share with others. You must go through the AppExchange Review process to make your private listing public.

              To Register, click Proceed to the AppExchange to register from the package upload detail page.


To log into the AppExchange, select the Login or Register tab on the top right. Your Publisher Login is the SAME login you use to access your Developer Edition to build the app.

You can either create a new blank listing and associate your package later or you can select List It in the Your Uploaded Packages section to generate the private listing of your package.


Sample eMail package in Salesforce

The link to download the package in your salesforce login, click the following link

https://login.salesforce.com/packaging/installPackage.apexp?p0=04tU0000000M33N.

This provides a sample package, which is mainly used to send emails.


Cheers!!!

Regular Expression using apex in Salesforce

String tempStr = 'test.78@gmail.com';

if(!Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}', tempStr))

{                         
    //error msg
}

Cheers!!!