Salesforce

An effort to bring a revolution in Salesforce.

Tuesday, 26 July 2016

Read csv file then create Account in Apex Salesforce.

Sample logic code. 



Document doc=[SELECT Body,ContentType,Description,DeveloperName,Name FROM Document WHERE Name = 'Csv File'];
    String[] columns=doc.Body.toString().split('\n');
    String[] columnNames=columns[0].split(',');
    columns.remove(0);

    for(String str:columns)
    {
        Account acc=new Account();
        String[] fields=str.split(',');
        for(Integer i=0;i<fields.size()-1;i++)
        {
            acc.put(columnNames[i],fields[i]);
        }
        lstAccounts.add(acc);
    }


Insert  lstAccounts;
, ,

How can I change the visualforce page to a public one?

Please follow the below steps for make visual force page public.
  • go to Setup > Develop > Sites,
  • register your Force.com subdomain name,
  • create a new Force.com Site
  • next to 'Site Visualforce Pages' click Edit
  • add your page to the list of Enabled Visualforce Pages

Please check the below links for more details.

https://developer.salesforce.com/page/An_Introduction_to_Force.com_Sites

https://help.salesforce.com/HTViewHelpDoc?id=sites_public_access_settings.htm

,

how to display two objects fields in visualforce page by using wrapper class?



Please find below an example of how to accomplish this.

I've included 2 ways to do this:
Using a single query

Using a wrapper class My controller (AccountContactWrapperController.class): 

public class AccountContactWrapperController {

    public List<Account> accounts{get;set;}
    public List<ACWrapper> ACWrappers{get;set;}

    public AccountContactWrapperController(){
        this.ACWrappers = new List<ACWrapper>();
        this.accounts = new List<Account>();

        //Get Accounts & Related Contacts in 1 query
        List<Account> accs = [Select Id, Name, (Select Id, FirstName, LastName From Contacts) From Account Limit 1];
        this.accounts = accs;

        //Get Accounts & Contacts in separate queries for Wrapper
        List<Account> accsForWrapper = [Select Id, Name From Account Limit 1];
        List<Contact> consForWrapper;
        Account acc;
        if(accsForWrapper != null && !accsForWrapper.isEmpty()){
            acc = accsForWrapper.get(0);
            consForWrapper = [Select Id, FirstName, LastName From Contact Where AccountId =:acc.Id];
        }
        if(consForWrapper != null){
            ACWrapper wrapper = new ACWrapper(acc, consForWrapper);
            this.ACWrappers.add(wrapper);
        }
    }

    public class ACWrapper{
        public Account account{get;set;}
        public List<Contact> contacts{get;set;}

        public ACWrapper(Account acc, List<Contact> cons){
            account = acc;
            contacts = cons;
        }
    }

}


My VF page (AccountContactWrapperTest.page): 

<apex:page controller="AccountContactWrapperController" >
<apex:form >

<!--Display Account & Contact info from 1 Query-->
<apex:pageBlock title="Info From Query">
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:Column value="{!a.Name}" />
<apex:Column headerValue="Contact Names">
<apex:repeat value="{!a.Contacts}" var="c">
{!c.FirstName} {!c.LastName} <br />
</apex:repeat>
</apex:Column>
</apex:pageBlockTable>
</apex:pageBlock>

<!--Display Account & Contact info from 1 Wrapper class-->
<apex:pageBlock title="Info From Wrapper class">
<apex:pageblocktable value="{!ACWrappers}" var="w">
<apex:Column value="{!w.account.Name}" />
<apex:column headervalue="Contact Names">
<apex:repeat value="{!w.contacts}" var="c">
{!c.FirstName} {!c.LastName} <br/>
</apex:repeat>
</apex:column>
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
</apex:page> 


      Output:

, , ,

difference between trigger.old and trigger.oldmap

Trigger.old: Returns a list of the old versions of the sObject records.
Note that this sObject list is only available in the update and delete triggers.

Trigger.oldMap: A map of IDs to the old versions of the sObject records.Note that this map is only available in the update and delete triggers.

Let say  you have a custom object Account.

Trigger.old&nbsp;means it is a&nbsp;List<Account>

Trigger.oldMap&nbsp;means it is a&nbsp;map<Id,Account>

Salesforce System.assert(Methods)

System.assert()

System.assert() detailed explanation below.

A simple scenario would be to create a test class +methods in which some work is done (e.g. put something into the DB, update a field or whatever). Once this is done you would use System.Assert functions to check what has been done.

For example:-

integer i = 0;
integer j = 1;

//this would throw an error and cause your test to fail
System.assertEquals(i,j);
//this would pass
System.assertNotEquals(1,i);
etc...

You may put something into the DB via an insert. You may then expect a trigger to run so you would then reload the item and check that the trigger has fired correctly as certain fields have been updated.

Really you could interchange any of the Assert functions dependent on your logic. Up to you. I find it easier to use AssertEquals as I mostly want to check that a proper number of records have been returned or that something I know about has happened and I'm expecting a certain result etc...

You are really just trying to create a method to test that some logic (i.e. code - trigger, apex...) is working correctly. Testing is required to cover a certain percentage of a class to enable packaging and a trigger must be tested (greater than 0%) to enable packaging.

Example for system.assert logic :

System.Assert(Today.Year()==2016);

Alternatively System.AssertEquals(2016,Today.Year());

Or System.AssertNotEquals(2015,Today.Year());

Could call a user function like:-

System.Assert(isYear2016());

public boolean isYear2016(){
return (Today.Year==2016 ? true : false);
}
, , , ,

Salesfrorce Batch apex and schedulable apex

Batch Apex in Salesforce
 
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
 
Start method


          The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.
 
Execute Method

          The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}
 
This method takes the following:
o    A reference to the Database.BatchableContext object.
o    A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records execute in the order they are received from the start method.
 
Finish Method

Syntax: global void finish(Database.BatchableContext BC){}
 
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
 
Example of Batch Apex Class: 
 
Batch Schedule Class
 
global class batchContactUpdate implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id, FirstName,LastName FROM Contact';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
         for(Contact a : scope)
         {
             a.FirstName=a.FirstName+'FirstName is Updated';
             a.LastName = a.LastName +'LastName is updated';         
         }
         update scope;
    } 
    global void finish(Database.BatchableContext BC)
    {
    }
}
 
Schedule Class
 
global class BatchScheduleUpdate implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
      
        // We now call the batch class to be scheduled
        BatchContactUpdate b = new BatchContactUpdate ();
      
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,200);
    }
  
}
 

Schedule from Developer Console

BatchScheduleUpdate batchSch=new BatchScheduleUpdate();
String sch='0 5 2 * * ?';
//System.schedule(String jobName, String cronExp, APEX_OBJECT schedulable);
System.schedule('Batch Schedule', sch , batchSch);

 

, , ,

difference between a normal wrapper and a REST API wrapper



Please find the difference between a normal wrapper and a REST API wrapper.


Wrapper Class : A Wrapper Class (or the Wrapper Pattern) is where you declare a Class as a container for an sObject to extend the functionality only for display or processing purposes (i.e. you don't intend for that attribute to be persisted) - the classic example is a checkbox to select records. I would say that a DTO is a slightly dumbed down version of such a wrapper (used in conventional OOP to pass structured data between the layers)

REST API Wrapper : A REST API wrapper is something slightly different. Salesforce exposes a REST API and if you were to invoke that say from C#, you would have to perform a set of common steps such as login, query, etc. To make this available in C# by abstracting the innards of the actual REST calls to salesforce and exposing only the developer relevant detail, you could write a rest wrapper which performs these commonly used functions - creates requests, parses responses, etc.

For use cases please refer to the below link.
https://www.godaddy.com/garage/webpro/wordpress/3-practical-use-cases-wp-rest-api/
, , ,

How can I show/ hide a div when the checkbox is selected?

Here is simple code With javascript.


<apex:page >
 <head>

 </head>
 <apex:form >
  <script>
  function HideMsg(istrue)
  {
    var checkval = document.getElementById("msg")
    if(istrue.checked )
    {  
        var checkval = document.getElementById("msg").style.display='block';
    }
    else
    {
        var checkval = document.getElementById("msg").style.display='none';
    }
  }
  </script>
  <apex:pagemessages />

  <div>
   <apex:inputCheckbox id="checkbox" onchange="HideMsg(this);"/>
  </div>
  <div class="showp" style="display: none" id="msg">
  <p>Hello World</p>
  </div>
 </apex:form>
</apex:page>
,

Convert Date to DateTime in salesforce


 

Simple code is used to convert Date to DateTime data type using Apex


Sample Code:

 
 
Date dToday = System.Today();
Datetime dt = datetime.newInstance(dToday.year(), dToday.month(),dToday.day());
, ,

Convert String to Date in salesforce

 

Simple code is used to convert String to Date data type using Apex


Sample Code:

String today = '7/26/2016';

Date dt = Date.parse(today);

,

Get Gmail, Docs, Drive, and Calendar for business