Posts

Showing posts from 2017

How to Select All Fields with SOQL in Apex

How to Select All Fields with SOQL in Apex // Based on Record ID , fetch all the field particular object ID recordId = '01t90000000vQFw'; DescribeSObjectResult describeResult = recordId.getSObjectType().getDescribe(); List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() ); System.debug( fieldNames); String query = ' SELECT ' + String.join( fieldNames, ',' ) +' FROM ' + describeResult.getName() +' WHERE ' +     ' id = :recordId ' + ' LIMIT 1 ';        // return generic list of sobjects or typecast to expected type List<SObject> records = Database.query( query ); System.debug( records ); // Based on Object without an ID, simply specify the object to then derive the sobject type     DescribeSObjectResult describeResult = SobjectApiName.getSObjectType().getDescribe(); List<String> fieldNames = new List<String>( describeResult.fields.getMap().key

Show Pagination and Colum Sorting on VF page using Jquery Plugin

Image
Requirement:  To show Account record in table form on VF page and user able to paginate pages and sort the column: Solution:  Using Jquery Plugin you can directly implement pagination and column Sorting Download Jquery Plugin : https://sfcomponent-dev-ed.my.salesforce.com/sfc/p/#6F000001f5y8/a/6F0000004XWj/F0czOc51PF5iaC7ERZBb.cO.nU95xWyEaGcUTmPkCaU Add data table zip file in Static Resource Class Code: public class AccountController {  public List<Account> lstofacc{get;Set;}  public AccountController ()  {      lstofacc = new List<Account>([select id,AccountNo, name from account]);        } } Page Code: <apex:page controller=" AccountController  " sidebar="false" standardStylesheets="false" docType="html-5.0" tabStyle="Account"> <head> <apex:stylesheet value="{!URLFOR($Resource.DataTable,'DataTable/datatables.min.css')}" /> <apex:stylesheet value="

Update Account Comment from Task Insertion Using Trigger

Requirement: Write a trigger to update account comment field from Task comment value on insertion of Task under Account Solution : trigger updateAccountCommentFromTask on Task (before insert) { String account_prefix = Schema.SObjectType.Account.getKeyPrefix(); Map<Id,Account> accountMap = new Map<Id,Account>(); Set<id> setofWhatID = new Set<id>(); for (Task objTask: Trigger.new)  { setofWhatID.add(objTask.WhatId); } Map<id,Account> MapAccIDToAccount = new Map<id,Account>([Select Id, Account_Status_Sales__c from Account Where Id in :setofWhatID]); for (Task objTask: Trigger.new) if(objTask.Subject != null && objTask.WhatId !=null && ((String)objTask.WhatId).startsWith(account_prefix)) { Account a = MapAccIDToAccount.get(objTask.WhatId); a.Comment__C = objTask.Comment__c; accountMap.put(a.id,a); } try { update accountMap.values(); } catch (system.Dmlexception e)  { system.debu

Duplicate Prevent Lead Based On Email

Requirement : Write a trigger to prevent duplicate Email on Lead Object Solution : trigger leadDuplicatePreventer on Lead (before insert, before update) { Map<String, Lead> leadMap = new Map<String, Lead>(); for (Lead lead : System.Trigger.new) { if ((lead.Email != null) &&     (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) { if (leadMap.containsKey(lead.Email)) {   lead.Email.addError('Another new lead has the ' + 'same email address.'); } else {      leadMap.put(lead.Email, lead);  } } } for (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) { Lead newLead = leadMap.get(lead.Email); newLead.Email.addError('A lead with this email ' + 'address already exists.'); } }                              Thanks,                            Sumit Shukla

Save the Batch Error Job ID in Custom Object in case of Failure

Requirement :  Get the Failure record when processing thru batch Class Solution : Create a custom object for saving batch log errors and create a batch class   Custom Object: Batch_Log_Error__c  Custom Fields : Job_id__c,Record_Id__c,Error__c global class BatchClassName implements Database.batchable<sObject>,Schedulable{ String query ; // define Constructor global BatchClassName(){  query = 'Select id from SobjectapiName'; }  // Start Method Call    global Database.QueryLocator start(Database.BatchableContext BC){         return Database.getQueryLocator(query);    }        //  Execute Method Call global void execute(Database.BatchableContext bc, List<SobjectapiName> scope){ // Declare SobjectList and BatchErrorLoglst  list<SobjectapiName> lstofsobject  = new list<SobjectapiName>(); list<Batch_Log_Error__c> lstObjBatchLogError = new list<Batch_Log_Error__c>() try{ for(SobjectapiName obj :sco

Show Hyper Link On Add Error in Salesforce Trigger

Requirement: Check Duplicate record in system and show the add error in form of hyperlink corresponding duplicate record ID Solution : Write a trigger and show add error objExistingRecord >>> OldRecord Id objNewRecord >> New Record  objNewRecord.addError('Same Combination of Record already Inserted in System: <a href=\'/'+ objExistingRecord.id +'\'>'+objExistingRecord.Name+'</a>', false);                                                                           Thanks                                                Sumit Shukla

Schedule Class for every One Hour Everyday in Salesforce

Write below code in "Developer Console" to schedule class for every One Hour Everyday.  Apex Code: NameofScheduleclassEveryhour objschclass =  new NameofScheduleclassEveryhour (); string strSeconds = '0'; string strMinutes = '0'; string strHours = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23'; string strDay_of_month = '*'; string strMonth = '*'; string strDay_of_week = '?'; String sch = strSeconds + ' ' + strMinutes + ' ' + strHours + ' ' + strDay_of_month + ' ' + strMonth + ' ' + strDay_of_week; system.schedule('ScheduleclassEveryhour', sch, objschclass);                                    Thanks,                               Sumit Shukla

Schedule Apex Class Job Script

Schedule Apex Class Job Script You Can run you job script in two ways 1 ) From UI : Go to Setup -> Apex Classes -> Click on Schedule Apex button  2) From Developer Console, check below  For Monitor : Go to Setup—>Monitor –> Scheduled Jobs Syntax:  Seconds Minutes Hours Day Month Week Year Year is optional. Seconds                         :- 0–59 Minutes                         :- 0–59 Hours                            :- 0–23 Day (Day_of_month)    :- 1–31 Month                            :- 1–12 Week (Day_of_week)     :- 1–7 Year                             :- null or 1970–2099 The following are some examples of cron expressions: Expression          Description 0 0 14 * * ? Class runs every day at 2 PM. 0 0 20 ? * 6L Class runs the last Friday of every month at 8 PM. 0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 AM. 0 0 20 * * ? 2016 Class runs every day at 8 PM during the year 2016. System.schedule('Job Name ', '0 0

Date Function using in apex

Date Functions are mostly using in apex (Salesforce) addDays(additionalDays) : This function adds the specified number of additional days to a Date. Syntax : public Date addDays(Integer additionalDays) addMonths(additionalMonths) : This function adds the specified number of additional months to a Date . Syntax : public Date addMonths(Integer additionalMonths) addYears(additionalYears) : This function adds the specified number of additional years to a Date . Syntax : public Date addYears(Integer additionalYears) day() : This function returns the day-of-month component of a Date . Syntax : public Integer day() dayOfYear() : This function returns the day-of-year component of a Date . daysBetween(secondDate) : This function returns the number of days between the Date that called the method and the specified date. daysInMonth(year, month) : This function returns the number of days in the month for the specified year and month (1=Jan) . format() : This function r

Standard Pagination Using Standard Controller based on RecordSetVar

Image
<apex:page standardController="Opportunity" recordSetVar="opportunities" tabStyle="Opportunity" sidebar="false">     <apex:form >             <apex:pageBlock title="Edit Opportunities" >             <apex:pageMessages ></apex:pageMessages>             <apex:pageBlockButtons >               <apex:commandButton value="Save" action="{!save}"/>               <apex:commandButton value="Cancel" action="{!cancel}"/>             </apex:pageBlockButtons>             <apex:pageBlockTable value="{!opportunities}" var="opp">                 <apex:column value="{!opp.name}"/>                   <apex:column headerValue="Stage">                     <apex:inputField value="{!opp.stageName}"/>                   </apex:column>                   <apex:column headerV

Get list of Key Prefix of Sobject in Salesforce

Image
Requirement:  Show the list of Key Prefix of Sobject in salesforce Solution: Class Code: public class populateObjectsAndKeyPrefixController {      public List<Schema.SObjectType> lstofSType {get;set;}       public List<SObjectInfo> lstofSobject {get;set;}           public class SObjectInfo {         public String prefix {get;set;}         public String name {get;set;}     }        public gettingObjectsAndKeyPrefix(){                        lstofSType  = Schema.getGlobalDescribe().Values();         lstofSobject = new List<SObjectInfo>();         for(Schema.SObjectType f : lstofSType )         {             SObjectInfo sobjectinfo = new SObjectInfo();            sobjectinfo.prefix = f.getDescribe().getKeyPrefix();             sobjectinfo.name = f.getDescribe().getLabel();             lstofSobject.add(SObjectInfo);         }             } } VF Page Code <apex:page controller="populateObjectsAndKeyPrefixController "

Find Day of selected Date on VF Page

Image
Requirement: Find the day of selected date in date field Solution: public class DayOfDate {     Private Date startDate = date.newInstance(0001, 1, 1);        Public Date selectedDate{get;set;}     public String dayValue{get;set;}     public Account acc {get;set;}     public DayOfDate()     {           system.debug('startDate***'+startDate);         selectedDate = date.today();         system.debug('selectedDate*****'+selectedDate);         acc = new Account();     }     public void calculateDayOfDate()     {         List<String> listDay = new List<String>{'Saturday' , 'Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday'};         selectedDate = acc.SLAExpirationDate__c;         Integer remainder = Math.mod(startDate.daysBetween(selectedDate) , 7);         system.debug('remainder____'+remainder);         dayValue = listDay.get(r

Show All custom and standard Object and respective field on VF Page

Image
Requirement: Provide a option on vf page that user can select any custom or standard object and create slelected SOQL query and get records according to selected fields  Solution:  Controller Class : public class clsCustStandObj  {     public PageReference checkAll1() {         return null;     }     public PageReference checkAll2() {         return null;     }     public string SelectedValue{get;set;}     public string SelectedObject{get;set;}     public List<SelectOption> lstofObj{get;set;}     public List<SelectOption> lstofAllselectedObj{get;set;}     public List<string> lstofAllfieldAndName{get;set;}     public List<WrapperClass> lstofStandardField{get;set;}     public List<WrapperClass> lstofCustomField{get;set;}     public List<string> lstofselectedfield{get;set;}     public string allselfield{get;set;}     public List<SObject> lstgetresult{get;set;}     public List<String> lstgetresult1{get;set;}