• Prakhar K
  • NEWBIE
  • 19 Points
  • Member since 2013
  • Developer

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 6
    Replies
Trying to deploy the Report chart component using SiteDotCom.com from the partner portal community but in the target org getting blank filters of each report.

The report filter after deployment is blank.
  1. ZipCode:94117
  2. ​Geolocaition of 94117: 37.7717185,-122.4438929
 
  1. ZipCode:94568
  2. Geolocaition of 94568: 37.7202463,-121.8676464

Distance between both ZipCodes is 1.6Miles Max

We have geoLocation stored in Salesforce custom object  XYZ,
when I am querying 

when searching all places within less than 5 miles of zipcode 94117 (37.7717185,-122.4438929)
SELECT Id, FROM XYZ WHERE Distance(XYZ_Location__c, GeoLocation(37.7717185,-122.4438929), 'mi') < 5
returns 2 records

while doing vice versa:
searching places withing 5 miles near zipcode 94568 (37.7202463,-121.8676464) 
SELECT Id FROM XYZ WHERE  Distance(XYZ_Location__c, GeoLocation(37.7202463,-121.8676464), 'mi') < 5
returns no rows. [Why this query is not returning result since there is a record having zipcode 94117  and 94568 ]

Has anyone faced this type of issue? 
 

Below code throws error saying: Getting error attempt dereference a  null pointer:

public class AccountHandler {
public class MyException extends Exception{}
public static Account insertNewAccount(String name) {
Account a = new Account();
try
{
    IF(name=='')
    {
    throw new MyException('Empty paramenter');
    }
    else
    {
    a.Name = name;
    insert a;
    return a;
    }
}
catch (DmlException e) {
return null;
}

}
}

what am I missing?
In Apex I am trying to count the number of days from first day of the current month excluding Sat and Sun.

            Date firstDayOfMonth = System.today().toStartOfMonth();
             Datetime dt1 = DateTime.newInstance(firstDayOfMonth, Time.newInstance(0, 0, 0, 0));
             String d=dt1.format('EEEE');
            
             if(d != 'Saturday' &&  d != 'Sunday')
              {
                Datetime et1 = DateTime.newInstance(Date.Today(), Time.newInstance(0, 0, 0, 0));
                String e=et1.format('EEEE');
                System.debug('After conversion present day======'+et1);
                 
                Integer noOfDaysFromFirstDyMonth=0; 
                while (dt1<= et1) {
                d=(String)dt1.format('EEEE');
                e=(String)et1.format('EEEE');  
                    if (d!='Saturday' || d!='Sunday')  {  
                    if (e!='Saturday' || e!='Sunday')
                        {
                            noOfDaysFromFirstDyMonth = noOfDaysFromFirstDyMonth + 1;  
                            System.debug('dt1=='+dt1.format('EEE'));
                            System.debug('et1=='+et1.format('EEE'));
                        }
                    }  
                    dt1= dt1.addDays(1);  
                } 
  
When the days are Sat or Sun ,it should not go inside if conditions but its going inside ifs.Where I am wrong please guide me?
 
I have made a picklist having dynamic values of picklist but I am unable to get the user selected value in controller.When user selects any of the values ,a function called "showTemplateText" fires up and here I want to get the user selected value. Below is the Component code and Controller code .

Component Code Snippet:

<aura:attribute name="templates" type="Message_Template__c[]" />   //object of type  Message_Template__c//
<select id="msg-template" name="msg.id" style="width:200px;"  onchange="{!c.showTemplateText}" class="form-control is-filled" aria-invalid="false">
                        <option>--Select Msg Template--</option>   
                        <aura:iteration items="{!v.templates}" var="templ" >
                           <ui:inputSelectOption text="{!templ.Name}" />       //it shows value in front end but did not send any value at back end.any ideas?//
                        </aura:iteration>
            </select>
      ----------------------------------------------------------------------------------
   
function showTemplateText in controller

showTemplateText: function(component, event, helper){
var variable=component.get("v.templates[1].Text_Template__c");    //but using this i get a specific value no matter what i select in picklist.
}

-------------------------------------
 
Hi All,
I am getting  an error while inserting record of OpportunitylineitemSchedule in test class for trigger and is unable to figure out the cause.Please help?  
error:
Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

Trigger
trigger trgUpdatePrdScheduleDate on OpportunityLineItem (after insert) {
   
    Set<Id> opids = new Set<Id>();
    
    for(OpportunityLineItem ol :trigger.New){
        opids.add(ol.Id);
    }
    
    list<OpportunityLineItemSchedule> lstScheduleToUpdate = new list<OpportunityLineItemSchedule>();
    map<id,OpportunityLineItemSchedule> mapScheduleDate = new map<id,OpportunityLineItemSchedule>();
    
    for(OpportunityLineItemSchedule opps:[Select id,Type,ScheduleDate,Revenue,
                                                 Quantity,OpportunityLineItemId from opportunityLineItemSchedule where 
                                                             OpportunityLineItemId IN:trigger.NewMap.KeySet()]){
        if(!mapScheduleDate.containsKey(opps.OpportunityLineItemId))
            mapScheduleDate.put(opps.OpportunityLineItemId,opps);   
    }
                                         
                                        
      for(OpportunityLineItem op : trigger.New){                                 
          If(op.Campaign_Start_Date__c != null && mapScheduleDate.containsKey(op.Id)){
             OpportunityLineItemSchedule opSchd1 = mapScheduleDate.get(op.Id);
             opSchd1.ScheduleDate = op.Campaign_Start_Date__c;
             lstScheduleToUpdate.add(opSchd1);
          }
      }
      
      if(lstScheduleToUpdate != null && lstScheduleToUpdate.size()>0)
          update lstScheduleToUpdate;
    
}
below is the code for my test class:
@isTest(SeeAllData=true)
private class TesttrgUpdatePrdScheduleDate {

    static testMethod void trgUpdateProductScheduleTest () {
        Test.startTest();
        User usr1 = [select id, Name, ProfileId  from User where Profile.Name = 'System Administrator' and isActive = true limit 1 ];
        System.runAs(usr1) { 
        Account acc = new Account();
        acc.Name = 'TestCompany1234';
        insert acc;
        System.assertEquals(acc.Name, 'TestCompany1234');

        Pricebook2 standardPB = [SELECT Id, Name FROM PriceBook2 Limit 1];
        
        Opportunity opp = new Opportunity();
        opp.Name = ' Testing123';
        opp.Pricebook2ID = standardPB.Id ;
        opp.AccountId = acc.Id;
        opp.StageName = 'Qualification';
        opp.CloseDate = date.parse('12/31/2012');
        opp.Start_Date__c = date.today();
        opp.Next_Steps__c = 'get steps';
        insert opp;
        System.assertEquals(opp.Pricebook2ID, standardPB.Id);
        System.assertEquals(opp.AccountId, acc.Id);
        
        Product2 p = new Product2();
        p.ProductCode = 'Test';
        p.Name = 'TestName';
        p.description ='testing product';
        p.isactive=true;
        insert p;
        System.assertEquals(p.isactive, true);
        
        PricebookEntry pe = new PricebookEntry();
        pe.Product2Id = p.Id;
        pe.Pricebook2Id = standardPB.Id;
        pe.UnitPrice = 1000;
        pe.IsActive = true;
        insert pe;
        System.assertEquals(pe.Product2Id, p.Id);
                
        OpportunityLineItem oli = new OpportunityLineItem();
        oli.OpportunityId = opp.Id;
        oli.PricebookEntryId = pe.Id;
        oli.Quantity = 1;
        oli.UnitPrice = 1000;
        insert oli;   
        
        update opp;
           System.assertEquals(oli.OpportunityId,opp.Id);
           System.assertEquals(oli.PricebookEntryId, pe.Id);
           system.debug('oli.OpportunityId----------'+oli.OpportunityId);
           system.debug('oli.PricebookEntryId----------'+oli.PricebookEntryId);
               
        
      /*  List<OpportunityLineItemSchedule> olie = new List <OpportunityLineItemSchedule>();
        olie = [select Quantity,ScheduleDate,OpportunityLineItemId from OpportunityLineItemSchedule
                          where OpportunityLineItemId =: oli.Id  limit 1 ];
        system.debug('##############'+olie);
      */
      
        OpportunityLineItemSchedule olis = new OpportunityLineItemSchedule();
        olis.OpportunityLineItemId = oli.id;
        system.debug('olis.OpportunityLineItemId++++++++++++'+oli.id);
        olis.quantity= 40;
        olis.revenue= 100.00;
        olis.type= 'Both';
        olis.ScheduleDate = Date.Today();
        insert olis;   
        
        System.assertEquals(olis.OpportunityLineItemId,oli.id);
        Test.stopTest();
    }
  }
}
------------------------------------------------------------------------------
 When I see the debug log i am getting the ids:

oli.OpportunityId----------006S0000008LaogIAC
oli.PricebookEntryId----------01uS0000006ftMEIAY
olis.OpportunityLineItemId++++++++++++00kS0000006FqA0IAK


 
after compiling and running sample app CONtaCT EXPLORER getting error as
Uncaught TypeError: Cannot call method 'query' of undefined at file:///android_asset/www/inline.js:
 in inline.js file
below is the code of inline.js


//Sample code for Hybrid REST Explorer


function init() {
     logToConsole("onLoad:jquery ready");
    document.addEventListener("deviceready",onDeviceReady,false);
                    }

function regLinkClickHandlers() {
alert("in inline.js");
  
    var $j = jQuery.noConflict();
    var logToConsole = cordova.require("salesforce/util/logger").logToConsole;
    $j('#link_fetch_device_contacts').click(function() {
                                           logToConsole("link_fetch_device_contacts clicked");
                                           var contactOptionsType = cordova.require("cordova/plugin/ContactFindOptions");
                                           var options = new contactOptionsType();
                                           options.filter = ""; // empty search string returns all contacts
                                           options.multiple = true;
                                           var fields = ["name"];
                                           var contactsObj = cordova.require("cordova/plugin/contacts");
                                           contactsObj.find(fields, onSuccessDevice, onErrorDevice, options);
                                           });
   
    $j('#link_fetch_sfdc_contacts').click(function() {
    alert("I am in inline alert");
    
                                         logToConsole("link_fetch_sfdc_contacts clicked");
                                         forcetkClient.query("SELECT Name FROM Contact", onSuccessSfdcContacts, onErrorSfdc);
                                         });
   
    $j('#link_fetch_sfdc_accounts').click(function() {
                                         logToConsole("link_fetch_sfdc_accounts clicked");
                                         forcetkClient.query("SELECT Name FROM Account", onSuccessSfdcAccounts, onErrorSfdc);
                                         });
   
    $j('#link_reset').click(function() {
                           logToConsole("link_reset clicked");
                           $j("#div_device_contact_list").html("")
                           $j("#div_sfdc_contact_list").html("")
                           $j("#div_sfdc_account_list").html("")
                           $j("#console").html("")
                           });
                          
    $j('#link_logout').click(function() {
             logToConsole("link_logout clicked");
             var sfOAuthPlugin = cordova.require("salesforce/plugin/oauth");
             sfOAuthPlugin.logout();
             });
}

function onSuccessDevice(contacts) {
    var $j = jQuery.noConflict();
    cordova.require("salesforce/util/logger").logToConsole("onSuccessDevice: received " + contacts.length + " contacts");
    $j("#div_device_contact_list").html("")
    var ul = $j('<ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a"></ul>');
    $j("#div_device_contact_list").append(ul);
   
    ul.append($j('<li data-role="list-divider">Device Contacts: ' + contacts.length + '</li>'));
    $j.each(contacts, function(i, contact) {
           var formattedName = contact.name.formatted;
           if (formattedName) {
           var newLi = $j("<li><a href='#'>" + (i+1) + " - " + formattedName + "</a></li>");
           ul.append(newLi);
           }
           });
   
    $j("#div_device_contact_list").trigger( "create" )
}

function onErrorDevice(error) {
    cordova.require("salesforce/util/logger").logToConsole("onErrorDevice: " + JSON.stringify(error) );
    alert('Error getting device contacts!');
}

function onSuccessSfdcContacts(response) {
    var $j = jQuery.noConflict();
    cordova.require("salesforce/util/logger").logToConsole("onSuccessSfdcContacts: received " + response.totalSize + " contacts");
   
    $j("#div_sfdc_contact_list").html("")
    var ul = $j('<ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a"></ul>');
    $j("#div_sfdc_contact_list").append(ul);
   
    ul.append($j('<li data-role="list-divider">Salesforce Contacts: ' + response.totalSize + '</li>'));
    $j.each(response.records, function(i, contact) {
           var newLi = $j("<li><a href='#'>" + (i+1) + " - " + contact.Name + "</a></li>");
           ul.append(newLi);
           });
   
    $j("#div_sfdc_contact_list").trigger( "create" )
}

function onSuccessSfdcAccounts(response) {
    var $j = jQuery.noConflict();
    cordova.require("salesforce/util/logger").logToConsole("onSuccessSfdcAccounts: received " + response.totalSize + " accounts");
   
    $j("#div_sfdc_account_list").html("")
    var ul = $j('<ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a"></ul>');
    $j("#div_sfdc_account_list").append(ul);
   
    ul.append($j('<li data-role="list-divider">Salesforce Accounts: ' + response.totalSize + '</li>'));
    $j.each(response.records, function(i, record) {
           var newLi = $j("<li><a href='#'>" + (i+1) + " - " + record.Name + "</a></li>");
           ul.append(newLi);
           });
   
    $j("#div_sfdc_account_list").trigger( "create" )
}

function onErrorSfdc(error) {
    cordova.require("salesforce/util/logger").logToConsole("onErrorSfdc: " + JSON.stringify(error));
    alert('Error getting sfdc contacts!');
}
After compiling and running the contact explorer sample app (hybrid), in index.html the onDeviceReady function is not firing nor it is giving any error in logCat in eclipse ADT?
I am using cordova 2.2.0.js using API 16 4.1.2 ?below is the code of index.html

 
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">

    
    <link rel="stylesheet" href="jquery/jquery.mobile-1.3.1.min.css" />
    <script src="jquery/jquery-2.0.0.min.js"></script>
    <script src="jquery/jquery.mobile-1.3.1.min.js"></script>
       

<script src="cordova-2.2.0.js"></script>

    <script src="cordova.force.js"></script>

   
    <script src="forcetk.mobilesdk.js"></script>


    <style>
      .logWindow {display:none; width:700px;}
      .logWindow > p {padding:0px; margin:0px; word-wrap:break-word;}
    </style>

    <script>

   
    // The version of the REST API you wish to use in your app.
    var apiVersion = "v28.0";

    var forcetkClient;
    var debugMode = true;
    var logToConsole = cordova.require("salesforce/util/logger").logToConsole;

    jQuery(document).ready(function() {
        //Add event listeners and so forth here
        logToConsole("onLoad: Hii jquery ready");
         logToConsole("onLoad:before");
           
  document.addEventListener("deviceready",onDeviceReady,false);                             //not firing,no error in LogCat and in console//
        logToConsole("onLoad:After");

    });
   
   

    // When this function is called, Cordova has been initialized and is ready to roll
    function onDeviceReady() {
   
        logToConsole("onDeviceReady: Cordova ready");
  //Call getAuthCredentials to get the initial session credentials
        cordova.require("salesforce/plugin/oauth").getAuthCredentials(salesforceSessionRefreshed, getAuthCredentialsError);

        //register to receive notifications when autoRefreshOnForeground refreshes the sfdc session
        document.addEventListener("salesforceSessionRefresh",salesforceSessionRefreshed,false);

        //enable buttons
        regLinkClickHandlers();

    }
       

    function salesforceSessionRefreshed(creds) {
        logToConsole("salesforceSessionRefreshed");
       
        // Depending on how we come into this method, `creds` may be callback data from the auth
        // plugin, or an event fired from the plugin.  The data is different between the two.
        var credsData = creds;
        if (creds.data)  // Event sets the `data` object with the auth data.
            credsData = creds.data;

        forcetkClient = new forcetk.Client(credsData.clientId, credsData.loginUrl, null,
            cordova.require("salesforce/plugin/oauth").forcetkRefresh);
        forcetkClient.setSessionToken(credsData.accessToken, apiVersion, credsData.instanceUrl);
        forcetkClient.setRefreshToken(credsData.refreshToken);
        forcetkClient.setUserAgentString(credsData.userAgent);
    }

    function getAuthCredentialsError(error) {
        logToConsole("getAuthCredentialsError: " + error);
    }
       
    </script>
       
<!-- load our app-specific code -->

    <script src="/inline/inline.js">
     alert('invoking callMe of inline.js ...');
     callMe();
   
    </script>      

  </head>
  <body>
      <div data-role="page" data-theme="b" id="jqm-home">
          <div  data-role="header">
              <h1>Hybrid REST Explorer (SalesforceMobileSDK + Cordova + JQM)</h1>
          </div>

          <div id="#content" data-role="content">

              <p><a href="#" id="link_fetch_device_contacts" data-role="button" data-inline="true">Fetch Device contacts</a></p>
              <p><a href="#" id="link_fetch_sfdc_contacts" data-role="button" data-inline="true">Fetch SFDC contacts</a></p>
              <p><a href="#" id="link_fetch_sfdc_accounts" data-role="button" data-inline="true">Fetch SFDC Accounts</a></p>
              <p><a href="#" id="link_reset" data-role="button" data-inline="true">Reset</a></p>

              <p><a href="#" id="link_logout" data-role="button" data-inline="true">Logout</a></p>

              <div id="div_device_contact_list"></div>
              <div id="div_sfdc_contact_list"></div>
              <div id="div_sfdc_account_list"></div>

              <h3>console:</h3>
              <p id="console" class="logWindow">
              </p>
          </div>

      </div>
  </body>
</html>
I am running Salesforce SDK sample apps available on GIT HUB and after compiling getting error in Android (Hybrid) sample app -Contact Explorer in UserSearch.Html and forcetk.mobilesdk.js ?
 
BELOW IS THE CODE snippet from UserSearch.html

i get error saying :
Uncaught ReferenceError: Force is not defined at UserSearch.html
Similarly in forcetk.mobilesdk.js

Uncaught ReferenceError: jquery is not defined at forcetk.mobilesdk.js

<script>
// -------------------------------------------------- The Models ---------------------------------------------------- //
// The User Model

User = Force.SObject.extend({
    sobjectType: "User",
    fieldlist: ["Id", "FirstName", "LastName", "SmallPhotoUrl", "Title", "Email", "MobilePhone","City"]
});+

// The UserCollection Model
app.models.UserCollection = Force.SObjectCollection.extend({
    model:app.models.User,
    fieldlist: ["Id" , "FirstName" , "LastName", "SmallPhotoUrl", "Title"],

    getCriteria: function() {
        return this.key;
    },

and

below is the code from forcetk.mobilesdk.js

Uncaught ReferenceError: jquery is not defined at forcetk.mobilesdk.js

    forcetk.Client.prototype.deleteFileShare = function(sharedId, callback, error) {
        return this.del("ContentDocumentLink", sharedId, callback, error);
    }
}})
.call(this, jQuery);

kindly Help me out!!!
Sir  I wanted to learn from SampleApps that salesforce has provided in their SDK,but the one which are posted on GitHub are full of errors and people have done so much editing even in SalesforceSDK libraries.It would be nice if you kindly post thelink or provide the original SDK Sample Apps .so that I can learn from it.


Thankyou!!!
Trying to deploy the Report chart component using SiteDotCom.com from the partner portal community but in the target org getting blank filters of each report.

The report filter after deployment is blank.
Below code throws error saying: Getting error attempt dereference a  null pointer:

public class AccountHandler {
public class MyException extends Exception{}
public static Account insertNewAccount(String name) {
Account a = new Account();
try
{
    IF(name=='')
    {
    throw new MyException('Empty paramenter');
    }
    else
    {
    a.Name = name;
    insert a;
    return a;
    }
}
catch (DmlException e) {
return null;
}

}
}

what am I missing?
In Apex I am trying to count the number of days from first day of the current month excluding Sat and Sun.

            Date firstDayOfMonth = System.today().toStartOfMonth();
             Datetime dt1 = DateTime.newInstance(firstDayOfMonth, Time.newInstance(0, 0, 0, 0));
             String d=dt1.format('EEEE');
            
             if(d != 'Saturday' &&  d != 'Sunday')
              {
                Datetime et1 = DateTime.newInstance(Date.Today(), Time.newInstance(0, 0, 0, 0));
                String e=et1.format('EEEE');
                System.debug('After conversion present day======'+et1);
                 
                Integer noOfDaysFromFirstDyMonth=0; 
                while (dt1<= et1) {
                d=(String)dt1.format('EEEE');
                e=(String)et1.format('EEEE');  
                    if (d!='Saturday' || d!='Sunday')  {  
                    if (e!='Saturday' || e!='Sunday')
                        {
                            noOfDaysFromFirstDyMonth = noOfDaysFromFirstDyMonth + 1;  
                            System.debug('dt1=='+dt1.format('EEE'));
                            System.debug('et1=='+et1.format('EEE'));
                        }
                    }  
                    dt1= dt1.addDays(1);  
                } 
  
When the days are Sat or Sun ,it should not go inside if conditions but its going inside ifs.Where I am wrong please guide me?
 
I am able to create a file in Google drive with the below code:

Http http = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files?uploadType=media');
req.setHeader('content-type', 'text/plain');
req.setHeader('Authorization','Bearer '+accessToken);
String messageBody = 'Hi, This message is from Salesforce';
req.setBody(messageBody); 
req.setTimeout(60*1000);
HttpResponse resp = http.send(req);

But now i want to create a file inside a folder in Google drive. I am using end point as:

req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files/0B602YDdndVQ6b3RnR2NYQXo5TXM/children?uploadType=media');
where 0B602YDdndVQ6b3RnR2NYQXo5TXM is the folder id.

Can someone please tell me what other changes i have to do in the above code in order to create the file inside a folder?
Sir  I wanted to learn from SampleApps that salesforce has provided in their SDK,but the one which are posted on GitHub are full of errors and people have done so much editing even in SalesforceSDK libraries.It would be nice if you kindly post thelink or provide the original SDK Sample Apps .so that I can learn from it.


Thankyou!!!

Hi,

I have a custom field where is stored a 15 digits Id.
I need to build a String csv with the 18 digits version of this Id.
In my Execute anonymous window, I tried a simple

system.debug(Id.valueOf('101c00000001GWe'));

 


and got

USER_DEBUG|[2]|DEBUG|101c00000001GWeAAM

 


Wonderful, that's what I need !  But when I try to write in my class

csv += Id.valueOf(var);

 


I get an ugly

Save error: variable does not exist: Id

 



I finally did what I need by creating a variable with

Id myId = String.valueOf(var); 
csv += myId;

 


But I don't understand why the documented static method Id.valueOf works in anonymous code and not in a class ?