• sharathchandra thukkani
  • 917 Points
  • Member since 2014

  • Chatter
  • 27
    Best Answers
  • 1
    Likes Received
  • 26
    Likes Given
  • 7
  • 275
  I am creating a custom button. On this custom button i want calender. Means suppose I want to create events for september 2016 then i will get rows of days in september 2016. If i want create events for october 2016 then i will get rows of days in oct 2016. How is this possible?egards,
Hi All,
I am getting "Unknown property 'VisualforceArrayList.Name" error while trying to create a Visualforce email template on custom object Status__c.
I have narrowed down the line that is actually giving me the error which is:

I do not get this error when I change the line to display the ID instead of Name:

I have checked my relationship name is correct and cant figure out why it wont traverse to the related object.

Any help will be really appreciated.

Thank you!
<messaging:emailTemplate subject="{!relatedTo.Name} {!$Label.Incident_Submit_For_Approval}" 
<messaging:htmlEmailBody >        
            <p>Hi {!relatedTo.Owner.Name},</p>
            <p>{!$Label.Incident_Submit_Approval_Request} {!relatedTo.Name}.</p>
            <p>{!relatedTo.Name} details :</p>
            <table cellspacing="0" cellpadding="0">
                <tr style="height: 21px;">
                    <td style="width: 130px;text-align: right;">Name</td>
                    <td style="padding-left: 10px;">{!relatedTo.Name}</td>
                 <tr style="height: 21px;">
                    <td style="width: 130px;text-align: right;">Demand vs Supply</td>
                    <td style="padding-left: 10px;">{!relatedTo.Demand_Vs_Supply_Master__r.Name}</td>
            <p>You can either approve or reject by typing APPROVE or REJECT in the first line and adding comments in the second line in reply to this email.</p>
            <br/>Thank You,
            <!--<br/>{!relatedTo.Demand_Vs_Supply_Master__r.Supplier_Site__r.Site__r.Company__r.Name}.<br/>          -->

Hello Community, I have written this trigger to update County field for a particualr postcode, I am getting a NULLPOINTER Exception, please help
trigger TriggerUpdateContact on Contact(before insert, before update) {

        RecursiveTriggerHandler.isFirstTime = false;

    // querying all the name and Zipcode from County object
    List<PostCodes__c> countyList = [select Id, PostCode__c, County__c from PostCodes__c];   
    Map<String,String > PostCodeMap = new Map<String,String>();       
    //populating the Map
    for(PostCodes__c p : countyList ){

    for (Contact c :Trigger.new){    
    string postcode2;
        if (c.MailingPostalCode.length() >= 8) {
                postcode2 = c.MailingPostalCode.substring(0,4);
        } else if (c.MailingPostalCode.length() >= 7)  {
                postcode2 = c.MailingPostalCode.substring(0,3);
        } else {
                postcode2 = c.MailingPostalCode.substring(0,2);
        if(c.MailingPostalCode!= null && PostCodeMap.containsKey(postcode2)) {
            c.County__c  = 'Unknown';
Hi all

I have an requirement that i want to send dirth day greating message every day to  customer who are having birth day on contact object or my custom object like customer__C

How i achive this requirement? Can i use time depended Workflow or write E-mail services using Apex class? Can we write it in trigger?

Thanks In Advance
Sampath Palli
How do I know current vfpage id in apex class?
Hey guys I'm new to salesforce and I've to update all phone numbers on contact when account phone number changes, how can I do this with trigger? please help.
Hi.  I have my entitlements automatically getting attached to cases with an apex trigger.  Each milestone (depending on priority and a checkbox) have different business hours.  When I create a case, the default business hours are getting added instead.  How do I fix this in the trigger?
trigger CW_DefaultEntitlement on Case (Before Insert, Before Update) {
    List<Id> acctIds = new List<Id>();
    for(Case c: Trigger.new){
        List <Entitlement> entls = [Select e.StartDate, e.Id, e.EndDate, e.AccountId From Entitlement e
                Where e.AccountId in :acctIds And e.EndDate >= Today And e.StartDate <= Today];
            for(Case c : Trigger.new){
                if(c.EntitlementId == null && c.AccountId != null){
                    for(Entitlement e:entls){
                            c.EntitlementId = e.Id;

  • July 11, 2016
  • Like
  • 0
Hi All,

I have created a Formula Field with return type as 'Date' and have set the value as Today().To store the value of the date i create the record on.But i observe that when i create a record on current date it is auto updating the previously created record with current date/todays date instead of retaining yesterdays date for it/or the date on which it was created.

Thanks for Any Help in Advance...!!
I have custom object with 10 fields. I want all fields and creation date in report. I am able to see creation date ( only date) and created by( user name) but my requirement is to add creation time also in terms of hours. How i can do that? in report type i am able to see created date field which is printing only date. Could you help me?
Hi Everyone,
//Component: LightningNavigate
<aura:component implements="force:appHostable">
    <div id="aura-page">
        <div class="container">
            <ui:button label="gotoURL" press="{!c.gotoURL}" />
        <div class="container">
            <ui:button label="navigate" press="{!c.navigate}" />

    gotoURL : function(component, event, helper) {
    navigate : function(component, event, helper) {

    gotoURL : function (component, event) {
        var urlEvent = $A.get("e.force:navigateToURL");
          "url": "/006/o"
    navigate : function(component,event) {
        var address = '/Salesforce.com+Inc/@37.793779,-122.39448,17z/';
        var urlEvent = $A.get("e.force:navigateToURL");
          "url": 'https://www.google.com/maps/place/' + address

<aura:application >
    <c:LightningNavigate />

While running above code, I am getting following issue:

Something has gone wrong. Action failed: c$LightningNavigate$controller$gotoURL [TypeError: Cannot read property 'setParams' of undefined] Failing descriptor: {c$LightningNavigate$controller$gotoURL}. Please try again.

Can someone please help me to resolve it?

Hi All,
Our Salesforce application uses web service callout to intergrate to a partner's system (non-salesforce).
The partner is asking if it is OK to enable TLS 1.1/1.2 on their firewal.
I refered to this document https://help.salesforce.com/apex/HTViewSolution?id=000221207
Browser supports TLS 1.1/1.2.
My questions are:
1. from code wise, do we need to make any change?
2. Do I need to enabled TLS in my Salesforce org?
3. We have other partners not using TLS 1.1/1.2. Will the same code work for both?

This is the code snippet:
HttpRequest req = new HttpRequest();
        String end_point = host+(port!=NULL?+(':'+port):'')+url_path+url_params+starter;

        try {
            Http http = new Http();
            HTTPResponse res;
            res = http.send(req);

            final_url = 'Success';
            //update integration;
        } catch(Exception e) {
            final_url = 'Error: ' + e.getMessage();


Hi there.
Working on my first trigger. The trigger works, and I can get 80% code coverage with the test class below. However, when I try to bring it into production it fails.
trigger attachToAccount on Task (before update) {
  // Get Lead Ids from all of the triggered Tasks
  set<id> leadIds = new set<id>();
  for(Task myTask :trigger.new) {

  // Get Leads and build a map of <LeadId,Lead_Accounts__c>
  map<id,id> mLeadAccountIds = new map<id,id>();
  list<Lead> leads = [SELECT id, Lead_Accounts__c FROM Lead WHERE Id IN :leadIds];
  for(Lead l :leads) {

  // Update triggered tasks with Account Id
  for(Task t :trigger.new) {
    if(mLeadAccountIds.containsKey(t.whoId)) {
      t.whatId = mLeadAccountIds.get(t.whoId);


My test class gives me 80% code coverage, but when I send everything through a change set the class fails with an INVALID_CROSS_REFERENCE_KEY Exception. My hunch is that this is because the lead IDs I use in WhoId are to leads that exist in sandbox, but not production. 

How would I write this in a way that it works when I deploy?
public class ActivityCountTest_Test
      public static testmethod void testinsert()

Task task= new task();
task.Subject='Message Sent 1';
insert task;

Task task1= new task();
insert task1;

Task task2= new task();
task2.Subject='Message Sent 3';
insert task2;

task.Subject = 'Closed';

task1.Subject = 'Closed';

task2.Subject = 'Closed';



I have one object that has country and language and other fields.  I have another object that has country, language and the Language Code whch is specific to the country and language combination.  How do I create a lookup relationship and use that field in a formula field in the first object?
In the before insert context, the IDs are not yet assigned to the list. In such scenario, If I need to create a map to uniquely access each record. What is the best way. Cannot depend on the field values.
Hi All,

I have a visualforce page which displays thumbnails of the attached images to that record. I put up checkboxes under each thumbnail to select the ones the user wants to delete, and have a remove button at the bottom. I want to pass the parameters of the selected checkboxes into the controller and delete only the selected ones. How can I achieve this ?

Any help is much appreciated. Thanks
If i create a List view in desktop version with admin profile , i want to see the list view in my Ipad in salesforce1 version where i am using portal licenses .... can you please help here
Could anybody help me with a formula field? Namely how I can use formula to choose the latest date for example:

DateA__c = 09/09/2013
DateB__c = 11/10/2014
DateC__c = 01/01/2010

Thanks in advance
Hi all,

Wish you a happy new year...

On case, I've 2 lookups. One on Product and another one on Asset. I want to add a lookup filter on Product lookup, so that I could see only those Products which have the same Group as Product family of selected Asset.

But, I'm not able to get Product family of Asset, while putting the criteria.

Can anyone help me to achive this?

Thanks in advance...
  • January 02, 2015
  • Like
  • 1
Hello Guys,

I have a string variable for example:

String str = 'Priority==\'xyz\' && Isescalated==true';
I want to execute the above statement in apex by replacing the Priority and Isescalated with record values.

I tried to use tooling API in triggers but i get exception cannot call future method from future. (I solved it by using stopping the recursion) but the record takes some time to reflect the changed owner.

Also i want to know what is the best way to do this. I cant use existing assignment rules as we can have more than 3000 rules setup and we also have to customize the assignment rules to use weightage.

Any suggestions?
I get response as System.HttpResponse[Status=Forbidden, StatusCode=403] when i Quick start with eienstien vision trail
What kind of phone format does salesforce suggest for the international numbers? Do anyone have idea on this.
Hello Everyone,

I have custom vf page in the interaction log of the console as a console component on the specific page layout which is assigned to the record type.

When i save the case in the console the record type will change to the record type to which i have the custom interaction log and the interaction log is not appearning. But if i close the case from the console and reopen then i'm able to see the log.

Could you please help me how can i see the CLI as soon as i save the record.

Thank You,

when should i use System.Integer.valueOf and Integer.valueOf salesforce

Seems like both are same but i want to know what is the difference.

Below is my sample code where i'm inserting the error occured for DML operation into SFDC_Log__c object. Can i capture the Stack Trace by using substring and index concept over here, have any one tried. It will also be helpful if any once can post the exact error message how it looks.

 //log bad Inserts
                        Database.Error err =  objResult.getErrors()[0];
                        objSfdcLog = new SFDC_Log__c();
                        objSfdcLog.Error_Message__c = err.getMessage().substring(0,255);
                        objSfdcLog.ToAddress__c = strToAddress;
                        objSfdcLog.FromAddress__c = strFromAddress;
                        System.Debug('######## Error while inserting Case: '+err.getStatusCode()+' '+err.getMessage());
Not able to see Login button for all users on user detail page even if i'm an administrator in developer account. My "System administartor" profile has "Mange Users" and "Modify All Data" permission.
Hello Guys,

I have a string variable for example:

String str = 'Priority==\'xyz\' && Isescalated==true';
I want to execute the above statement in apex by replacing the Priority and Isescalated with record values.

I tried to use tooling API in triggers but i get exception cannot call future method from future. (I solved it by using stopping the recursion) but the record takes some time to reflect the changed owner.

Also i want to know what is the best way to do this. I cant use existing assignment rules as we can have more than 3000 rules setup and we also have to customize the assignment rules to use weightage.

Any suggestions?
Hi Everyone 

We would like to add emails from Saleforce for example alert@mail.salesforce.comnoreply@salesforce.com , noreply@mail.salesforce.com in our Company whitelist because some of Salesforce emails go to spam box.
So can anyone get me a List of all email addresses from Salesforce Email Servers?  

Nutthawan P. 
I found out that  Salesforce Shield is not a full-disc-encryption. Only selected data is stored encrypted at REST in the Salesforce database. I would like to know what fields  or data are guaranteed to be stored encrypted at RES in the db. What happen to those that are encrypted but not selected? It will not be encrypted?
How to list new articles in the Community page without performing search on it?

I have a field called 'Main Contact,' which is a lookup relationship on my Account object. I am trying to query the Main Contact's email, full name, and phone number, from a button on the Contract object, (custom Conga object.) I've come at this a bunch of different ways, but can't seem to get the data to pull. Here's what I have at the moment: SELECT Main_Contact__r.Email, Main_Contact__r.Name, Main_Contact__r.Phone FROM Account WHERE Id = '{pv0}' Any guidance would be much appreciated! Thank you!  
I get response as System.HttpResponse[Status=Forbidden, StatusCode=403] when i Quick start with eienstien vision trail
global class Batch_SMSInjection implements Database.Batchable<sObject>, Database.AllowsCallouts{    
    // Start method of batch class
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String str_CommunicationType = 'SMS';
        String query = 'SELECT Id, Activate__c, Business_Rule__c, Comminication_Template__c, Communication_Type__c, Comminication_Template__r.Template_Name__c,Patient__r.Person__r.Contact__r.MobilePhone,'+
                        +' Day__c, Frequency__c, Hours__c, Patient__c, Patient__r.Person__c, Patient__r.Person__r.Contact__c, Patient__r.Person__r.Current_Timezone__c, Scheduled_Date__c, Time__c'+
                        +' FROM Communication_Scheduled__c'+
                        +' WHERE Activate__c = true AND Communication_Type__c =:str_CommunicationType AND Patient__r.SMS_Opt__c = true';
        return Database.getQueryLocator(query);
    global void execute(Database.BatchableContext BC, List<Communication_Scheduled__c> scope) {
        Map<Id, Communication_History__c> mapIdToSMSHistory = new Map<Id, Communication_History__c>();
        // creating map for all the communication history
        for(Communication_History__c history: [SELECT Id, CreatedDate, Patient__c, Communication__c, Communication_Template__c 
                                                    FROM Communication_History__c 
                                                    WHERE Communication__c IN :scope 
                                                    ORDER BY CreatedDate ASC]){
        List<Communication_History__c> lstSMSHistoryInsert = new List<Communication_History__c>();
        Map<String, List<String>> map_TemplateNameSetOfContactId = new Map<String, List<String>>(); 
        Set<Id> set_ContactId = new Set<Id>();
        Map<Id, Contact> map_ContactIdAndRecord;
        List<Communication_Scheduled__c> list_CommScheduleToUpdate = new List<Communication_Scheduled__c>();
        // Iterating all the communication scheduled
        for(Communication_Scheduled__c smsSchedule : scope){
            DateTime datetime_Accr_UserTimezone;
                datetime_Accr_UserTimezone = Utility.convertTimeAccrTimeZone(smsSchedule.Patient__r.Person__r.Current_Timezone__c);
                datetime_Accr_UserTimezone = System.now();
             // calculating the weekday of the current date And current time for a patient respective to timezone.    
            String currentTime = String.valueOf(datetime_Accr_UserTimezone.hour());          
            String communicationTime = '12';
            if(smsSchedule.Time__c.indexOf(':') != -1){
                communicationTime = smsSchedule.Time__c.subString(0, smsSchedule.Time__c.indexOf(':'));
            }else if(smsSchedule.Time__c != '') {
                communicationTime =  smsSchedule.Time__c;
            // checking for the communication matching criteria
            Boolean isCommSend = false;
            if(smsSchedule.Frequency__c == 'Daily'){
                if((!mapIdToSMSHistory.containsKey(smsSchedule.Id) && communicationTime == currentTime)
                        ||( mapIdToSMSHistory.containsKey(smsSchedule.Id) && datetime_Accr_UserTimezone.dateGmt() != mapIdToSMSHistory.get(smsSchedule.Id).CreatedDate.date())) {
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
            else if(smsSchedule.Frequency__c == 'Monthly'){
                if((!mapIdToSMSHistory.containsKey(smsSchedule.Id) && communicationTime == currentTime && Integer.valueOf(smsSchedule.Day__c) == datetime_Accr_UserTimezone.dayGmt())
                            || mapIdToSMSHistory.containsKey(smsSchedule.Id) && mapIdToSMSHistory.get(smsSchedule.Id).CreatedDate.Day() != datetime_Accr_UserTimezone.dayGmt()){
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
            else if(smsSchedule.Frequency__c == 'Other' || String.isEmpty(smsSchedule.Frequency__c)){
                if(smsSchedule.Scheduled_Date__c == datetime_Accr_UserTimezone.dateGmt() && communicationTime == currentTime){
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                    smsSchedule.Activate__c = false;
            // creating map of sms template and list of Person id
            if(isCommSend && !String.isEmpty(smsSchedule.Comminication_Template__r.Template_Name__c)){
                    map_TemplateNameSetOfContactId.put(smsSchedule.Comminication_Template__r.Template_Name__c, new List<String>());
        if(set_ContactId.size() > 0){
             // This list is having all email instances which will be send out
            List<smagicinteract__smsMagic__c> list_SMSToBeSend = new List<smagicinteract__smsMagic__c>();
            // SMS instances are created for a respective sms template
            for(smagicinteract__SMS_Template__c smsTemplate : [SELECT Id, smagicinteract__Text__c FROM smagicinteract__SMS_Template__c WHERE smagicinteract__Name__c IN :map_TemplateNameSetOfContactId.keySet()]){
                //smagicinteract.TemplateResolver temp = new smagicinteract.TemplateResolver();
                String  templateText = smsTemplate.smagicinteract__Text__c;             
                String senderId = 'smsMagic';
                for(String personMob : map_TemplateNameSetOfContactId.get(smsTemplate.smagicinteract__Name__c)){  
                    smagicinteract__smsMagic__c smsObject = new smagicinteract__smsMagic__c();
                    smsObject.smagicinteract__SenderId__c = senderId;
                    smsObject.smagicinteract__PhoneNumber__c = personMob ;
                    smsObject.smagicinteract__ObjectType__c = 'Person__c';
                    smsObject.smagicinteract__disableSMSOnTrigger__c = 1;
                    smsObject.smagicinteract__external_field__c = smagicinteract.ApexAPI.generateUniqueKey();
                    smsObject.smagicinteract__SMSText__c = templateText;
            // Communications are send out and history created for each communication,.
            if(list_SMSToBeSend.size() > 0){
                String response = smagicinteract.ApexAPI.pushSMSCallout(list_SMSToBeSend);
                system.debug('@@@response  <> :' + response );
                Database.insert (list_SMSToBeSend, false);      
                insert lstSMSHistoryInsert;
            if(list_CommScheduleToUpdate.size() > 0){
                Database.update(list_CommScheduleToUpdate, false);
    global void finish(Database.BatchableContext BC) {
        // Do nothing
    // this method is used to create communication history.
    public Communication_History__c createCommHistory(String patientId, String commScheduleId){
        Communication_History__c commHistory = new Communication_History__c();
        commHistory.Patient__c = patientId;
        commHistory.Communication__c = commScheduleId;
        return commHistory;
i need u r  help.....
as u have shown code for above link for  parent to child when we will select  for the parent to child
bt i need the select for all  where i check the check  all accounts should be selected and all contacts child should be shown in vf page....?
please let me get the code pleasee..
currently we are running via manual clicking on the batches. could you please suggest an option to automate apttus job.

these are the apttus batch jobs update.
Has anyone had experience with implementing the message durability functionality with the new version 37 in java? I'm trying to figure out how to implement the replay functionality but there is not any java code examples and only javascript examples
  I am creating a custom button. On this custom button i want calender. Means suppose I want to create events for september 2016 then i will get rows of days in september 2016. If i want create events for october 2016 then i will get rows of days in oct 2016. How is this possible?egards,

Hi every one,
I need to create an interface to integrate a serie of Account’ data and Product’s data between Salesforce CRM and one management system.
I would predict 2 bidirectional flow that allow me to align the information from one system to another. For example: I could create a new Account in my management system and replicate a sub set of its data in the Salesforce CRM and viceversa, all in real time.
I think the use of WSs are as indicated.  
Do someone developed such integration? It could give me some useful tip to approach correctly the topic?

Hello Everyone,

I have custom vf page in the interaction log of the console as a console component on the specific page layout which is assigned to the record type.

When i save the case in the console the record type will change to the record type to which i have the custom interaction log and the interaction log is not appearning. But if i close the case from the console and reopen then i'm able to see the log.

Could you please help me how can i see the CLI as soon as i save the record.

Thank You,

User-added image
Hi all
am working on this page where i want, when i click on the account tab my data will be shown in the related list section and when i select that account from related list that account will be editable below the account tab and i want same for payment tab also please help am completly stuck in this problem . please shARE SOME releated examples to this .


I have created a console app in my development enviroment to learn more about omnichannel. I need to take some action when an agent accepts a case. I am able to see cases (assigned to my queue) popping up on the omnichannel widget with the accept link so the routing part is working.

I next created a visualforce page with the following code:
(After going through the salesforce integration toolkit)

<apex:page >
<script type="text/javascript">
    var showAlert = function (result) { alert("Accepted with result message " + result.message); }
    window.onLoad = function() {  sforce.console.addEventListener(sforce.console.ConsoleEvent.PRESENCE.WORK_ACCEPTED, showAlert); }


But when I accept a case by clicking accept, nothing happens. I am clearly doing it wrong.

How can I  "catch" the omnichannel accept action ?

I am new to both salesforce dev and javascript, any suggestions regarding the right course of action would be helpful.



I created a couple of javascript functions for managing the number
of open tabs inside the service cloud console. I am using addEventListener
for the OPEN_TAB and CLOSE_TAB console events to trigger these functions.

I was also assuming clicking the "+" button for explicitly opening a new tab as well
as closing it would also trigger my functions. The function associated with the
OPEN_TAB was NOT triggered, but the function associated with the CLOSE_TAB
DID get triggered. Not sure why.

I am using the integration.js library, version 30. I tried 31, but it wasn't working
for some reason.

Any help would be appreciated. Thanks, Chris
Hello there!!

I have a custom object named "CustomObject" I have created its fields and relationships and set its layout. I want to call REST webservice before inserting the object depending on the webservice response so can I override the default submit mechanism ???
Hi all,

I am trying to login into Salesforce Customer Community using Facebook as Auth Provider. 

Issue faced: I am able to sign in to Salesforce community using facebook authentication, however I am not able to fetch the facebook user details such as firstname,lastname,email dynamically using the Registration Handler Class by  using data.firstname,data.lastname,data.email . Currently i am using static values for the fields like firstname,lastname,email 

Expected : Getting dynamic values from facebook in the code below where static values are provided.

Code for Registration Handler that i am using as below.

global class FacebookHandler implements Auth.RegistrationHandler{ 
    global User createUser(Id portalId, Auth.UserData data){
    system.debug('hahahahaha' +portalId);
      User result;
      try {
        //default account to collect Community Members
        Account a = [ SELECT Id
                      FROM Account
                      WHERE name='MyAllergy'
                      LIMIT 1
       //default profile
      Profile p = [ SELECT Id
                     FROM Profile
                    WHERE name='Custom Customer Community Plus Login User'
                     LIMIT 1
       Contact c   = new Contact(
        accountId = a.Id,
         email     = 'prateek.sharma@salesforce.com',
         firstName = data.firstName,
         lastName = data.lastname

     //    lastName  = 'testr'
       insert c;
      //get the alias as username
      String alias = this.getAlias(data.username);
       User u = new User(
         username          = alias + '@community.com',                                    
         email             = 'prateek.sharma@salesforce.com',
        lastName          = 'testtr',
         firstName         = data.firstName,
        alias             = alias,
         languagelocalekey = 'en_US',
         localesidkey      = 'en_GB',
         emailEncodingKey  = 'UTF-8',
         timeZoneSidKey    = 'GMT',
        profileId         = p.Id,
         contactId         = c.Id
       result = u;
     catch(Exception pEx) {
      //re-throwing exception to allow tracing the error from URL
      throw new HandlerException(
    return result;           
   //custom exception
   global class HandlerException extends Exception{}
   global void updateUser(Id userId, Id portalId, Auth.UserData data){
        User u = new User(
       id        = userId,
      email     = 'prateek.sharma@salesforce.com',
       lastName  = 'tata',
     firstName = data.firstName,
     alias     = this.getAlias(data.username)
     update u;
   global String getAlias(String pUsername) {
     //generate random string (8)
     Blob blobKey           = crypto.generateAesKey(128);
     String key             = EncodingUtil.convertToHex(blobKey);
     String random_username = key.substring(0,8);
     //if not defined, create a random one
     String alias = pUsername != null ?
                     pUsername :
     //check alias.length() > 8 and chop it
     alias = alias.length() > 8 ?
               alias.substring(0,8) :
     return alias;

Any help would be appreciated,

I am trying to connect Cognos with SalesForce and started creating the Salesforce datasource.

I am getting error while testing the connection , error being below:
XQE-GEN-0002 An unexpected exception occurred: Connecting "<username>@<domain>.com@//https://www.salesforce.com/services/Soap/u/20.0" failed. Error message "org.apache.axis2.AxisFault: peer not authenticated".

I found out that our cognos server is in a secured network and not all ports are opened.

I checked on whats available on internet and found below:
which says:
80: This port only accepts HTTP connections.
443: This port only accepts HTTPS connections.
1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.

I need to know 
1. which ports should I get opened for connecting to Salesforce from Cognos is it 443?
3. List of SalesForce servers (referred https://help.salesforce.com/apex/HTViewSolution?id=000003652)

Hi All,

I'm getting Cross site Scripting (XSS) attack for the line strIdeaId = ApexPages.currentPage().getParameters().get('id'); Below is my code snippet. Please suggest me how to overcome this problem.
public  with sharing class TestController {
     String strIdeaId;
 public TestController () {
  strIdeaId = ApexPages.currentPage().getParameters().get('id');

Hello guys, I'm having trouble creating a case via live agent. Follows the code I am using. If anyone can help, thank you.
<input type="hidden" name="liveagent.prechat:caseOrigin" value="Chat" /> 
<input type="hidden" name="liveagent.prechat.findorcreate.map:Case" value="Origin,caseOrigin;" /> 
<input type="hidden" name="liveagent.prechat.findorcreate.map.doCreate:Case" value="Origin,true" /> 
<input type="hidden" name="liveagent.prechat.findorcreate.saveToTranscript:Case" value="Case" /> 
<input type="hidden" name="liveagent.prechat.findorcreate.showOnCreate:Case" value="true" /> 
<!-- Link the Contact to the Case -->
<input type= "hidden" name="liveagent.prechat.findorcreate.linkToEntity:Account" value="Case,AccountId" />
Does the REST API support the capability to initiate an SMS message with the message text provided as a parameter to the API call rather than having been pre-defined on "Exacttarget"?
Can data extensions be used to personalize SMS texts sent by triggered sends with the REST API?
any help would be appretiated.
When I first started developing a year ago (and I forget which version I was using at the time), I seem to recall that I'd get a warning if the server code was newer than the copy I was working with. This is no longer happening.  We have multiple developers working in our sandbox and recently discovered that when I save my apex code, VF pages, etc., the Force.com IDE is simply saving overtop of whatever is on the server without any warning that the server code changed since I last refreshed my local copy.

I upgraded my Force.com IDE to Winter'16 (v35) hoping it would resolve the issue, but it doesn't.

Please, there *has* to be a way to fix this! Even if I use the "Synchronize with server" to update my local copy, til I go through a dozen changes or so and then save the results to the server, someone else could've have already uploaded another change. If the IDE is going to go through a lengthy "Synchronize check against server" it should at least work properly.

At the moment, all I can figure to do is bring up a list of the classes/pages I'm about to upload and make sure I'm the last one to have updated them before I save to server. 
I have a custom object ToDoObj which has no fields ( I am using only the Name field from it) and I am trying to create a ToDo list type of functionality with this Object. Below is my code for Component and Controller:
<aura:component controller="ToDoController">
    <aura:attribute name="list" type="ToDoObj__c[]" />
    <aura:attribute name="listItem" type="ToDoObj__c" />
    <aura:handler name="init" action="{!c.myAction}" value="{!this}" />

   <div class="container">
    <form class="form-for-list">
      <div class="if-field-is-req">
        <div class="only-one-inputfield">
          <ui:inputText aura:id="todoitemfield" label="Enter ToDo Item  "
      <ui:button label="Add To List" 
<div class="msg">
              <div id="list" class="row">
                 <aura:iteration items="{!v.list}" var="item">
                     <ui:inputCheckbox value="" /><ui:outputText value="{!item.Name}"/>
 myAction : function(component, event, helper) {
    var action = component.get("c.getToDos");
    action.setCallback(this, function(data) {
    component.set("v.list", data.getReturnValue());

createToDo : function(component, event, helper) {
 var todoItemField = component.find("todoitemfield");
   console.log('field is'+todoItemField);
 var todoItem = todoItemField.get("v.value");   
    console.log('item is '+todoItem);
    if(!todoItem || 0 === todoItem.length){
        todoItem.set("v.errors", [{message:"Enter a value!"}]);
    else {
    todoItem.set("v.errors", null);
    var listItem = component.get("v.listItem");
    createtodo(component, listItem);
createtodo: function(component, listItem) {
this.upserttodo(component, listItem, function(a) {
    var list = component.get("v.list");
    component.set("v.list", list);
I tried to debug the same using console.log but I am getting null value for todoItem while todoItemField is being updated correctly in the variable (as far as I know - it comes as some value which is in some other format and doesnt show the actual fieldName or something). Can anyone tell me where I am going wrong in this!

Hi, I have a deployment where we are using the Live Agent REST API to broker the messages. Is it possible to execute a file transfer using the REST API?
We recently implemented Enterprise Territory Management in our organization. I have used the "OppTerrAssignDefaultLogicFilter" apex class to display the territory name in the opportunities. When the button "Run Opportunity Filter" is clicked, the apex class populates the territory name on the  opportunities . I am observing the following issues  with the Apex class:

- Even though the account has only single territory with the maximum priority, the associated opportunity doesn't get the territory assigned
-Under the same account one opportunity gets territory assigned whereas the other opportunity doesn't get territory assigned
- I have even tried to run this class for small group of records. Still not all the records get the territory assigned.

Note: We have only one Territory model active
In Lightning Experience, when I'm on a record and select "Activity", I get only "New Task" and "New Event".  How can I get Email and Log Call on there, like they're supposed to be? 
When I add a partner to an opportunity through the web UI and issue a query like this:
[select AccountFromId, AccountToId, Role, OpportunityId, ReversePartnerId from Partner where OpportunityId = :opportunityId]

Two records are found. One has the AccountFromId field referring to the opportunity's account and AccountToId referring to the partner account while the other one has AccountToId referring to the opportunity's account and AccountFromId referring to the partner account.

Both also have the ReversePartnerId field referring to one another; and, thus, form some kind of bidirectional relationship.

I have some APEX code that queries the Partner object to find which accounts are related to a certain opportunity. Hence, I need to write test cases that setup the right database environment before they run. I want to run them with @isTest(seeAllData=false), for they need to be deterministic and not affected by the state of the production database when I deploy them.

I tried the following:
Partner partner = new Partner();
partner.AccountToId = partnerAccountId;
partner.OpportunityId = opportunityId;
partner.IsPrimary = true;
partner.Role = PARTNER_ROLE; // A constant
insert partner;
I ran this from the @testSetup method, but only one record was inserted.

Then, I  tried to insert the reverse relationship record programmatically in many different ways, but Salesforce doesn't allow us to set AccountFromId and OpportunityId at the same time. In addition, the  ReversePartnerId field is not writable.

My conclusion so far is that it's impossible to create the bidirectional relationships in the same way that Salesforce does when we use the web UI.

There are no clear directions in the documentation on how to insert these objects, and this seems to be yet another pitfall in Salesforce's CRM platform.
Trailhead is great! The simple page layout itself really lends itself to doing the work on an iPad, but in my experience I can't tap to select answers on the Challenge.. so I can't us the iPad.

> Is iOS supported? Has anyone else tried?    ( I get the results I've described under Safari and Chrome, on iOS 8.4.1)
> If not, could we please fix it? This would be a boon to the many people taking Trailhead. 

I'm receiving an error on my visualforce page when I try save records.  It is happening on the subject field for Tasks.  When I checked the Task subject field, it is defined as a picklist, but even when I choose one of the predefined picklist values, I still receive an error.

Task Subject Error
public with sharing class AddTasksToCases {

    public Case[] caseList = null;
    public Task cftTask {get; set;}
    public AddTasksToCases(ApexPages.StandardSetController setCon) {       
        caseList = setCon.getSelected();
        //newTask = new Task();        

    public pageReference CreateTask(){
        Task[] newTasks = new Task[]{};
        for(Case c : caseList){
             Task tk = new Task(
             	 WhatId = c.Id, 
             	 OwnerId = cftTask.Owner.Id, 
             	 Subject = cftTask.Subject, 
             	 Role__c = cftTask.Role__c, 
                 ActivityDate = cftTask.ActivityDate,
                 Description = cftTask.Description,
                 Status = cftTask.Status,
                 Type = cftTask.Type);
            if(newTasks.size() >= 200){
                insert newTasks;
            insert newTasks;
        return new PageReference('/500');

Visualforce page
<apex:page showHeader="true" sidebar="true" standardController="Case" recordSetVar="cases" extensions="AddTasksToCases">
    <apex:sectionHeader title="Cases" subtitle="Mass Task Create" />
    <apex:form >
        <apex:pageBlock title="CFT Task">
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="Add Tasks" action="{!CreateTask}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
           <apex:pageBlockSection columns="2" title="Assignee Information">
               <apex:inputField value="{!cftTask.OwnerId}"></apex:inputField>
               <apex:inputField value="{!cftTask.Role__c}"></apex:inputField>
               <apex:inputField value="{!cftTask.Type}"></apex:inputField>
               <apex:inputField value="{!cftTask.ActivityDate}"></apex:inputField>
           <apex:pageBlockSection columns="1" title="Task Description">
               <apex:inputField value="{!cftTask.Status}"></apex:inputField>
               <apex:inputField value="{!cftTask.Subject}"></apex:inputField>
               <apex:inputField value="{!cftTask.Description}"></apex:inputField>

Hi everybody,

I have a mobile application Salesforce, in the user details's page, there is an SMS boutton, when I click on, I have to choose a template (Text body) and click Send .
The button have to send me to my mobile' SMS section with the choosed the template.
I'm stuck in the last step . How can i get from a mobile salesforce to SMS section ?

It works great with email and seletion templates too. So I just changed some paramettres as [Email = account.PersonEmail ;] by [Email = account.PersonMobilePhone ;]

VF page IC_GenerateSMS

<apex:page showHeader="false" docType="html-5.0" standardStylesheets="false" cache="false" Controller="IC_GenerateSMS_VFCx">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

<link rel="stylesheet" href="{!URLFOR($Resource.JQuery_120, 'jquery.mobile-1.2.0.min.css')}" />
<apex:includeScript value="{!URLFOR($Resource.JQuery_120, 'jquery-1.8.2.min.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.JQuery_120, 'jquery.mobile-1.2.0.min.js')}"/>   

<!-- New Relic integration -->
<apex:includeScript value="{!IF($Setup.ICONSettings__c.NewRelic__c, $Resource.NewRelic, '')}"/>

    $j = jQuery.noConflict();
    var backUrl = '/apex/IC_ClientDetails?id={!accountId}';
    function logTask(subject) {
        console.log('Selected Template ' + subject);
                                          function(records, e) {console.log(records);}, {escape:true});
    function createMail(){
        var email = document.getElementById("Email").innerHTML;
        var subject = encodeURIComponent(document.getElementById("initSubject").innerHTML);
        var body = encodeURIComponent(document.getElementById("initBody").innerHTML);
        window.location = "mailto:"+email+"?subject="+subject+"&body="+body;
    <div data-role="page" data-theme="a" id="mainpage" data-fullscreen="true" data-add-back-btn="true">
        <!-- HEADER -->
        <div data-role="header">
            <a href="#" onclick="window.location.href=backUrl;" data-icon='arrow-l' style="box-shadow: none;" data-iconshadow="false" data-iconpos="notext"></a>
        <!-- CONTENT -->
    <div data-role="content" data-fullscreen="true">   
       <ul data-role="listview" data-theme="a"  data-inset="true" >
            <!-- SMS TEMPLATE SELECTION FORM -->
            <apex:form >
             <!-- SMS TEMPLATE SELECTION LIST -->
             <div data-role="fieldcontain">
                <label for="selectedTemplate">{!$Label.IC_SelectTemplate}</label>   
                <apex:selectList value="{!selectedTemplate}"  size="1" id="selectedTemplate">
                    <apex:selectOptions value="{!templateOptions}"/>
                    <apex:actionSupport event="onchange" action="{!previewTemplate}" rerender="counter"/>
                <!-- SMS TEMPLATE SELECTION PREVIEW -->
                <apex:outputpanel id="counter">
                    <!-- SMS TEMPLATE ENCODED FOR BROWSER PREVIEW -->          
                    <!-- <div id="Email">{!Email}</div>  -->
                    <div id="Subject"></div>
                    <div id="Body"></div>
                    <div id="initSubject" style="display:none;visbility:hidden;">{!initSubject}</div> 
                    <div id="initBody" style="display:none;visbility:hidden;">{!initBody}</div> 
                        document.getElementById("Subject").innerHTML = "{!Subject}";
                        document.getElementById("Body").innerHTML = "{!Body}";
            <a data-role="button" data-direction="reverse" data-transition="none" href="javascript:createMail();" data-icon="false" data-iconpos="left">

IC_GenerateSMS_VFCx Controller

public with sharing class IC_GenerateSMS_VFCx {
 /** Variable declarations **/
    public String accountId{get;set;}
    public String ownerId;
    private Account account;
    private User owner;
    private User Sender;
    //public String SMS{get;set;}
    public String Email{get;set;}
    public String Subject{get;set;}
    public String initBody{get;set;}
    public String initSubject{get;set;}
    public String Body{get;set;}
    private List<EmailTemplate> emailtemplates;
    private List<SelectOption> tempList = new List<SelectOption>();
    private EmailTemplate emailTemplate;
    public string selectedTemplate{get;set;}
    public IC_GenerateSMS_VFCx() {
        /** Retrieve sms templates dedicated to mobile device **/
        List<Folder> Folders = [Select Id, Name From Folder Where Type = 'Email' AND DeveloperName like  '%Mobile'];
        emailtemplates = [select Id,Name,Subject,body,IsActive from EmailTemplate Where Folder.Id IN :Folders AND IsActive = true  Order By Folder.Name, Name Limit 1 ];
        tempList.add(new SelectOption('NONE', '----- ' + Label.IC_None +' -----'));
        for (EmailTemplate emailTemp : emailtemplates) {
            tempList.add(new SelectOption(emailTemp.id, emailTemp.Name));
        /** Retrieve current account and owner information **/
        accountId = ApexPages.currentPage().getParameters().get('id');
        //account = [select id, Salutation, FirstName, LastName, PersonEmail, OwnerId from Account where id =: accountId];
        account = IC_Factory.getAccountt(accountId);
        //Email = account.PersonEmail;
        Email = account.PersonMobilePhone;
        //owner = [select id, FirstName, LastName from User where id = :account.OwnerId];
        //Sender = [select id, defaultStore__c from User where id =: UserInfo.getUserId()];
        owner = IC_Factory.getUser(account.OwnerId);
        Sender = IC_Factory.getUser(userInfo.getUserId());
    /** Provide options for email template list **/
    public List<SelectOption> getTemplateOptions() {
        return tempList;
    /** Encode and provide email template content **/
    public PageReference previewTemplate(){
        if(selectedTemplate <> 'NONE'){
            emailTemplate = [select Id,Name,Subject,Body from EmailTemplate where Id =: selectedTemplate LIMIT 1];
            Subject = renderMergeFieldsAndReplaceEncoding(emailTemplate.Subject);
            Body = renderMergeFieldsAndReplaceEncoding(emailTemplate.Body);
            initSubject = renderMergeFields(emailTemplate.Subject);
            initBody = renderMergeFields(emailTemplate.Body);
            Subject = '';
            Body = '';
            initSubject = '';
            initBody = '';
        return null;
    private String nullToText(String value) {
        return (value == null?'':value);
    private String nullToText_Title(String value) {
        return IC_UTILS.getTranslationPicklistValue('Contact', 'Salutation', value);
    private String nullToText_Salutation(String value) {
        return IC_UTILS.getTranslationPicklistValue('Contact', 'Salutation', value);
    /** Replace dynamic fields by value **/
    private String renderMergeFields(String textToRender) {
        textToRender = textToRender.replace('{!Contact.Salutation}', account.Title__pc == null ? nullToText_Salutation(account.Salutation):nullToText_Title(account.Title__pc) );
        textToRender = textToRender.replace('{!Contact.FirstName}',  nullToText(account.FirstName));
        textToRender = textToRender.replace('{!Contact.LastName}',  nullToText(account.LastName));
        textToRender = textToRender.replace('{!Contact.OwnerFirstName}',  nullToText(owner.FirstName));
        textToRender = textToRender.replace('{!Contact.OwnerLastName}',  nullToText(owner.LastName));
        textToRender = textToRender.replace('{!User.FirstName}',  nullToText(UserInfo.getFirstName()));
        textToRender = textToRender.replace('{!User.LastName}',  nullToText(UserInfo.getLastName()));
        textToRender = textToRender.replace('{!User.DefaultStore__c}', nullToText(Sender.defaultStore__c));
        return textToRender;
    /** Replace dynamic fields by value and formate for brower display **/
    private String renderMergeFieldsAndReplaceEncoding(String textToRender) {
        textToRender = textToRender.replace('{!Contact.Salutation}', account.Salutation);
        textToRender = textToRender.replace('{!Contact.FirstName}', account.FirstName);
        textToRender = textToRender.replace('{!Contact.LastName}', account.LastName);
        textToRender = textToRender.replace('{!Contact.OwnerFirstName}', owner.FirstName);
        textToRender = textToRender.replace('{!Contact.OwnerLastName}', owner.LastName);
        textToRender = textToRender.replace('{!User.FirstName}', UserInfo.getFirstName());
        textToRender = textToRender.replace('{!User.LastName}', UserInfo.getLastName());
        textToRender = textToRender.replace('{!User.DefaultStore__c}', Sender.defaultStore__c);
        textToRender = renderMergeFields(textToRender);    
        textToRender = textToRender.replace('\\n', '<br/>');
        return textToRender;
    * Create new Task for current user and selected client when user click on SMS or Mobile
    public static String createTask(String accountId, String numberPhone, String selectedTemplate) {
        system.debug ('*** createTask ');
        String tskSubject = Label.IC_SendEmail + ': ' + selectedTemplate; 
        String tskDescription =  String.format(Label.IC_TaskDescriptionEmail, new String[] {String.valueOf(Date.toDay()), UserInfo.getName(),  numberPhone, selectedTemplate });       
        Task newTask = IC_Factory.createTask(accountId, tskSubject, tskDescription, null, null, null, null, 'Email');
        newTask.TECH_is_AutoSave__c = true;
        return IC_Factory.insertTask(newTask);

Help Please !!
Hi all,

Wish you a happy new year...

On case, I've 2 lookups. One on Product and another one on Asset. I want to add a lookup filter on Product lookup, so that I could see only those Products which have the same Group as Product family of selected Asset.

But, I'm not able to get Product family of Asset, while putting the criteria.

Can anyone help me to achive this?

Thanks in advance...
  • January 02, 2015
  • Like
  • 1
While developing in Apex, I need to retrieve sandbox name in my code.  How do I do this in Apex?  Thanks in advance.
Hello, I am eagerly waiting for the rest of the modules to be updated. Any ideas when will the rest of the modules be updated like:
Apex Integration Services , Visualforce & JavaScript ..

Hi All,


Did anyone do SagePay Integration using apex? I want to implement it for my client. I got the document from SagePay. The request format is only given in the document. The way to do the encryption and sending the request are not provided over there.


Please help me out to complete this.





Hi all,


I am stuck in a problem. I want to create a visual force page in which I need to show all the addresses in account table on Google map. Currently I am able to show one address on google map by adding my visual force page into the standard account page. But now I need a separate standalone page showing only a google map and all the addresses (in account table) marked on this map.


Any help will be highly appreciated...

  • August 05, 2010
  • Like
  • 2