• kdavis
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 19
    Replies
Our instance has a large amount of apex on a custom object and we continously run into the dreaded CPU Timeout error. Even after going to great lenghts to optimize our code by combining queries, pushing triggers to async methods, and even removing some logic we still manage to run into this error. We have also implemented a trigger framework similar to the one documented on Salesforce Dev blogs to try and cope with this. However, since we are using a trigger framework, there are a large number of class instantiations and method calls per transaction so I'm wondering if this is just adding to the problem.

My question is, what are some of the less obvious culprits that can contribute to the timeout error? And given those, what is the best way to compensate for those when writing triggers?

Any feedback is appreciated, Thanks.
  • August 17, 2016
  • Like
  • 0
I am trying to share a chatter document(Has AllUsers Visibility) via apex with a partner commuity user using the ContentDocumentLink object but, I am continuously thrown an error. I need to allow the community user to upload revisions of documents they did not create. Any ideas on how to do this? Code and error below:

Record I attempt to insert:
insert new ContentDocumentLink(
    ContentDocumentId = '069XXXXXXXXX',
    LinkedEntityId  = [Portal User Id],
    ShareType = 'C'
);

Error Received: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.: [LinkedEntityId]
  • August 11, 2016
  • Like
  • 0
Hi Developers,

I am attempting to make a request to the endpoint /oppitm/lineitemsort.jsp from a visual force page to sort OLIs. However, it is my understanding that in order to make post request like this I will need the CSRF token present in the request. I am trying to do this but I am having difficutly getting the correct token. I try to retrieve the token with the following ajax request:
$j.ajax({
                 url:"./oppitm/lineitemsort.jsp?id={!oppId}",
                 contentType:"text/html",
                 xhrFields:{withCredentials:true},
            }).done (function(data){
                key_start='csrfToken="';
                key_end='"';
                pos_start=data.indexOf(key_start);
                pos_end=data.indexOf(key_end,pos_start+key_start.length);
                var token=data.substring(pos_start+key_start.length,pos_end);
            });
});

But I continually get redirected to "Unable to access page." when using the CSRF token that is returned.  My understanding is that Visual Force will store the CSRF token in the form under an input with id "com.salesforce.visualforce.ViewStateCSRF" following a post, so I have been trying to get the token that way. But all attempts to do so result in an empty value in that element. Any ideas when that is appending to the form and how I can get it?
  • April 29, 2015
  • Like
  • 1
Anyone have a clever workaround for updating the SortOrder for olis and qlis programmatically? I know there is a url hack for doing this but I need to accomplish this inside a trigger not via a button click or VFP. It seems like there has been a lot of buzz over this topic over the years (6+ years to be precise) and several ideas posted on the community. 
  • March 24, 2015
  • Like
  • 1
Hi,

We are trying to post chatter files (up to 10mb) using an ETL tool, currently Informatica, but keep running into what I think is a file size limitation of the SOAP API, for the files keep getting cut off around 5mb. Any tips on how to post files above 5mb to salesforce chatter feeds? Can this be done through the API or any ETL tool?

Thanks.
  • November 18, 2014
  • Like
  • 0

Hi,

 

I'm writing a trigger to prevent duplicate accounts from being created and to do that I am using a SOSL to search across phone fields for accounts. Person Accounts are being used. Its running on update and insert. I have no idea why but it will actually work on some instances but most of the time it allows duplicates. When you enter a value in the phone field in should search across all phone fields in all accounts to see if one exists. Code is below, please lemme know if you notice something becuase I am stumped. I limit the trigger to single updates only.

Thanks.

/*Need to limit the deduping from running for bulk updtes*/
    Integer triggerSize = Trigger.New.size();
    if(triggerSize == 1){ 
        if((Trigger.isUpdate && Trigger.isBefore) ||(Trigger.isInsert && Trigger.isAfter)){
            String phones;
            Account acct = Trigger.New[0];
            Account returnedAccount;
            String home = acct.PersonHomePhone;
            String mobile = acct.PersonMobilePhone;
            String otherPhone = acct.PersonOtherPhone;
            String regPhone = acct.Phone;
            Set<String> currPhones = new Set<String>{home,mobile,otherPhone,regPhone};
            Set<String> cleansedPhones = new Set<String> ();
            
            for(String p : currPhones){
                if(p != null){
                    p = p.replace('(',''); p = p.replace(')','');
                    p = p.replace('-',''); p = p.trim(); //remove characters               
                    p = p.replace(' ','');
                    cleansedPhones.add(p);
                }
            }

            for(String p : cleansedPhones){
                if(phones == null){
                    phones = String.ValueOf(p);
                }else{
                    phones = phones + ' OR '+String.ValueOf(p);
                }
            }


            System.debug('phones  '+phones);
            
            if(phones != null){
                String queryString = 'FIND {FILTER} IN PHONE FIELDS RETURNING Account(Owner.Name, Name,Id WHERE Id != \'currentId\')';      
                queryString = queryString.replace('FILTER',phones);
                queryString = queryString.replace('currentId',acct.Id); 
                System.debug('This is the Query String    '+queryString);           

                List<List <sObject>> query = search.query(queryString);
                System.debug('This is the return    '+query);
                for(sObject s : query[0]){
                    returnedAccount = (Account)s;
                    System.debug('This was returned  '+returnedAccount);
                }

                if(returnedAccount != null){
                    acct.addError('ERROR: This Account belongs to another broker: '+returnedAccount.Owner.Name, false);
                }
            }
        }
    }       

 

  • November 27, 2013
  • Like
  • 0

Hi,

 

I have a custom detail page button that redirects to a visual force page and then upon a "save" action I need to redirect to that records detail page. I need it to work both in the service console and out. Is there a different approach to refreshing the parent window to return the detail view in service console and also directing to the VFP? In the regular case you would just append the record id onto the url but I see that the URL in the console has a different anatomy. Any tips would be very much appreciated.

 

Thanks

  • November 06, 2013
  • Like
  • 0

Hi,

 

I have an odd request by a client where they would like the text in the last column in their VF component to stay in the same line and not wrap, and just be able to scroll left. That's fine the problem I am encountering is that I am using a pageblock and when the text grows too high in characters the pageblock wont stretch with the table and its columns, and it looks very clunky. I have all widths set to 100% including the component in the detail page. Any idea how I can get the pageblock to stretch to the full width of the page with the table? VF below:

 

<apex:PageBlock title="Search Assets">
        
        <div id="searchContainer" style="width:100%;height:50px;">            
            <span id="serialSpan" >Serial #:</span>&nbsp;&nbsp;
            <apex:inputText id="serialIn" value="{!serialId}" ondblclick="clearText(this)" style="width:100px;"/>&nbsp;&nbsp;
            <apex:CommandButton value="Search" action="{!searchAssets}" onClick="resetSerialCount()"/>&nbsp;&nbsp;&nbsp;
        
            <span id="regSpan" stringLic="{!licString}">Registration #:</span>&nbsp;&nbsp;
            <apex:inputText id="extIn" value="{!externalRef}" ondblclick="clearText(this)" style="width:100px;"/>&nbsp;&nbsp;
            <apex:CommandButton value="Search" action="{!searchByRefId}" onClick="resetExtCount()"/><br/><br/>  
        </div>
                   
        
        <div id="pageBlockContainer" style="width:100%;height:100%;">
            <apex:pageMessages />
            
            <apex:pageBlockTable value="{!entitlements}" var="e" columns="7" Width="100%" rendered="{!renderEntitlements}">
                <apex:column id="Select" headerValue="Select">
                    <input type="checkbox" onclick="selectAsset(this)" name="{!e.Asset.Name}" serial="{!e.Asset.Serial_Number__c}" lic="{!e.Asset.External_Reference__c}" aid="{!e.AssetId}" entitle="{!e.Id}" caseId="{!c.Id}" eDate="{!e.EndDate}"/>
                </apex:column>
                <apex:column id="Name" headerValue="Name" value="{!e.AssetId}"/>                                
    
                <apex:column id="Serial" headerValue="Serial" value="{!e.Asset.Serial_Number__c}"/>
                
                <apex:column id="endDate" headerValue="Usage End Date" value="{!e.EndDate}"/>
                
                <apex:column id="extRef" headerValue="Registration" value="{!e.Asset.External_Reference__c}"/>
    
                <apex:column id="Entitle" headerValue="Entitlement" value="{!e.Name}"/>
                
                <apex:column id="sc" headerValue="Service Contract" style="white-space: nowrap;" value="{!e.ServiceContractId}"/>                
    
            </apex:pageBlockTable>
      
        </div>
        <div id="reloadMessage" style="width:100%;height:100%;display:none;margin: 0 auto;">
            <div style="width:50%;height20px;display:inline-block;"><b>Please wait for the parent page to manually refresh...</b></div><br/><br/>
            <div id="spinnerDiv" style="width:100px;margin:auto;">
                <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
            </div>   
        </div>                           
        <apex:PageBlockButtons location="bottom">
            <div class="linkBtn" onclick="insertAssets()">Link</div>
        </apex:PageBlockButtons>
    </apex:PageBlock>

 

  • November 04, 2013
  • Like
  • 0

Hi,

 

I'm using a static recursive variables for my triggers and I am encountering an issue when testing. I have 2 triggers. One on a custom object called procedure and another on custom object revenue that updates a procedure when inserted.

 

So in my test class I insert a procedure record, the first trigger runs and at the end sets the recursive variable hasRun = True.

 

Now when I go an insert my Revenue record, I want it to run through the procedure trigger again, but hasRun still equals to True? Do you need to reset static variables like that in test cases because test classes are considered a single execution state?

 

  • October 03, 2013
  • Like
  • 0

Hi,

 

Getting this extremely annoying issue.

 

Here is my query:

 

assets = [SELECT Id, Name, External_Reference__c, Serial_Number__c, UsageEndDate, (SELECT Id, Name, AssetId FROM Entitlements) FROM Asset WHERE Serial_Number__c IN : serialIds ORDER BY UsageEndDate Desc];

 

 

I have a nested page block where I want to iterate through the child Entitlements, but I continously get this error:

 

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Asset.Entitlements

 

I can't find any security that is prohibiting me from viewing this list.

Any ideas?

 

  • October 01, 2013
  • Like
  • 0

Hi,

 

I'm putting a VF component on Case records. Essentially I return a set of Asset records and provide a checkbox next to each so they can add multiple assets to the case at once. Once they select a checkbox next to the assets, the asset ID is pushed to a JScript variable. 

 

After all the user has selected all their assets, they click a button which pushes the Javascript Var String to my remote method in my controller where I parse the Jscript string into the different ID's.

 

Problem is, everything works fine in the page, when I do it in editor. Once I get on an actual Case detail page I get an error everytime I try to call the remote method that tells me Uncaugh ReferenceError: [My Controller Name] is not defined. 

 

Any Ideas on how to fix this? I know they communicate correctly in the page editor just not in the acutal component. Code Below:

 

 

Page:

<apex:page standardController="Case" extensions="linkAssetExtension">
    <apex:includeScript value="{!$Resource.JqueryUI}"/>
    <apex:includeScript value="{!$Resource.JQueryCustom}"/>
    <apex:stylesheet value="{!$Resource.JqueryStyles}"/>
    <apex:stylesheet value="{!$Resource.JqueryStyles2}"/> 

    
<script type="text/javascript">

var j$ = jQuery.noConflict();

var assets = null;

function selectAsset(ele){
    
    console.log(j$(ele).is(':checked'));
    
    if(j$(ele).is(':checked')){
        console.log(j$(ele).attr('Id'));
        id = j$(ele).attr('Id');
        entitlement = j$(ele).attr('entitle');
        
        if(assets === null){
            assets = id+':'+entitlement;
        }else{
            assets += '-'+id+':'+entitlement;
        }
        console.log(assets);
    }
   
}
    
function insertAssets(){
    
        linkAssetExtension.linkAsset( 
        assets,
        function(result, event){
            console.log(result)
        }
    );

}

</script>

<apex:form >
    <apex:PageBlock title="Search Assets">

            Please Enter A Serial Number:&nbsp;&nbsp;&nbsp;
            <apex:inputText value="{!serialId}"/><br/><br/>

            <apex:pageBlockTable value="{!assets}" var="a" columns="4" Width="90%">
                <apex:column id="Select" headerValue="Select">
                    <input type="checkbox" onclick="selectAsset(this)" name="{!a.Name}" serial="{!a.Serial_Number__c}" id="{!a.Id}" entitle="{!a.Entitlement__c}"/>
                </apex:column>
                <apex:column id="Name" headerValue="Name" value="{!a.Name}"/>                

                <apex:column id="Serial" headerValue="Serial #" value="{!a.Serial_Number__c}"/>

                <apex:column id="Entitle" headerValue="Entitlement" value="{!a.Entitlement__c}"/>

            </apex:pageBlockTable>
      
        <apex:PageBlockButtons location="bottom">
            <apex:CommandButton value="Search" action="{!searchAssets}"/>
            <div style="width:45px;height:18px;border:1px solid black;border-radius:5px;text-align:center;display:inline-block;margin-top:-2px;vertical-align:middle;" onclick="insertAssets()">Link</div>
        </apex:PageBlockButtons>
    </apex:PageBlock>
</apex:form>

</apex:page>

 

Controller:

public class linkAssetExtension {
    
    public String serialId {get; set;} 
    public List<Asset> assets {get; set;}   
    private final Case c;
    public static Id caseId {get; set;}
    
    public linkAssetExtension(ApexPages.StandardController controller) {
        this.c = (Case)controller.getRecord();
        caseId = c.Id;
        assets = new List<Asset> ();
    }

    public void searchAssets(){
        if(serialId != null){
            assets = [SELECT Id, Name, Serial_Number__c, Entitlement__c, Asset_Type__c FROM Asset WHERE Serial_Number__c =: serialId];
        }
    }
    
    @RemoteAction
    public static Map<String, List<String>> linkAsset(String assetList){
       
       system.debug(assetList);
       List<Case> upsertCase = new List<Case> ();
       Map<String, List<String>> assetMap = new Map<String, List<String>> ();
       

        List<String> assetFields = new List<String> ();
        assetFields = assetList.split('-');
        
        for(String s : assetFields){
            List<String> fields = new List<String> ();
            fields = s.split(':');
            assetMap.put(fields[0], fields);
        }
            
     
        for(String s : assetMap.keySet()){
            //Add link records
        }

        return assetMap;
    }    
}

 

  • September 20, 2013
  • Like
  • 0

Hey Guys,

 

I have a requirement where: A contact already exists, they need a custom button that directs to a visual force page where I have a created a form that has a subset of fields on the contac they need to fill out. When they are done they save and need to update the contact.

 

So far I have completed:

1. Directing to the page

2. Querying the subset of contact fields in the controller that will be used in the page since we cannot use a standard controller

3. Built the page

Error 4. Updating the record using a page refrence

 

Here is the controller:

 

public class IntakeController{

public static Contact currentContact {get; set;}
public final Id cId {get; set;}


public IntakeController() {

cId = ApexPages.currentPage().getparameters().get('cid');
currentContact = new Contact();
currentContact = [SELECT
                  //All the fields
FROM Contact
WHERE Id =: cId];

}

public PageReference SaveContact(){
system.debug(currentContact);

if(currentContact != null){
update currentContact;
}

PageReference returnPage = new PageReference('/' + cId);
returnPage.setRedirect(true); 
return returnPage; 
} 
}

 

Problem is everytime I go to save I get a null value for currentContact in that debug. I am updating the values of contact Record in the page using input fields. What am I doing wrong here, and how do I get the updated values from the page? 

 

Thanks

 

  • September 10, 2013
  • Like
  • 0

Hi,

 

Does salesforce offer any online courses on API integration with salesforce and .Net development. API integration with SF is something I would really like to imporve on and I'd be willing to pay for the course. Any classes anyone has taken and would reccommend? I am located in Michigan so I'm not sure if they offer any locally.

 

Thanks

  • August 23, 2013
  • Like
  • 0

Hi,

 

I have a requirement that everytime a user changes ownership of a Lead, after 60 days that Lead needs to be re-evaluated. If after 60 days the Lead has not been converted, it needs to automatically be reassigned to the original owner (which there will be a field for).

 

Is the best way to handle this through TBWF or through apex scheduling? Sounds like Time Based Workflow due to the 100 class scheudling limit. Is there a similar limit on workflow?

Any other suggestions?

  • August 19, 2013
  • Like
  • 0

Hi,

 

I am running a scheduled batch job where I perform the DML operation inside the finish method. I placed a debug log inside the finish method to print out my records to see if everything is updating the values correctly and it does, and from the test log I see that it performs the update as well.

 

Now the problem is, after I do my Start.Test() and Stop.Test() where I schedule my class to run and set up data, I query the objects I have updated and print them out nothing happens to them....

 

When I look at the execution in the test log, the print outs in my test method are occuring before my debugs in both my execute and finish methods.

 

Am I missing something here? It looks as if my assertions and debugs are occurring before the fact rather than after and I'm not quite sure how to fix it.

 

Any feedback would be appreciated.

Thanks

  • August 09, 2013
  • Like
  • 0

Hey all,

 

So I have a requirement that my client wants to be able to count the number of times a canned email response is used. They are using quick texts for cases and they want to monitor how many times the message field is contained in the text body of an email, for every quick text record. They also want to break it up into three fields, how many emails contain the text in that last 30, 7, and one days. So I wrote up a scheduled class and a batch class to try and handle this and I wanted to get some feedback if I am approaching this the correct way. They also wants to run this every 24 hours. Code posted below.

 

Scheduled Class: 

 

global class emailCountScheduled implements Schedulable{


global void execute(SchedulableContext sc) {

List<QuickText> qt = new List<QuickText> ();
Map<String, QuickText> responseToQT = new Map<String, QuickText> ();
List<String> messages = new List<String> ();
Date dateFilter = Date.Today().addDays(-30);
String dateFilterString = String.valueOf(dateFilter);

qt = [SELECT Id, Message, Total_Use_1_Day__c, Total_Use_30_Days__c, Total_Use_7_Days__c FROM QuickText];

if(!qt.isEmpty()){
for(QuickText q : qt){
if(q.Message != null){
messages.add(q.Message);
responseToQT.put(q.Message, q);
}
}
}

String query = 'SELECT Id, Subject, Description, ActivityDate FROM task WHERE Subject LIKE \'%Email%\' AND ActivityDate > dateFilter';
query = query.replace('dateFilter', dateFilterString);

emailCountBatch b = new emailCountBatch(responseToQT,messages,query);

database.executebatch(b);
}
}

 

Batch class:

 

global class emailCountBatch implements Database.Batchable<sObject> {

global final String query;
global final Map<String, QuickText> responseObjects;
global final List<String> cannedResponses;

global emailCountBatch(Map<String, QuickText> qt, List<String> messages, String q) {

responseObjects = new Map<String, QuickText> ();
cannedResponses = new List<String> ();

responseObjects = qt; cannedResponses = messages; query = q;
}

global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<sObject> scope) {
Map<String, List<sObject>> thirtyDays = new Map<String, List<sObject>> ();
Map<String, List<sObject>> sevenDays = new Map<String, List<sObject>> ();
Map<String, List<sObject>> oneDay = new Map<String, List<sObject>> ();

for(sObject s : scope){

String emailBody = String.ValueOf(s.get('Description'));

for(String m : cannedResponses){
if(emailBody.contains(m)){
if(!thirtyDays.containsKey(m)){
thirtyDays.put(m, new List<sObject> ());
}

if(thirtyDays.containsKey(m)){
List<sObject> objectList = thirtyDays.get(m);
objectList.add(s);
thirtyDays.put(m, objectList);
}

//Check if within 7 days
if(Date.ValueOF(s.get('ActivityDate')) > Date.Today().addDays(-7)){
if(!sevenDays.containsKey(m)){
sevenDays.put(m, new List<sObject> ());
}

if(sevenDays.containsKey(m)){
List<sObject> objectList = sevenDays.get(m);
objectList.add(s);
sevenDays.put(m, objectList);
}
}

//Check if within 1 day
if(Date.ValueOF(s.get('ActivityDate')) > Date.Today().addDays(-1)){
if(!oneDay.containsKey(m)){
oneDay.put(m, new List<sObject> ());
}

if(oneDay.containsKey(m)){
List<sObject> objectList = oneDay.get(m);
objectList.add(s);
oneDay.put(m, objectList);
}
}
}
}
}

for(String s : responseObjects.keySet()){
QuickText currentQT = responseObjects.get(s);
currentQT.Total_Use_30_Days__c += thirtyDays.get(s).size();
currentQT.Total_Use_7_Days__c += sevenDays.get(s).size();
currentQT.Total_Use_1_Day__c += oneDay.get(s).size();
}
}

global void finish(Database.BatchableContext BC) {
update responseObjects.values();
}
}

 

I appreciate any feedback. Thanks guys.

  • August 08, 2013
  • Like
  • 0

Hey guys,

 

So I have a trigger that will run on a bulk update or insert. My query will run 5 Aggregate queries, none of these are in for loops I query based on collected ID's. If I run for more that 2000 records and I hit 

System.LimitException: Too many SOQL queries: 101. Any tips on how to work around this and bulkify my trigger more? I was thinking of batch apex but I have very little familiarity. If I use batch apex can I give a specific amount to insert at once and will it reset governor limits on every batch. Any helpful documentation on this?

Thanks.

  • August 03, 2013
  • Like
  • 0

Hi all,

 

I have a template object that has a field called "Instructions" which is a large string that contains merge fields. I need to create a list of these merge fields so I can loop through a queried record and replace the merge field in the template string with actual information. The instructions are not always the same there are different merge fields on every record.

 

Here is a simple example and explanation:

 

String instructions = 'Instructions: Contact Name: {{Contact_Name__c}}, Contact Number: {{Contact_Number__c}}' ;

 

Is there an simple string method or clever way someone knows of that will allow me to grab the fields between the ' {{ }} '  or any characters for that matter?

 

Thanks

Hi,

 

I'm recieving this error: 

No more than one executeBatch can be called from within a testmethod.  Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

 

The scope is an iterable list of XML docs returned by the start method:

global Iterable<SyncXmlFeedsUtils.XmlFeed> start(Database.BatchableContext bc) {
return SyncXmlFeedsUtils.feeds;
}

 

the feeds list is formatted as such:

 

static {

feeds = new List<XmlFeed> {
new XmlFeed('URL----', PressReleaseParser.class),
new XmlFeed('URL----', AnalystReportsParser.class),
new XmlFeed('URL----', WebinarsParser.class),
new XmlFeed('URL----', ClientSuccessStoriesParser.class)
};
}

 

for my execute method I have:

global void execute(Database.BatchableContext bc, List<SyncXmlFeedsUtils.XmlFeed> scope) 

 

And then then the test class:

 

global class SyncXmlBatchTest {


@isTest static void testBatch() {


test.startTest();

Test.setMock(HttpCalloutMock.class, new HttpResonseGenerator());


List<RSINews__c> response = SyncXmlFeedsUtils.parseXmlFeeds(SyncXmlFeedsUtils.feeds);

 

SyncXmlFeedsBatchable batchTest = new SyncXmlFeedsBatchable ();


Id batchprocessId = Database.executeBatch(batchTest, 1);

test.stopTest();

}


}

 

 

Any Idea how to get around this error? If I don't set the batch size to 1 I get another error saying "System.CalloutException: . Please commit or rollback before calling out".

 

Any help would be very appreciated.

Thanks.

  • March 15, 2013
  • Like
  • 0

Hi, 

I'm trying to parse some XML with the following code

 

public class AnalystReportsParser implements XMLParser{

public virtual RSINews__c[] parseXml(XmlStreamReader xml) {
RSINews__c[] news = new RSINews__c[0];
while(xml.hasNext()) {

  if (xml.getEventType() == XmlTag.START_ELEMENT) {

   if ('Page' == xml.getLocalName()){

       if('en-us' == xml.getAttributeValue(null, 'Locale')){
             RSINews__c record = new RSINews__c ();

 

                  ''

                  ''

             news.add(record);
        }
     }

      xml.next();
    }
}
return news;
}
}

 

However I keep recieving the error:

System.LimitException: Too many code statements: 200001

And it indicates that it occurs in my if loop:

 

if (xml.getEventType() == XmlTag.START_ELEMENT) {

 

any ideas why this occurs?

thx

  • March 15, 2013
  • Like
  • 0
Hi Developers,

I am attempting to make a request to the endpoint /oppitm/lineitemsort.jsp from a visual force page to sort OLIs. However, it is my understanding that in order to make post request like this I will need the CSRF token present in the request. I am trying to do this but I am having difficutly getting the correct token. I try to retrieve the token with the following ajax request:
$j.ajax({
                 url:"./oppitm/lineitemsort.jsp?id={!oppId}",
                 contentType:"text/html",
                 xhrFields:{withCredentials:true},
            }).done (function(data){
                key_start='csrfToken="';
                key_end='"';
                pos_start=data.indexOf(key_start);
                pos_end=data.indexOf(key_end,pos_start+key_start.length);
                var token=data.substring(pos_start+key_start.length,pos_end);
            });
});

But I continually get redirected to "Unable to access page." when using the CSRF token that is returned.  My understanding is that Visual Force will store the CSRF token in the form under an input with id "com.salesforce.visualforce.ViewStateCSRF" following a post, so I have been trying to get the token that way. But all attempts to do so result in an empty value in that element. Any ideas when that is appending to the form and how I can get it?
  • April 29, 2015
  • Like
  • 1
Anyone have a clever workaround for updating the SortOrder for olis and qlis programmatically? I know there is a url hack for doing this but I need to accomplish this inside a trigger not via a button click or VFP. It seems like there has been a lot of buzz over this topic over the years (6+ years to be precise) and several ideas posted on the community. 
  • March 24, 2015
  • Like
  • 1

Hi,

 

I'm writing a trigger to prevent duplicate accounts from being created and to do that I am using a SOSL to search across phone fields for accounts. Person Accounts are being used. Its running on update and insert. I have no idea why but it will actually work on some instances but most of the time it allows duplicates. When you enter a value in the phone field in should search across all phone fields in all accounts to see if one exists. Code is below, please lemme know if you notice something becuase I am stumped. I limit the trigger to single updates only.

Thanks.

/*Need to limit the deduping from running for bulk updtes*/
    Integer triggerSize = Trigger.New.size();
    if(triggerSize == 1){ 
        if((Trigger.isUpdate && Trigger.isBefore) ||(Trigger.isInsert && Trigger.isAfter)){
            String phones;
            Account acct = Trigger.New[0];
            Account returnedAccount;
            String home = acct.PersonHomePhone;
            String mobile = acct.PersonMobilePhone;
            String otherPhone = acct.PersonOtherPhone;
            String regPhone = acct.Phone;
            Set<String> currPhones = new Set<String>{home,mobile,otherPhone,regPhone};
            Set<String> cleansedPhones = new Set<String> ();
            
            for(String p : currPhones){
                if(p != null){
                    p = p.replace('(',''); p = p.replace(')','');
                    p = p.replace('-',''); p = p.trim(); //remove characters               
                    p = p.replace(' ','');
                    cleansedPhones.add(p);
                }
            }

            for(String p : cleansedPhones){
                if(phones == null){
                    phones = String.ValueOf(p);
                }else{
                    phones = phones + ' OR '+String.ValueOf(p);
                }
            }


            System.debug('phones  '+phones);
            
            if(phones != null){
                String queryString = 'FIND {FILTER} IN PHONE FIELDS RETURNING Account(Owner.Name, Name,Id WHERE Id != \'currentId\')';      
                queryString = queryString.replace('FILTER',phones);
                queryString = queryString.replace('currentId',acct.Id); 
                System.debug('This is the Query String    '+queryString);           

                List<List <sObject>> query = search.query(queryString);
                System.debug('This is the return    '+query);
                for(sObject s : query[0]){
                    returnedAccount = (Account)s;
                    System.debug('This was returned  '+returnedAccount);
                }

                if(returnedAccount != null){
                    acct.addError('ERROR: This Account belongs to another broker: '+returnedAccount.Owner.Name, false);
                }
            }
        }
    }       

 

  • November 27, 2013
  • Like
  • 0

Hi all ,

I have controller and I written test class for that . It is covering 60% code but, I am facing following problem

 

 

I am able see how much % code covered , earlier if we click on percentage it used to show what portion code covered and not covered with different colors , but now its not coming So please help me where I can find that  .

Hi,

 

I'm using a static recursive variables for my triggers and I am encountering an issue when testing. I have 2 triggers. One on a custom object called procedure and another on custom object revenue that updates a procedure when inserted.

 

So in my test class I insert a procedure record, the first trigger runs and at the end sets the recursive variable hasRun = True.

 

Now when I go an insert my Revenue record, I want it to run through the procedure trigger again, but hasRun still equals to True? Do you need to reset static variables like that in test cases because test classes are considered a single execution state?

 

  • October 03, 2013
  • Like
  • 0

Hi,

 

Getting this extremely annoying issue.

 

Here is my query:

 

assets = [SELECT Id, Name, External_Reference__c, Serial_Number__c, UsageEndDate, (SELECT Id, Name, AssetId FROM Entitlements) FROM Asset WHERE Serial_Number__c IN : serialIds ORDER BY UsageEndDate Desc];

 

 

I have a nested page block where I want to iterate through the child Entitlements, but I continously get this error:

 

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Asset.Entitlements

 

I can't find any security that is prohibiting me from viewing this list.

Any ideas?

 

  • October 01, 2013
  • Like
  • 0

Hi,

 

I'm putting a VF component on Case records. Essentially I return a set of Asset records and provide a checkbox next to each so they can add multiple assets to the case at once. Once they select a checkbox next to the assets, the asset ID is pushed to a JScript variable. 

 

After all the user has selected all their assets, they click a button which pushes the Javascript Var String to my remote method in my controller where I parse the Jscript string into the different ID's.

 

Problem is, everything works fine in the page, when I do it in editor. Once I get on an actual Case detail page I get an error everytime I try to call the remote method that tells me Uncaugh ReferenceError: [My Controller Name] is not defined. 

 

Any Ideas on how to fix this? I know they communicate correctly in the page editor just not in the acutal component. Code Below:

 

 

Page:

<apex:page standardController="Case" extensions="linkAssetExtension">
    <apex:includeScript value="{!$Resource.JqueryUI}"/>
    <apex:includeScript value="{!$Resource.JQueryCustom}"/>
    <apex:stylesheet value="{!$Resource.JqueryStyles}"/>
    <apex:stylesheet value="{!$Resource.JqueryStyles2}"/> 

    
<script type="text/javascript">

var j$ = jQuery.noConflict();

var assets = null;

function selectAsset(ele){
    
    console.log(j$(ele).is(':checked'));
    
    if(j$(ele).is(':checked')){
        console.log(j$(ele).attr('Id'));
        id = j$(ele).attr('Id');
        entitlement = j$(ele).attr('entitle');
        
        if(assets === null){
            assets = id+':'+entitlement;
        }else{
            assets += '-'+id+':'+entitlement;
        }
        console.log(assets);
    }
   
}
    
function insertAssets(){
    
        linkAssetExtension.linkAsset( 
        assets,
        function(result, event){
            console.log(result)
        }
    );

}

</script>

<apex:form >
    <apex:PageBlock title="Search Assets">

            Please Enter A Serial Number:&nbsp;&nbsp;&nbsp;
            <apex:inputText value="{!serialId}"/><br/><br/>

            <apex:pageBlockTable value="{!assets}" var="a" columns="4" Width="90%">
                <apex:column id="Select" headerValue="Select">
                    <input type="checkbox" onclick="selectAsset(this)" name="{!a.Name}" serial="{!a.Serial_Number__c}" id="{!a.Id}" entitle="{!a.Entitlement__c}"/>
                </apex:column>
                <apex:column id="Name" headerValue="Name" value="{!a.Name}"/>                

                <apex:column id="Serial" headerValue="Serial #" value="{!a.Serial_Number__c}"/>

                <apex:column id="Entitle" headerValue="Entitlement" value="{!a.Entitlement__c}"/>

            </apex:pageBlockTable>
      
        <apex:PageBlockButtons location="bottom">
            <apex:CommandButton value="Search" action="{!searchAssets}"/>
            <div style="width:45px;height:18px;border:1px solid black;border-radius:5px;text-align:center;display:inline-block;margin-top:-2px;vertical-align:middle;" onclick="insertAssets()">Link</div>
        </apex:PageBlockButtons>
    </apex:PageBlock>
</apex:form>

</apex:page>

 

Controller:

public class linkAssetExtension {
    
    public String serialId {get; set;} 
    public List<Asset> assets {get; set;}   
    private final Case c;
    public static Id caseId {get; set;}
    
    public linkAssetExtension(ApexPages.StandardController controller) {
        this.c = (Case)controller.getRecord();
        caseId = c.Id;
        assets = new List<Asset> ();
    }

    public void searchAssets(){
        if(serialId != null){
            assets = [SELECT Id, Name, Serial_Number__c, Entitlement__c, Asset_Type__c FROM Asset WHERE Serial_Number__c =: serialId];
        }
    }
    
    @RemoteAction
    public static Map<String, List<String>> linkAsset(String assetList){
       
       system.debug(assetList);
       List<Case> upsertCase = new List<Case> ();
       Map<String, List<String>> assetMap = new Map<String, List<String>> ();
       

        List<String> assetFields = new List<String> ();
        assetFields = assetList.split('-');
        
        for(String s : assetFields){
            List<String> fields = new List<String> ();
            fields = s.split(':');
            assetMap.put(fields[0], fields);
        }
            
     
        for(String s : assetMap.keySet()){
            //Add link records
        }

        return assetMap;
    }    
}

 

  • September 20, 2013
  • Like
  • 0

Hey Guys,

 

I have a requirement where: A contact already exists, they need a custom button that directs to a visual force page where I have a created a form that has a subset of fields on the contac they need to fill out. When they are done they save and need to update the contact.

 

So far I have completed:

1. Directing to the page

2. Querying the subset of contact fields in the controller that will be used in the page since we cannot use a standard controller

3. Built the page

Error 4. Updating the record using a page refrence

 

Here is the controller:

 

public class IntakeController{

public static Contact currentContact {get; set;}
public final Id cId {get; set;}


public IntakeController() {

cId = ApexPages.currentPage().getparameters().get('cid');
currentContact = new Contact();
currentContact = [SELECT
                  //All the fields
FROM Contact
WHERE Id =: cId];

}

public PageReference SaveContact(){
system.debug(currentContact);

if(currentContact != null){
update currentContact;
}

PageReference returnPage = new PageReference('/' + cId);
returnPage.setRedirect(true); 
return returnPage; 
} 
}

 

Problem is everytime I go to save I get a null value for currentContact in that debug. I am updating the values of contact Record in the page using input fields. What am I doing wrong here, and how do I get the updated values from the page? 

 

Thanks

 

  • September 10, 2013
  • Like
  • 0

Hi,

 

I am running a scheduled batch job where I perform the DML operation inside the finish method. I placed a debug log inside the finish method to print out my records to see if everything is updating the values correctly and it does, and from the test log I see that it performs the update as well.

 

Now the problem is, after I do my Start.Test() and Stop.Test() where I schedule my class to run and set up data, I query the objects I have updated and print them out nothing happens to them....

 

When I look at the execution in the test log, the print outs in my test method are occuring before my debugs in both my execute and finish methods.

 

Am I missing something here? It looks as if my assertions and debugs are occurring before the fact rather than after and I'm not quite sure how to fix it.

 

Any feedback would be appreciated.

Thanks

  • August 09, 2013
  • Like
  • 0

Hey guys,

 

So I have a trigger that will run on a bulk update or insert. My query will run 5 Aggregate queries, none of these are in for loops I query based on collected ID's. If I run for more that 2000 records and I hit 

System.LimitException: Too many SOQL queries: 101. Any tips on how to work around this and bulkify my trigger more? I was thinking of batch apex but I have very little familiarity. If I use batch apex can I give a specific amount to insert at once and will it reset governor limits on every batch. Any helpful documentation on this?

Thanks.

  • August 03, 2013
  • Like
  • 0

Hi,

 

I'm recieving this error: 

No more than one executeBatch can be called from within a testmethod.  Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

 

The scope is an iterable list of XML docs returned by the start method:

global Iterable<SyncXmlFeedsUtils.XmlFeed> start(Database.BatchableContext bc) {
return SyncXmlFeedsUtils.feeds;
}

 

the feeds list is formatted as such:

 

static {

feeds = new List<XmlFeed> {
new XmlFeed('URL----', PressReleaseParser.class),
new XmlFeed('URL----', AnalystReportsParser.class),
new XmlFeed('URL----', WebinarsParser.class),
new XmlFeed('URL----', ClientSuccessStoriesParser.class)
};
}

 

for my execute method I have:

global void execute(Database.BatchableContext bc, List<SyncXmlFeedsUtils.XmlFeed> scope) 

 

And then then the test class:

 

global class SyncXmlBatchTest {


@isTest static void testBatch() {


test.startTest();

Test.setMock(HttpCalloutMock.class, new HttpResonseGenerator());


List<RSINews__c> response = SyncXmlFeedsUtils.parseXmlFeeds(SyncXmlFeedsUtils.feeds);

 

SyncXmlFeedsBatchable batchTest = new SyncXmlFeedsBatchable ();


Id batchprocessId = Database.executeBatch(batchTest, 1);

test.stopTest();

}


}

 

 

Any Idea how to get around this error? If I don't set the batch size to 1 I get another error saying "System.CalloutException: . Please commit or rollback before calling out".

 

Any help would be very appreciated.

Thanks.

  • March 15, 2013
  • Like
  • 0

Hi, 

I'm trying to parse some XML with the following code

 

public class AnalystReportsParser implements XMLParser{

public virtual RSINews__c[] parseXml(XmlStreamReader xml) {
RSINews__c[] news = new RSINews__c[0];
while(xml.hasNext()) {

  if (xml.getEventType() == XmlTag.START_ELEMENT) {

   if ('Page' == xml.getLocalName()){

       if('en-us' == xml.getAttributeValue(null, 'Locale')){
             RSINews__c record = new RSINews__c ();

 

                  ''

                  ''

             news.add(record);
        }
     }

      xml.next();
    }
}
return news;
}
}

 

However I keep recieving the error:

System.LimitException: Too many code statements: 200001

And it indicates that it occurs in my if loop:

 

if (xml.getEventType() == XmlTag.START_ELEMENT) {

 

any ideas why this occurs?

thx

  • March 15, 2013
  • Like
  • 0

Hi,

 

Can anyone tell me where to find some quality documention on parsing XML with apex. I have no experience in parsing XML, so some detailed walkthrough's would be very helpful.

 

Thanks!

  • March 13, 2013
  • Like
  • 0

Hello,

 

I have a (before insert, before update) trigger on a custom object called Assignment that reassigns the record ownerID to a user ID based on a custom field in the Assignment object that looks up to another custom object called Requested Employee that looks up to a user record.

 

In addition I have a workflow rule that populates the users email in a custom field on the Assignment object.

 

The trigger works, I am able to reassign the owner, but only when the workflow rule is active. When I deactivate the workflow rule, the record owner will not reassign when I insert a new record, it will only update after I have edited a record TWICE.

 

My question is...why does this occur. I'm relatively new to SF and Apex, and trying to learn what is going on behind the scenes in this situation.

I'm assuming the workflow rule has some effect on the records contained in the Trigger.NEW list but I am having trouble wrapping my head around what is going on.

 

Any help or advice would be greatly appreciated.

 

Thanks!

  • January 23, 2013
  • Like
  • 0