• BritishBoyinDC
  • PRO
  • 2544 Points
  • Member since 2006

  • Chatter
    Feed
  • 94
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 30
    Questions
  • 576
    Replies
Hi all. My first question over here in the foreign climes of the dev boards - go easy on me, I am but a mere admin. :-)

I have written a trigger which stops an account being deleted if one of its field values is not null. This works as expected. I have written the test class, which is at 100% coverage but one of my asserts is failing. The asserts around the delete being blocked work fine - it is the negative case, where the field is null and so where the delete should go ahead, that is not working.

Here is my test class, with the delete and failing assert highlighted:
 
@IsTest
public class PreventAccountDeletionTest {

    private static testMethod void testDeleteSuccess()
    {
           Account acc=new Account(Name='Test Account');
           insert acc;
           
           System.assertNotEquals(acc.Id, null);
           System.assertEquals(acc.Some_Field__c, null);

           delete acc;
                 
           System.assertEquals(acc.IsDeleted, true);
        }

    private static testMethod void testDeleteFail()
    {
           Account acc=new Account(Name='Test Account', Some_Field__c='ABCDEFGHIJKLMNOP');
           insert acc;
  
           try
           {
              delete acc;
              // should throw an exception - the following assertion will cause an error if the code carries on
              System.assert(false);
           }
           catch (DMLException e)
           {
               // expected
               System.assert(e.getMessage().contains('You cannot delete an Account which is linked to the external system.'));
           }
        
        System.assertEquals(acc.IsDeleted, false);
        
    }

}

Any suggestions? Is there something I don't know about deleting in a test class? As the record is (hopefully) in the recycle bin do I need to use something like the equivalent of ALL ROWS? Or any other obvious thing that I'm missing?

Oh and let me know if you want to see the trigger code. Many thanks in advance!

I'm having a difficult time to get my code coverage increased (I'm still a newb on the dev end).

My class is working and the test class passes, but I'm not able to piece it all together.  Any help?

 

My Class to display values on a VF page...

public class ascSummary{

    public ascSummary() {

    }


    public ascSummary(ApexPages.StandardController controller) {

    }


        public Visit__c getVisit()
    {
        
        //Retrieve Audit Results based on Id parameter of this page
        return [Select Id,
                Visit__c.Account__c,
                Visit__c.Contact__c,
                Visit__c.Visit_Date__c,
                Visit__c.Pre_audit_score__c,
                Visit__c.Workshop_Score1__c,
                Visit__c.Total_3_0v2__c,
                Visit__c.Total_4_0v2__c,
                Visit__c.Total_5_0v2__c,
                Visit__c.X1_0__c,
                Visit__c.X2_0__c,
                Visit__c.X3_0__c,
                Visit__c.X4_0__c,
                Visit__c.X5_0__c,
                Visit__c.Total_Percent__c,
                Visit__c.Total_Audit_Score__c
                from Visit__c j
                where Id = 
:ApexPages.currentPage().getParameters().get('id') ];
    }
}

 My test class..

@isTest
private class ascSummaryTestClass {
     static testMethod void validateascSummary() {
         visit__c v = new visit__c (Account__c='001c000000Qm4kp', Contact__c = '003c000000N7Bl0');
         insert v;
        
          // Retrieve the contact from the visit
        v = [SELECT Contact__c FROM Visit__c WHERE Id =:v.Id];
    System.debug('Contact after visit created: ' + v.Contact__c);  
    }
}

 

 

  • September 04, 2013
  • Like
  • 0

Hi,

 

 I have a small doubt,

 

1) I am building a site for a exam which is internal to the orgn , How to restrict the site based on organisation ip,

 

2) The site should to be visible only to specific ip (within orgn)

 

Please tell me how to do it

 

Thanks in advance

Hi!

 

This is really annoying me now. I am unable to deploy my code into our client org because of the above error from a test class that tests webservices. HOWEVER, the tests pass when I run them individually as well as when I run all Apex tests!

 

Any ideas what's going on?!

I have a trigger written that updates a field on an Opportunity based on whether or not another field is null. The trigger is firing, but it seems to be firing twice? 

 

For example, what I would expect to see is if the Opportunity meets the criteria (VersionType__c == 'Change Request' && ApprovalStatus__c == 'Approved' && ChangeTag__c == 'null') and AdServer__c != null and Retargeting__c!=null, then the ChangeTag__c field would update to say 'Ad Server Change; Retargeting Change'. However, it updates to 'Ad Server Change; Ad Server Change; ReTargetingChange; ReTargetingChange". 

 

I cannot figure out why this would be happening. The System debug for the ID List returns only 1 ID (like it should). Any ideas what is happening here? Thank you!

 

Here is the code:

trigger ChangeTagOpp on Opportunity (after update) {

//(1) define variable for list of all ChangeRequestIDs (2) that are approved

List<ID> ChangeRequestIDs = new List<ID>();
    for(Opportunity crOpp: trigger.new){
    if(crOpp.versiontype__c =='Change Request' && crOpp.ApprovalStatus__c =='Approved'&& crOpp.ChangeTag__c==null){
        ChangeRequestIDs.add(crOpp.id);
        }
        System.debug('*************Opps in ID List**********' + ChangeRequestIDs);
}
//(3) get ids and field for change request forms
List<Opportunity> changerequests = new List <Opportunity> ();
for (Opportunity crOpp:[SELECT ID, AdServer__c,ReTargeting__c, ChangeTag__c 
                      FROM Opportunity
                      Where ID in: ChangeRequestIDs]) {                 

//(4) select Change Tag reaons based on fields completed on change request form
    if(crOpp.AdServer__c !=null){crOpp.ChangeTag__c +=';Ad Server Change';}
    if(crOpp.Retargeting__c!=null){crOpp.ChangeTag__c+=';ReTargetingChange';}
    crOpp.ChangeTag__c = crOpp.ChangeTag__c.replaceAll(';?null;?',' ');
    
    changerequests.add(crOpp);

//(5) update Change Tag field on approved change request forms
}
update changerequests;
}

 

I have a page that iFrames another site and uses a simple class to get the URL and userid.  I changed the class to use the Custom Settings for the URL instead of hardcoding it into the code.  It works; but I get the following error when running the test:  Message:  System.NullPointerException: Attempt to de-reference a null object.  Stack Trace:  Class.clsPMNotes.<init>: line 14, column 1 Class.clsPMNotes.testPMNotes: line 20, column 1

 

It looks like this "PmNotesSite__c.getInstance('DefaultSiteName').Site__c" is the culprit.

 

Here's the class

 

public class clsPMNotes
{
    public string prpIFrameSourceURL {get;set;}
    public clsPMNotes()
    {
         prpIFrameSourceURL = PmNotesSite__c.getInstance('DefaultSiteName').Site__c + Userinfo.getUserId();
    }
    
    public static testMethod void testPMNotes()
    {
        Test.StartTest();
        clsPMNotes obCLS = new clsPMNotes();
        Test.StopTest();
    }
}

 

Thanks much in advance.

  • November 26, 2012
  • Like
  • 0

Hi folks,

 

I'm trying to limit the batch size on one of my scheduled batch jobs, and adding a scope parameter on my Database.executeBatch doesn't seem to be working.  Here's my code:

 

batchGenerateOriginalCS cCases = new batchGenerateOriginalCS();
       
cCases.query='SELECT Id, Some_other_fields__c From Case where Some_other_fields__c = 'A string' limit 16';

ID batchprocessid = Database.executeBatch(cCases, 15);

 

So as you can see, I'm testing this by limiting my query to 16, but have (tried to) set the scope on my executeBatch to 15. When I run this bad boy, it runs my batchGenerateOriginalCS class as it ought to, but on 16 cases rather than on 15.

 

Any thoughts?

 

Thanks!

Charlotte

Hi Everyone,

After banging my head against the desk repetedely for the past few days I decided to see if any of you wonderful people in the community could help me out with an issue I am having.  A little backstory....my project has two pages, the first to select a recipe and then the second to pass recipe yield multiplier with the recipe Id to the second visualforce page that pulls the ingredients.  On this second visualforce page, I want the value they enter (that gets passed to the next page) double, triple, etc the ingredients actual amount.  For example: to make an egg sandwich, the base yield requires one egg.  To make three egg sandwiches, (Base 1) * (Multiplier 3 )=3

 

Listed below is the output based on the parameters passed in the url:

 

3.0 * 123 Cup Onions 1/4" Diced
3.0 * 123 Cup Green Bell Pepper 1/4" Diced
9.0 * 123 Cup Scramble Egg Mix
3.0 * 123 Cup Cheddar Cheese, Shredded

 

123 is what I am passing from the first page, and the * is added into the apex repeat

 

<apex:pageBlock title="Multiplied Ingredients">
<apex:repeat value="{!Ingredients}" var="Ingredient">
<tr>
<td align="right"> 
<apex:outputText value="!Ingredient.Amount__c} * {!YieldMultiplier}"/></td>
<td align="right"><apex:outputField value="{!Ingredient.Unit__c}"/></td>
<td align="right">
<apex:outputField value="!Ingredient.Ingredient__c}"/></td><br/>
</tr>
</apex:repeat>
</apex:pageBlock> 

 and here is the query

public string YieldMultiplier {get;set;}

//Get Ingredients
public List<Ingredients__c> getIngredients()

     {
List<Ingredients__c> outIngredients = new List<Ingredients__c>();
            outIngredients = [select Unit__c, Amount__c, Ingredient__c, Recipe__c, Multiplied_Amount__c 
FROM Ingredients__c 
WHERE Recipe__c = : ApexPages.currentPage().getParameters().get('id')];
            
for (Ingredients__c ar : outIngredients)  {
     
// ar.Amount__c = decimal.valueOf(ar.Amount__c) *= YieldMultiplier;
// not sure if this is needed       
     }
     return outIngredients;

}

 Any help would be greatly appreciated!!

  • October 19, 2012
  • Like
  • 0

Our company is in the process of trying to create and license our software.  One of the issues that I'm having is providing in such a way that the licensee can customize it.  For example, we have pages that include our company's name on it.  What I'm trying to do is allow the customer to change that particular item.  However, because we're distributing the application as a managed package, the client is unable to modify anything.  I've tried using custom labels, but the same issue occurs.  Once the manage package is deployed in a client's org, the labels become read-only.  The only thing that I've come up with would be a cusom object, and that complicates things considerably.  For example, for a custom label, a Visualforce page would simply use {!$Label.Company_Name} as the reference.  If I use a custom object, then it's not as simple and would actually cause a SOQL query on each page load.

 

My question is:  Is there any "best practice" in a managed package  that allows a client to customize certain aspects of the application?

 

Thanks in advance.

I want to tidy up my triggers and follow a best practice I learned of at Dreamforce X. I learned that is is better to have just one trigger of one type (Before Insert, Before Update.. etc.). This way you can have control over the order of execution and just makes for less clutter.

 

I am trying to move all my trigger code to apex class methods and just call them from the trigger passing in the trigger.new, trigger.old objects (where applicable) as arguments. Seems easy and I've seen many articles on-line on this very subject. The problem is none of these articles show me how to use the trigger object that is passed to the method. Just the template. I need to iterate through the trigger in the method to make it work but in the for loop I get a save error when trying to save the class: (Save Error: Loop variable must be of type Object). Can someone help me figure out why? Thanks!

 

I get the error on line 18: "for (Asset a : newTrigger)" of the following code example.

 

public with sharing class My_TriggerHandler 
{

    private boolean m_isExecuting = false;
    
    public My_TriggerHandler(boolean isExecuting)
    {
    	m_isExecuting = isExecuting;
    }

    public boolean IsTriggerContext
    {
        get {return m_isExecuting;}
    }

    Public void AssetBeforeInsert(object[] newTrigger)
    {
        for (Asset a : newTrigger) 
        {

        }
    }

}

 

Hi everyone,

 

I have a question about my Apex controller below. I'm having major problems getting my AggregatedResults list to work. Ultimately, I want a list that I can reference in a custom visualforce component. I am an admin, not a developer, so I am sure that I've messed up something that is pretty simple. I don't get any errors or anything, it's just that nothing shows up in the visualforce email template where data from this list should be displayed. The last 10-15 lines of code are the ones of interest. Any help is very much appreciated! Thanks!

 

public class TeacherlistatSchoolX2{


    public Id thisContactId {get;set;} 
    private List<Teacher_Implementation__c> Teacherlist;
    private List<Class_Implementation__c> Classlist;
    private List<AggregateResult> Metriclist;
    
    public List<Teacher_Implementation__c> getTeacherlist() {
        if (Teacherlist == null) {
            Teacherlist = 
            [SELECT Id, Name, School_Implementation__r.Name, School_Implementation__r.Principal_Name__c, 
            School_Implementation__r.Id FROM Teacher_Implementation__c 
            WHERE School_Implementation__r.Principal_Name__c = :thiscontactid];
        }
        return Teacherlist;
    }
    
    public List<Class_Implementation__c> getClasslist() {
        if (Classlist == null) {
            Classlist = [SELECT Id, Name, Teacher_Implementation__r.Name, 
            Teacher_Implementation__r.Id, Grade__c
            FROM Class_Implementation__c 
            WHERE Teacher_Implementation__r.id IN :getTeacherlist()];
        }
        return Classlist;
    }
  
    public List<AggregateResult> getMetriclist() {
    if (Metriclist == null) {
    AggregateResult[] Metriclist =
        [SELECT AVG(A__c), AVG(of_scheduled_time_online__c), AVG(Hours_Online__c), Start_Date__c,
        MIN(Class_Implementation__r.Name), MIN(Class_Implementation__r.Id), MIN(Class_Implementation__r.Date_of_previous_admin_email__c), MIN(class_grade__c)
        FROM Class_Metric__c
        WHERE Class_Implementation__r.Id IN :getClasslist()
        GROUP BY Start_Date__c];
    }
        return Metriclist;
    }
}

 

  • September 25, 2012
  • Like
  • 0

Hi,

   I have  the following Apex Page where the form shouldn't submit if there is any validation error.

 

<apex:page showHeader="false" sidebar="false" standardController="Lead"
    extensions="Beneficiary">


    <h1>NGO membership form</h1>

    <apex:form id="myform" styleClass="standard-form"
        enctype="multipart/form-data">

        <apex:outputText value="Organisation" />
        <apex:inputText value="{!Lead.Company}" label="Organisation"
            required="true" id="organisation" />
        <br></br>
        <apex:outputText value="Email" />
        <apex:inputText value="{!Lead.Email__c}" label="Email" required="true"
            id="email" />
        <br></br>
        <apex:outputText value="LastName" />
        <apex:inputText value="{!Lead.LastName}" label="LastName"
            required="true" id="lastname" />
        <br></br>

        <apex:commandButton value="Submit" onclick="validate()" immediate="false"/>
    </apex:form>


    <script>
function validate()
{

    var a = document.getElementById('{!$Component.myform.lastname}').value;
    if(a == null || a.length == 0)
    {
         alert("Last name is a Mandatory Field");
         return null;
    }

}
</script>

</apex:page>

 

If the lastname is blank. I'm getting the validation error. But the form still submits. How to stop the form submission if there is any validation error?

I'm still pretty new at this, and I'm trying to add a PayPal button to my page.  The page gathers basic data - name, address, etc. - and the button should  open a new window onto the PayPal site (so that my website doesn't have any credit card numbers pass through it).  I've got the PayPal button HTML code, but don't know how to translate it on the visualforce page.

 

The PayPal HTML code is:

 

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">  
 
 <!-- Identify business to collect the payments. -->   
 <input type="hidden" name="business"  value="baird_1327341394_biz@leadgreen.org">  
 
<!-- Specify a Donate button. -->  
 <input type="hidden" name="cmd" value="_donations">  
 
 <!-- Specify details about the contribution -->   
 <input type="hidden" name="item_name" value="{!opp.name}">  
 <input type="hidden" name="item_number" value="Fall Cleanup Campaign">  
 <input type="hidden" name="currency_code" value="USD">   
  <input type="hidden" name="amount" value="{!opp.amount">   
 <input type="hidden" name="first_name" value="{!pcontact.firstname}">
 <input type="hidden" name="last_name" value="{!pcontact.lastname}">
 <input type="hidden" name="address1" value="{!pcontact.MailingStreet}">
 <input type="hidden" name="city" value="{!pcontact.MailingCity}">
 <input type="hidden" name="state" value="{!pcontact.MailingState}">
 <input type="hidden" name="zip" value="{!pcontact.MailingPostalCode}">
 <input type="hidden" name="email" value="{!pcontact.email">
 
 <input type="image" name="submit" border="0" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" alt="PayPal - The safer, easier way to pay online">  
 <img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >  
 
</form>

 I've tried translating into VF, but don't find any equivalent for elements like 'method = "post".'

 

So I'd appreciate your guidance on the approach I should take.

 

Baird

 

Hello.  I'm pretty new to triggers, and am somewhat stuck.  I'm trying to write a trigger that will look at tasks, and if they were created under a case, pull the Case Contact (WhoId) down onto the Task in the 'Name' field.  I have the first piece of logic working which checks to see if the task is related to a case.  When I get to the SOQL query, though, it always returns zero results.  I have tried looking over numerous examples and even hard-coding a case id that should work, but it still comes back empty.  Does anyone have any ideas?  Any assistance would be appreciated, and thanks in advance. Here's the trigger:

 

trigger UpdateCaseTask on Task (before insert, before update)
{

  String tempId;
  String contactId;
  String recType;
  List<Task> newValues = trigger.new;
  List<Id> caseIds = new List<Id>();
  List<Case> caseData = new List<Case>();
  Map<Id,Case> caseMap = new Map<Id,Case>();
  Boolean haveCases = false;

 

// This for look checks the tasks to see if they are tied to a case
for (Task newValue: newValues){
  tempId=newValue.WhatId;
  if(tempId.substring(0,4)=='500R') {
    caseIds.add(tempId);  
    haveCases = true;
    }   
}
// If we have activities that are tied to cases, query for the case information
if (haveCases) { 
       caseData=[Select Id,ContactId,RecordTypeId from Case where Id in: caseIds];
       for (Case c:caseData) {   
           caseMap.put(c.Id,c);
           }  
}    
// Rebuild the list of tasks that need updates   
   for (Task newValue: NewValues) {
       tempId=newValue.WhatId;
       contactId=newValue.WhoId;
 system.debug ('trying to update Task '+caseMap.get(tempId).ContactId);  
 system.debug ('filling in task');  
       if(tempId.substring(0,4)=='500R') {
           contactId=caseMap.get(tempId).ContactId;
       }
      }
}

Hello,

 

I have such code:

List<Contact> retContacts = [FIND :txtName IN ALL FIELDS RETURNING Contact(Id, Name,Phone,Email)][0];

 

This code works and gives me few results when I am running it through a visualforce page. I need to upload my app for which I require min 75% code coverage, so I wrote test class which has:

mainObj.txtName = 'man*';
mainObj.SearchRecord();

 

It shows me only 57% code coverage and when i see test results I find the coverage is not going inside loop I have to process found results, in other words no results are returned.

 

If I use such statement it works and give perfect code coverage but I dont want to use this statement because it just searches Name field:

queryname = '%' + txtName + '%';

retContacts = [SELECT Id, Name,Phone,Email FROM Contact WHERE Name like :queryname];


Can anybody please help?

 

Thank you,

Nishant

http://nanostuffs.com/

Hi

 

Here is my code.

 

 

  list<Contact> ContactMap1=[Select Id,Email from Contact where Email IN :EmailSet1];
       for(Contact k:ContactMap1){
          Map_Contact_To_Id.put(k.Email,k.Id);
        }
      list<Campaign> theCampaign = [SELECT Id, Name FROM Campaign WHERE Name IN :CampaignList OR Id IN :SfCampaignList];
      
      for (Campaign k:theCampaign) {
       Map_CampaignName_To_Id.put(k.Name,k.Id);
       Map_CampaignId_To_Id.put(k.Id,k.Id);
      }

      for (CnP_Transaction__c c : Trigger.new) {
      if(c.sf_Campaign__c == null)
          c.sf_Campaign__c=Map_CampaignName_To_Id.get(c.Campaign__c);
      }
 
      list<CampaignMember> ListMemebers=new list<CampaignMember>();
           CampaignMember CreateMem=new CampaignMember();

    for (CnP_Transaction__c c : Trigger.new) {
    
     campMembers(c.sf_Campaign__c);
     if((c.sf_Campaign__c!=null || c.Campaign__c!= null)&&Map_CamId_ConId.get(c.sf_Campaign__c)!=c.Contact__c){
        CreateMem = new CampaignMember(Campaignid=Map_CampaignId_To_Id.get(c.sf_Campaign__c), Contactid=c.Contact__c, Status='Received');
          Map_CamId_ConId.put(Map_CampaignId_To_Id.get(c.sf_Campaign__c),Map_Contact_To_Id.get(c.Email__c));
          ListMemebers.add(CreateMem);
     }
    }

     if(ListMemebers.size()>0){
       insert ListMemebers;       
       }
 
       public void campMembers(String CampaignId1){
 
 List<CampaignMember> campmem = [select contact.Email,Campaignid,Contactid from CampaignMember where CampaignId!=null];       
         for(CampaignMember cm :campmem){
         if(cm.CampaignId == CampaignId1)
            Map_CamId_ConId.put(cm.ContactId,cm.CampaignId);

         }

 

        

 

One of my client getting the following error because of my code:

 

Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CnP_PaaS.addCorresCont: execution of BeforeInsert

caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows)

 

Consider an index filter.

 

My doubt is they are getting the error because of that query(which is in bold).

 

How can I solve that??

 

Please help

 

Thanks

Anu

Hey all,

 

I'm trying to send some GET data to an external server after a product gets updated.  I have both the trigger and class created to the point that I think it should work, but something is going wrong.  I'm getting the error: Method is not visible: httpSendtoService.sendFunc(String). I realize this must mean that this has something to do with scope and the fact that my class is defined as global, but I was under the impression that this was the correct way to define it in order to declare a @future function.

 

Here's my trigger:

trigger httpTest on Product2 (after update) {
		
	string toSend = 'Product';
	
	httpSendtoService.sendFunc(toSend);
	
}

 

 

 And my Class:

global class httpSendtoService {
	@future (callout=true) static void sendFunc(string which){
		
		Http connect = new Http();
		HttpRequest req = new HttpRequest();
		
		req.setMethod('GET');
		req.setEndpoint('http://domain.com/tests/SalesForce-HTTP-Requests.php?Data=' + which);
		
		HttpResponse res = connect.send(req);
		
	}
}

 

 

On a related note, I would prefer to send this data via POST, rather than GET, but I can't seem to find how to structure the data.

 

Any Ideas?

 

Any help would be greatly appreciated,

Josh

 

  • December 28, 2011
  • Like
  • 0

Hi, I know this will have been posted before but I have quite a complicated issue here (for me cos I'm new to Force dev) that I'd like to share with you guys to see if there is anything I am missing.

 

I have a requirement for a bulk upload of records from another system that will be uploaded using the DataLoader from a csv file. No problem so far, have that covered and working.

 

The problem is that there may or may not be lookup field values in the file rows that can be used to form relationships within the SalesForce system and if so they need hooking up on import.

 

So this means that somehow, for every line of the import record I need to look at an Account record to see if certain values match. If not I then need to link the import record to know values for dummy Account objects marked as "UNKNOWN".

 

The spec is they want a trigger to do this and I have come up with three possible solutions, all of which run into Governor Limits pretty quickly. I cannot find a way of having any more than 99 records in the import file at a time?

 

OK so here is my code for each solution. I'd like you to cast your eyes on the code and see if there is anything simple that I have missed that would allow me to do this without running into the Governor Limits.

 

Here's the code...

 

First idea I had was to use a MAP so I would get a list of Accounts in one hit. From there I'd go for a match on Account Id. Unfortunately I have only one AccountId in the file(possibly). The other numbers are from a legacy system so I can only match on those which means using SOQL?

 

trigger customUpload on Custom__c (before insert, before update) 
{
	

// Map for THE MAP WAY //

Map<Id,Account> accountMap = new Map<Id, Account>([select Id,  Customer_Number__c from Account]);




	
	for (Custom__c customObj : trigger.new)
	{
				
		
		/*###################################################################################################################################################################################*/
		/*																																																																																										*/
		/*THE MAP WAY - it only solves on problem partially in that we can easily look for a match on Id in the MAP. However, we can only have a MAP of the form <Id,SOBject> in other 
		/* words, we can only use an actual Id to search on Account key field. We only have a key field for one attribute which is Lookup1__c or Lookup1 in the import file. Another issue is that this works
		/* by relying on catching exceptions which are thrown when no match shown. Don't like doing that but still works.
		/
		/* SOLUTION if using this method would be to ensure that instead of Lookup2 and Lookup3 in the import file we actually have SalesForce Ids as Lookups that we can use to get matches from the 
		/* map using those Account Numbers for Lookup1 and 2 e.g. instead of Lookup2__c matching on Account.Customer_Number__c we match on Lookup__c (an Account number due to it being a lookup). I do not know if this is possible though...
		/*   
		/* AT 100 ROWS ON INPUT FILE THIS FAILS WITH TOO MANY SOQL QUERIES                                                                                                                   */
		/*###################################################################################################################################################################################*/
		
		
		try
		{
			Account Lookup1Match = accountMap.get(customObj.Lookup1__c);
			
		}
		catch (Exception e)
		{
			Lookup1Unknown();
		}
		
		
		// Cannot use this technique for the the other two because these are not SalesForce Ids and we can only build a map with an Id and an SObject to enable searches like this as far as I am aware.
		// Thus we have to resort to using SOQL queries...
		
		// Get the Account with the matching Lookup2__c to Account.Lookup2__c
		List<Account> Lookup2Match = [Select Id from Account where Customer_Number__c = :customObj.Lookup2__c];
			if (Lookup2Match.size() == 0)
			{
				Lookup2Unknown();
			}
		// Get the Account with the matching Lookup3_RID to the Account.Lookup3__c
		List<Account> Lookup3Match = [Select Id from Account where Customer_Number__c = :customObj.Lookup3__c];
			if (Lookup3Match.size() == 0)
			{
				Lookup3Unknown();
			}	
	
	
	}
	
	public void Lookup1Unknown()
	{
		system.debug('Lookup1Unknown');
	}
	
	public void Lookup2Unknown()
	{
		system.debug('Lookup2Unknown');
	}
	
	public void Lookup3Unknown()
	{
		system.debug('Lookup3Unknown');
	}	
	
	
	
}

 So I thought I'd try the SOQL way.... Just look for a match using SOQL for every line in the import file...

 

trigger testingUpload on Custom__c (before insert, before update) 
{
	






	
	for (Custom__c customObj : trigger.new)
	{
		// Get the Account with the matching Lookup1 to Account Id...
		
		
		/*###################################################################################################################################################################################*/
		/*THE SOQL WAY - runs into SOQL limits very quickly due to invoking the 3 queries for every line in file to insert */
		/* 
		/* FOR 100 LINES IN THE INPUT FILE THIS FAILS BY GOING OVER THE 100 LIMIT ON SOQL QUERIES.                                                                                */
		/*###################################################################################################################################################################################*/
	
		
		
		


		// Get the Account with the matching Lookup1__c to Id on Account...
		List<Account> Lookup1Match = [Select Id from Account where Id = :customObj.Lookup1__c];
			if (Lookup1Match.size() == 0)
			{
				Lookup1Unknown();
			}
		
		// Get the Account with the matching Lookup2__c to Account.Lookup2__c
		List<Account> Lookup2Match = [Select Id from Account where Customer_Number__c = :customObj.Lookup2__c];
			if (Lookup2Match.size() == 0)
			{
				Lookup2Unknown();
			}
		// Get the Account with the matching Lookup3_RID to the Account.Lookup3__c
		List<Account> Lookup3Match = [Select Id from Account where Customer_Number__c = :customObj.Lookup3__c];
			if (Lookup3Match.size() == 0)
			{
				Lookup3Unknown();
			}
		
	
	}
	
	public void Lookup1Unknown()
	{
		system.debug('Lookup1Unknown');
	}
	
	public void Lookup2Unknown()
	{
		system.debug('Lookup2Unknown');
	}
	
	public void Lookup3Unknown()
	{
		system.debug('Lookup3Unknown');
	}
	
	
	
	
}

 As you can see, it runs into the 100 query limit pretty quick...

 

So then I thought I'd try the CODE way. Basically get an Account list in one hit using SOQL then loop through the list for every line in the input file. Yes I know, very innefficient! :-\

 

trigger testingUpload on Custom__c (before insert, before update) 
{
	

List<Account> accountList = new List<Account>([select Id,  Customer_Number__c from Account]);




	
	for (Custom__c customObj : trigger.new)
	{
		// Get the Account with the matching Lookup1 to Account Id...
		
		
		/*###################################################################################################################################################################################*/
		/*THE CODE WAY - runs into scripting lines over 200,0000 */
		/*###################################################################################################################################################################################*/
	
		
		for (Account acct : accountList) 
			{
				
				
				if (customObj.Lookup1__c == acct.Lookup1__c)
				{
					
					customObj.Lookup1__c = acct.Id;				
				}
				else 				
				{
					
					lesseeUnknown();
				}
				
				
				if (customObj.Lookup2__c == acct.Lookup2__c)
				{

					customObj.Lookup2__c = acct.Id;				
				}
				else
				{
					
					shipperUnknown();
				}
				
				
				
				if (customObj.Lookup3__c == acct.Lookup3__c)
				{
					
					customObj.Lookup3__c = acct.Id;
				}
				else
				{
					Lookup3Unknown();
				}
			}
		
	
	}
	
	public void Lookup1Unknown()
	{
		system.debug('Lookup1Unknown');
	}
	
	public void Lookup2Unknown()
	{
		system.debug('Lookup2Unknown');
	}
	
	public void Lookup3Unknown()
	{
		system.debug('Lookup3Unknown');
	}
	
	
	
	
}

 I would be very grateful if someone could point me in the right direction with this one. It seems I can get code that works but not for many input file lines... The requirement is to eventually automate this process you see so the uploads are done unattended.

 

My thoughts are that it's asking a trigger to do a lot of work BUT this is what the client specified. I value your thoughts on this.

 

Thanks and regards,

 

Ian

How can I call the Contact records I'm creating in my test class?  How can I write a systeAssertEquals on the records that are inserted after the batch is ran?  Below is my test class, but it's throwing an error message that says the variable testcon does not exist when I try to query the contact that it is in the test class:

 

@istest
private class testBatchReferrals {

/*
Purpose: - This is the test method to test the batchReferrals class to ensure it runs properly
- Within this test class
- an account and 2 contacts are created.
- referral entry records are created based off the amount of similar Referral Physicians and MRN's there are in that month
- the batch process takes place
- the result will be 2 new referral entry summary records created that count the similar records for each month.


*/

static testmethod void testBatch(){
Test.startTest();

list<Account> accs = new list<Account>();
Account a1 = new Account(Name = 'test account1');
accs.add(a1);

list<Contact> testcon = new list<Contact>();
Contact c1 = new Contact(FirstName = 'test contact1',  AccountId = a1.Id);
Contact c2 = new Contact(FirstName = 'test contact2', AccountId = a1.Id);
testcon.add(c1);
testcon.add(c2);

list<Referral_Entry__c> testrefent = new list<Referral_Entry__c>();
Referral_Entry__c r1c1 = new Referral_Entry__c (Name = 'test referral 1 con 1', Referring_Physician_del__c = c1.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r2c1 = new Referral_Entry__c (Name = 'test referral 2 con 1', Referring_Physician_del__c = c1.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r1c2 = new Referral_Entry__c (Name = 'test referral 1 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r2c2 = new Referral_Entry__c (Name = 'test referral 2 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c exsum = new Referral_Entry__c (Name = 'test summary referral 1 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), Count_of_MRN__c = Decimal.Valueof('2'));
testrefent.add(r1c1);
testrefent.add(r2c1);
testrefent.add(r1c2);
testrefent.add(r2c2);
testrefent.add(exsum);


batchReferrals batch = new batchReferrals();
batch.contactquery = 'select Id from Contact where Id in :testcon';
ID jobId = Database.executeBatch(batch, 2);
Integer t = [Select count() from Referral_Entry__c where Count_of_MRN__c != Null Id in :testrefent];
system.AssertEquals(0, t);  - The size of this should be 6 (4 of the existing Referr_Entry__c records plus the 2 new summary Referral_Entry__c records.  The existing summary record listed above will be deleted since there is a value in the Count_of_MRN__c field.
Test.stopTest();

 

}

}

 

 

 

I'm getting 75% coverage, but I want to do some system asserts on the Referral Entry object to ensure there are actually 2 records created that have a value in the Count_of_MRN__c field once the batch is complete.

I amtrying to write a test class for Contacts code with ReportsTo completed

The code creates a single contact (ignore the test factory piece) and then creates a second contact reporting to the first.

The first and second contacts are created, but the ReportsTo is null on the second.

Contact con1 = Test_Factory.CreateContact();
con1.AccountId = tt.testADP.Customer__c;
con1.Contact_Post_Code__c = 'WR5 3RL';
insert con1;
Contact con2 = Test_Factory.CreateContact();
con2.AccountId = tt.testADP.Customer__c;
con2.Contact_Post_Code__c = 'WR5 3RL';
con2.ReportsTo = con1;

 I have tried the variationbut that no longer works

con2.ReportsToId = con1.Id;

There was a similar issue raised:

http://boards.developerforce.com/t5/Apex-Code-Development/Trigger-not-updating-Contact-RelatedTo-field-with-no-reason-why/m-p/209732/highlight/true#M37146

That shows a work around, however this is for a test class so cannot really work around.

Are there problems writing to this field via Apex or have a i got something wrong.

Any help much appreciated.

  • November 21, 2011
  • Like
  • 0

If I use the code below, and click the button, instead of getting the expected error (Error: You must enter a value) and stopping the process, I instead get this error:

 

System.FinalException: SObject row does not allow errors

 

But if I comment out the line in bold in the controller, and use the more typical syntax on the line below (commented out), it works just fine. Is that expected behavior, or should I be doing something different to make it work?

 

When I use the first version, and I do enter a name, it does save the Campaign correctly though, which suggests the object is being create properly?

 

<apex:page controller="campTest">
<apex:form >
<apex:pageBlock>
<apex:pageBlockSection columns="1">
<apex:commandButton action="{!CreateandAddCampaign}" value="Test"/>
<apex:inputField required="true" value="{!newCampaign.Name}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
 
</apex:page>

 

public with sharing class campTest {

public Campaign newCampaign;

public Campaign getnewCampaign () {
if (newCampaign == null) {
newCampaign = (Campaign)Campaign.sObjectType.newSObject(null, true);
//newCampaign = new Campaign();
newCampaign.IsActive = TRUE;
}
return newCampaign;
}

public PageReference CreateandAddCampaign () {
insert newCampaign;
return null;
}

}

 

I have a sites page, and it seems to work fine. It has a custom controller that retrieves some data from a custom object and the Contact object, displays the info to the user, and lets them submit an updated version to the data into another custom object. 

 

But after a certain amount of time (24-48 hours), when I go to the page I get a 'Not Authorized message'. After much testing, and thinking it was a a problem with css/statis resources, I have now found that the problem seems to be with the controller (i.e. a age with no references to css/static resources still fails)

 

When I get the error, I can login to SF and simply view the apex controller class in the usual Setup - Develop - Classes interface, and the public sites page then works again for another 24-48 hours. 

 

What am I missing here?

I'm thinking I have an issue with caching but can't work out what it is...I have a Sites page (key code below) that works now, but I know that when I try and access it tomorrow morning, it will throw an 'Authorized Only' error to the person trying to access it via the Sites page.

 

Then, if I sign into SF, I can access the page via the internal /apex/pagename link, and from then on the Sites page also works fine until the next morning, when the problem occurs again. What I am missing?

 

<apex:page standardController="Nomination2__c" extensions="NominationAcceptanceExtension" standardStylesheets="false" showHeader="false" sidebar="false">

  <apex:stylesheet value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
  <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" />
  <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" />
  
<!--Multi Select Functionality based on this post:
http://www.tgerm.com/2012/01/ipad-multiselect-picklist-jquery-plugin.html
-->
   
  <apex:includeScript value="{!URLFOR($Resource.twinBoxMultiSelectList, 'uiPickList.js')}"/>
  <apex:stylesheet value="{!URLFOR($Resource.twinBoxMultiSelectList, 'uiPickList.css')}"/>


<!--    Additional style sheets stored in VF Components -->
    <c:ACYPlWebCSS />
    <c:NominationACSS />
    
<script type="text/javascript">
       var j$ = jQuery.noConflict();
 
       j$(document).ready(function(){
           j$("#accordion").accordion({ autoHeight: false, collapsible: true });
           
           j$('[id$=travelavail]').twinBoxMultiSelectList({
                            availableList : 'span[id$=availabletravelContactsContainer]',
                            selectedList : 'span[id$=selectedtravelContactsContainer]',
                            styles: {
                                width: '220px'
                            }
                        });
           
              
             j$().css('font-family', 'Verdana,Arial,sans-serif');
             j$('#dialog').hide();
                              
        });
        
        function openlanguages () {
     
                   j$("#dialog").dialog({
                   modal:false,
                   closeable:false,
                   resizeable:false,
                   width:440,
                   overlay: {opacity:0.5, background:"black" },
                   title: 'Language Proficiency'       
                   });
                   
                   }
       
        function closelanguages () {
     
                   j$("#dialog").dialog('close');
                   
                   } 
     </script>    

<title>Nomination Acceptance</title>

    <header id="header" role="banner">
        <div class="upPanel">

=====The rest is just standard VF/HTML====

 

 

I have a scenario where a user will upload documents to Chatter for a Case, and then send an email regarding that case, with links to the uploaded files, to some contacts linked to the case via a Custom Object.

 

So I would like to be able to access those links, and either store them, or build an email template on the fly...but although I can see the uploaded items in the feedpost object, and can access them via the ContentDocumentLink object, I can't see anywhere the link that is created that you can access via the UI to send to someone to share outside the Org.

 

Are the links accessible via APEX?

There was an earlier unanswered post about this, but hopefully someone has found a fix since August...

 

I created a Config Only Sandbox, and loaded some data...all seems fine. I go to the Chatter Groups, and they aren't there - so I assume they don't get brought over into the Sandbox. So I then try to re-create a group I use in some of my batch processes, but it won't let me create it...says it's a duplicate name...? But when I run a simple query in SOQL against Colloboration Groups, it comes back empty...

 

What I am missing? 

My understanding of the Summer release was that a Long Text / Rich Text fields shared one big pool of characters up to 1.6 million.

 

So I have a Rich Text field I'd like to extend, but it says my Max Available is 32,768 even though I only have one other long text field of 1000 chars on the object, and the help text says I have 1.5+ million chars available.

 

Any idea what I need to do to enable me to take advantage of the extra characters?

 

Thanks

I've had success using REST based web services that return XML but I am having more difficulty with this one, so was hoping someone could guide me in the right direction. The service I am calling is an asmx service with one method GetService() that expects to receive an XML file. I parsed the WSDL and received the following, but can't work out what I should be setting the xmldoc variable that is declared as a xmldoc_element to...a DOM.Document, XMLNode List, or something else entirely...? Thanks

 

 

//Generated by wsdl2apex

public class KWD1 {
    public class xmlDoc_element {
        private String[] apex_schema_type_info = new String[]{'http://localhost/','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
    public class GetService_element {
        public KWD1.xmlDoc_element xmlDoc;
        private String[] xmlDoc_type_info = new String[]{'xmlDoc','http://localhost/','xmlDoc_element','0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://localhost/','true','false'};
        private String[] field_order_type_info = new String[]{'xmlDoc'};
    }
    public class XMLServiceSFIntegratedSoap {
        public String endpoint_x = 'http://www.test.com/Services/XMLServiceSFIntegrated.asmx';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'http://localhost/', 'KWD1'};
        public String GetService(KWD1.xmlDoc_element xmlDoc) {
            KWD1.GetService_element request_x = new KWD1.GetService_element();
            KWD1.GetServiceResponse_element response_x;
            request_x.xmlDoc = xmlDoc;
            Map<String, KWD1.GetServiceResponse_element> response_map_x = new Map<String, KWD1.GetServiceResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'http://localhost/GetService',
              'http://localhost/',
              'GetService',
              'http://localhost/',
              'GetServiceResponse',
              'KWD1.GetServiceResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.GetServiceResult;
        }
    }
    public class GetServiceResponse_element {
        public String GetServiceResult;
        private String[] GetServiceResult_type_info = new String[]{'GetServiceResult','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://localhost/','true','false'};
        private String[] field_order_type_info = new String[]{'GetServiceResult'};
    }
}

 

 

 

 

 

 

Not sure what I am missing here - this seems simple enough...

 

I have a MVP Picklist field called Languages__c. I want to split the field into a String List using ';' as the split. But when Languages has more than ten entries, ther debug shows me that the List contains the first ten, and then the characters  ', ...)'

 

What I am missing here? What can I do to make sure all the values end up in the array?

 

 

public class cSearch{
        Public String [] languagesvalue{get;set;}    
         
        
        //This is the contructor method to build the search filters
        public cSearch(Contact con,Contact formatch){ //set search fields = values on contact being searched           
                   
            languagesvalue = new String [] {} ;
            if (con.Languages__c != null) {
            String [] sissues = con.Languages__c.split(';');
            for (String s: sissues) {
            languagesvalue.add('\'' + s + '\'');
            }           
            }

 

 

Just trying out the new Spring 11 functionality, and had a question I am hoping someone might know..

 

I can get field sets to work as input or output fields.

 

I can get Inline editing to work as advertised.

 

But is it possible to output a set of fields from a field set and have those fields enabled to use inline editing? I have tried to combine the various examples but with no success - is it possible and if so, can someone give me an example?

 

For instance, it looks from the Spring Webinar that this should work if I pass in a Contact Id into the page...

 

 

<apex:page standardController="Contact" >
<apex:sectionHeader title="Inline for {!contact.Name}"/>
<apex:form>
 
<apex:pageMessages/>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="2">
<apex:repeat value="{!$ObjectType.Contact.FieldSets.TestFS1}" var="f">
<apex:outputField value="{!Contact[f]}">
<apex:inlineEditSupport event="ondblclick"/>
</apex:outputField> 
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

 

 

Many thanks

I have a simple custom button in my Dev Org, that clones the current record, but also passes in a parameter into a custom fields e.g.

 

 

/{!mycustomobject__c.Id}/e?clone=1&retURL=%2F{!mycustomobject__c.Id}&00N500000023pHE=1

 

where 00N500000023pHE is the Id of the custom field.

 

When I package and deploy this though, the Custom field Id reference is not updated to reference the newly created custom field. Instead, it is still the same as the above...

 

Is there anyway to change the way I build this to enable me to package this button with a the parameters, but have them work with the fields in the target Org?

 

Thanks

 

So I am seeing some odd behavior with a Campaign/CampaignMemberStatus trigger

 

I remove the Standard Sent and Responded, and replace them with some new ones. But to avoid problems with cloning, I check to see if the Campaign already has my new custom values, and don't update cloned records...

 

So if the default value I use  is 'Added to Campaign', it fails...but if I change the new default to 'Added to the Campaign' (or as far as I can tell, any other phrase) it works just fine...

 

Is 'Added to Campaign' some special phrase I should be avoiding?

I feel this should be easy, but I'm just missing something...

 

I have a page header like this for page cmupdate, to update a Campaign Member Status

 

<apex:page standardController="CampaignMember" extensions="UpdateCampaignMemberClass" sidebar="false" showHeader="false" action="{!checkidvalid}" >

 The checkidvalid method is designed to be called by the page action to check if there is no Id (e.g. a merge failed in an email)

 

 

If the page is called like this, the user is correctly redirected to an error page

 

http://pnctest.staging.cs0.force.com/cmupdate

 

 

But if the merge failed, the page would more likely look like this:

 

http://progress.staging.cs0.force.com/cmupdate?id=

 

 

And then the error page is not called - you just get the {checkmanageability} reference in the debug logs...and a VF page error...

 

Anything I can do to catch this sort of error with an standard controller/extension construct?

 

 

Can someone confirm if this is expected behavior...?

 

I have a batch apex class that calculates a Contact's opportunity total and updates the contact record. It works fine, except I am seeing an odd error. This is an example of the SOQL I use, where ctotal is the instance of the Batch Apex Class.

 

 

ctotal.query = 'Select Id, total__c,(Select OpportunityId, Opportunity.StageName, Opportunity.Date_Received__c, Opportunity.Amount from OpportunityContactRoles where Opportunity.StageName = \'Collected\' Order by Opportunity.CloseDate ASC) From Contact WHERE Id = \'0034000000U842kAAB\'';

 

 

The contact I am filtering for has one Opportunity that matches the SOQL criteria, and if I submit this SOQL via the system log, it correctly returns on record.

 

But when I execute this in the Batch Context, it is returning two rows. Looking into it further, I discovered the second record is a deleted record, which only appears if I use the ALL ROWS parameter in the system log.

 

Do I need to filter my batch apex to disregard deleted rows, or should I be setting some other paramter, or is this a bug?

 

Thanks

 

Maybe I am missing something wth the new aggregrate functions, but should I be able to execute a simple query like this when the object has > 10,000 rows of data, or should I still be using the old 'order by closedate desc limit 1' syntax? Currently, I get an error saying the query rows returned is too large...

 

 

AggregateResult[] groupedResults = [Select max(closedate) maxcdate from Opportunity WHERE closedate != null]; system.debug('CheckDate' + groupedResults[0].get('maxcdate'));

 


 

I have a managed package with some custom page layouts for Accounts and Contacts. I've built an extension with some additional custom fields, and I would like to include those fields on the custom page layouts originally installed with the managed package.

 

I can add the custom fields to the extension package, and I can add the custom fields to the custom page layouts in the extension environment, but it seems I can't include the page layouts in the package for the extension. Is there anyway to also include those custom page layouts from the managed package in the Extension with the extra fields? Or do I just have to create new page layouts in the extension, and instruct the administrator to create new profiles that use these new enhanced page layouts when they install the extension?

I am trying to create an extension for a existing Managed-Released Package. I've installed the package in a Developer instance, and I created a new managed package. As I understand the docs, I should be able to select a component from the installed package, and that will make my new package an extension and dependant on the existing installed package

 

But when I try to select Components from the existing package for the new Package, none of the installed package are available to choose from, so I am thinking I just have missed step somewhere, but can't work out where...?

I am trying to remove my installed app from my test drive account, so I can installe a newer version. The app includes Record Types on th Contact object, and when I try and remove it, I get an error saying:

 

"This installed component is referenced by a locally created component: [Contact's Name]"

 

I thought I had updated all the data to not reference the record types in the package, but apparently not. The record is not in the recycle bin, and any attempts to undelete via the System Log are not working. How do I remove/updatet this record so it no longer references my package if it is apparently Permanently deleted?

 

 

Anyone else noticed this...I have a batch upload that uses Apex DataLoader...under version 16.0, it would happily truncate a text field if the value was too long.

 

This doesn't seem to work with version 17.0, either via the UI or Batch Interface. It just gives me an error saying String Too Long.

 

Does this need to be enabled differently in 17.0? It's checked in the UI, and I've tried placing it in various combinations of config files/process-xml files, all with no avail.

 

If anyone else could test their installation, and confirm that it's broken, or that it is my config that isn't working, I'd be most grateful!

 

 

I am trying to render a PDF using the <div style="page-break-after:always;"> </div> to createpage breaks across a set or repeating table tags. Is there anything I can do do avoid this happening?

 

PDF generation encountered problems with the layout of your page and couldn't complete because the request took too long. Possible reasons include blocking normal page breaks from rendering.

So I'm pretty sure this worked last week, but now doesn't...did something change with the new release...

 

This simple VF page still works:

 

<apex:page standardController="Position__c" title="Job Details" showHeader="false" standardStylesheets="false"> <apex:form > <!-- The site template provides the site layout and style --> <!-- Breadcrumb link back to the search page --> <apex:outputLink value="<- Back to Search" onclick="top.history.go(-1);return false;" /> <br/> <!-- Job details --> <apex:pageBlock> <h3><apex:outputField value="{!Position__c.name}"/></h3><br/><br/> </apex:pageBlock> </apex:form> </apex:page>

 

 But when I add in the apex:composition tag below, it breaks with the following error:

SObject row was retrieved via SOQL without querying the requested field: Position__c.Name

 

But the tags work fine on every other page - just not when I use a standard controller?

 

 

<apex:page standardController="Position__c" title="Job Details" showHeader="false" standardStylesheets="false"> <apex:composition template="{!$Site.Template}"> <apex:define name="body"> <apex:form > <!-- The site template provides the site layout and style --> <!-- Breadcrumb link back to the search page --> <apex:outputLink value="<- Back to Search" onclick="top.history.go(-1);return false;" /> <br/> <!-- Job details --> <apex:pageBlock> <h3><apex:outputField value="{!Position__c.name}"/></h3><br/><br/> </apex:pageBlock> </apex:form> </apex:define> </apex:composition> </apex:page>

 

 

 

 

In this apex class the logic is to update a custom lead field with a math.random() value.
public class leadRandomNumber {
	
	/* update lead status for leads related to the tasks */
    public static void updateRandomNumber (List<Lead> leadsFromTasks) {
    	
    	system.debug ('***** entering method leadRandomNumber.updateRandomNumber class *****');
    	
    	List<Lead> leadsToUpdate = new List<Lead>();
    	
    	List<Lead> leads = new List<Lead>([select Id, RandomNumber__c from Lead where Id IN :leadsFromTasks and Status='Attempting' and createddate = this_year and RandomNumber__c = null]);
    	system.debug('updateRandomNumber leads queried:' + leads.size());
    	// for leads related to the tasks apply a random number to the leads if they do not yet have one
    	for(lead ld: leads) {
    		if(ld.RandomNumber__c == null) {
    			Double rand = math.random();
    			ld.RandomNumber__c = rand;
    		}
    		leadsToUpdate.add(ld);
		}
		
		update leadsToUpdate;
		system.debug('updateRandomNumber leadsToUpdate: ' + leads.size());
    	
    }
    
}

This unit test verifies that inserting the task causes the logic in the apex class above to run and update the leads as expected.
 
/*
- For leads whose lead status was just updated as the result of an attempting call
- check that the random number was set
 */
 
@isTest
private class leadRandomNumberTest {

    static testMethod void insertAttemptingCall() {
    	
    	system.debug('Inserting outbound preview call tasks as a new logo rep...');
    	
    	User newLogoRep = [select id from user where isactive = true and profile.name = 'Inside Sales User' limit 1];
    	
    	QueueSobject smbQueue = [select queue.id from queuesobject where queue.name = 'SMB AE Queue'];
    	
    	Lead l = new Lead(Company='Company',LastName='Test',Phone='8885551234',Status='Open',LeadSource='Marketing', ownerid=smbQueue.queue.id);
        insert l;
        
        // bulk insert a list of calls related to the lead
        Task task = new Task(WhoId=l.Id, OwnerId=newLogoRep.Id, Type = 'Call', Five9__Five9CallType__c='Outbound Preview', Subject='Call Attempting', Status='Completed', Five9__Five9SessionId__c='fb3636336363', ActivityDate=date.today(), Five9__Five9HandleTime__c = '00:01:59', Five9__Five9WrapTime__c = '00:00:29');
        
        test.startTest();
        
        system.RunAs(newLogoRep) {
        	insert task;
        }
        
        system.debug('Asserting that the leads status was updated to Attempting and it now has a RandomNumber value...');
        
        Task insertedTask = [select Id, Status from Task where Id =: task.id];
        System.assertEquals('Completed',insertedTask.Status);
        
        // check that the lead was updated as expected
        Lead insertedLead = [select Id, Status, RandomNumber__c from Lead where Id =: l.Id];
        System.assertEquals('Attempting',insertedLead.Status);
    	System.assertNotEquals(null,insertedLead.RandomNumber__c);
    	
    	system.debug('random number set to: ' + insertedLead.RandomNumber__c);
    	
    	test.stopTest();
    
    }

}
However the test coverage for the apex class is only 56% as the updates inside the for loop are not covered.

code that needs coverage

What is the best practice for test coverage for the lines that are missing?
Hi all. My first question over here in the foreign climes of the dev boards - go easy on me, I am but a mere admin. :-)

I have written a trigger which stops an account being deleted if one of its field values is not null. This works as expected. I have written the test class, which is at 100% coverage but one of my asserts is failing. The asserts around the delete being blocked work fine - it is the negative case, where the field is null and so where the delete should go ahead, that is not working.

Here is my test class, with the delete and failing assert highlighted:
 
@IsTest
public class PreventAccountDeletionTest {

    private static testMethod void testDeleteSuccess()
    {
           Account acc=new Account(Name='Test Account');
           insert acc;
           
           System.assertNotEquals(acc.Id, null);
           System.assertEquals(acc.Some_Field__c, null);

           delete acc;
                 
           System.assertEquals(acc.IsDeleted, true);
        }

    private static testMethod void testDeleteFail()
    {
           Account acc=new Account(Name='Test Account', Some_Field__c='ABCDEFGHIJKLMNOP');
           insert acc;
  
           try
           {
              delete acc;
              // should throw an exception - the following assertion will cause an error if the code carries on
              System.assert(false);
           }
           catch (DMLException e)
           {
               // expected
               System.assert(e.getMessage().contains('You cannot delete an Account which is linked to the external system.'));
           }
        
        System.assertEquals(acc.IsDeleted, false);
        
    }

}

Any suggestions? Is there something I don't know about deleting in a test class? As the record is (hopefully) in the recycle bin do I need to use something like the equivalent of ALL ROWS? Or any other obvious thing that I'm missing?

Oh and let me know if you want to see the trigger code. Many thanks in advance!
/*
 * **Created by Jack Wang 9.24.2014
*/
global class AR_Creating75DummyNML implements Database.Batchable<sObject>{
    
    static final Integer numofNML=75;
    global final String query;
    global AR_Creating75DummyNML(String q)
    {
        query=q;
    }
    
    public List<Task> createNML(List<ID> IDs)
    {
        integer size=IDs.size();
        List<integer> ints=new List<integer>();
        
        Integer numberDays = date.daysInMonth(Date.today().year(), Date.today().month());
        for(integer i=0;i<75;i++)
        {
            double k=Math.random()*size;
            ints.add(k.intValue());          
        }
        
        
        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Task> tsks=new List<Task>();
        for(Integer i : ints)
        {
            double datek=Math.random()*numberDays;
            Task nml=new Task(ownerid=userid,CallType__c='NML',whatid=String.valueOf(IDs[i]),Subject='NML',
                              Status='Completed',Priority='Normal',ActivityDate=Date.today().tostartofMonth().addDays(datek.intValue()));
            tsks.add(nml);
        }
        return tsks;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {        
        return Database.getQueryLocator(query);        
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        
        Map<String,List<ID>> territoryClientIDMap=new Map<String,List<ID>>();
        for(Account client : scope)
        {
            if(territoryClientIDMap.containsKey(client.client_territories__c))
            {
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
            else
            {
                territoryClientIDMap.put(client.client_territories__c, new List<ID>());
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
        }
        
        for(List<ID> clientIDS : territoryClientIDMap.values())
        {
            List<Task> tsks=createNML(clientIDS);
            insert tsks;
        }
        
        
    }
    
    global void finish(Database.BatchableContext BC)
    {
        
    }

}
@isTest
private class Test_AR_Creating75DummyNML {
    
    
    static testMethod void Test(){
        //create 10 advisors
        ////for each advisor create 100 clients
        //

        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Account> advisors=new List<Account>();
    
        For(integer i=0;i<10;i++)
        {
            Account a=new Account(name='a'+String.valueOf(i),client_territories__c='a'+String.valueOf(i),account_type__c='provider',Monthly_Activity_Reporting__c=true,Account_Status__c='active');
            advisors.add(a);
        }
        insert advisors;
        
        For(integer j=0;j<advisors.size();j++)
        {
            List<Account> clients=new List<Account>();
            For(integer i=0;i<100;i++)
            {
                Account client=new Account(name=advisors[j].name+String.valueOf(i),client_territories__c=advisors[j].client_territories__c,account_type__c='prospect');
                clients.add(client);
            }
            insert clients;
        }
        
        
        List<Account> advisors1= [select client_territories__c from Account where
                                (account_type__c='provider' or account_type__c='advisor') 
                                 and Monthly_Activity_Reporting__c=true and Account_Status__c='active'];
        List<String> territories=new List<String>();
        List<String> advisorIDs=new List<String>();
        for(Account advisor : advisors1)
        {
            territories.add(advisor.client_territories__c);
            advisorIDs.add(advisor.id);
        }        
        //[select id,client_territories__c from Account where client_territories__c in :territories];
        string tempquery='Select id,client_territories__c from Account where client_territories__c in (';        
        for(String terr : territories)
        {
            tempquery+='\'';
            tempquery+=terr;
            tempquery+='\',';
        }
        tempquery=tempquery.substring(0, tempquery.length()-1);
        tempquery+=') and id not in (';
        for(String adid : advisorIDs)
        {
			tempquery+='\'';
            tempquery+=adid;
            tempquery+='\'';
            tempquery+=',';
        }
        string query=tempquery.substring(0, tempquery.length()-1);
        query+=')';
        
        Test.startTest();
        AR_Creating75DummyNML c=new AR_Creating75DummyNML(query);
        Database.executeBatch(c);
        Test.stopTest();
        
        List<Task> tsk=[select ownerid,CallType__c,Subject,
                              Status,Priority,ActivityDate from Task where createddate=TODAY and CallType__c='NML'
                       and ownerid= :userid and Status='Completed' and Priority='Normal'];
        
        //75 tasks for each advisor
        System.assertEquals(750, tsk.size());
        
        
	}

}

I tried to google this error, but I didn't get a satisfied answer.


  • September 24, 2014
  • Like
  • 0

I'm having a difficult time to get my code coverage increased (I'm still a newb on the dev end).

My class is working and the test class passes, but I'm not able to piece it all together.  Any help?

 

My Class to display values on a VF page...

public class ascSummary{

    public ascSummary() {

    }


    public ascSummary(ApexPages.StandardController controller) {

    }


        public Visit__c getVisit()
    {
        
        //Retrieve Audit Results based on Id parameter of this page
        return [Select Id,
                Visit__c.Account__c,
                Visit__c.Contact__c,
                Visit__c.Visit_Date__c,
                Visit__c.Pre_audit_score__c,
                Visit__c.Workshop_Score1__c,
                Visit__c.Total_3_0v2__c,
                Visit__c.Total_4_0v2__c,
                Visit__c.Total_5_0v2__c,
                Visit__c.X1_0__c,
                Visit__c.X2_0__c,
                Visit__c.X3_0__c,
                Visit__c.X4_0__c,
                Visit__c.X5_0__c,
                Visit__c.Total_Percent__c,
                Visit__c.Total_Audit_Score__c
                from Visit__c j
                where Id = 
:ApexPages.currentPage().getParameters().get('id') ];
    }
}

 My test class..

@isTest
private class ascSummaryTestClass {
     static testMethod void validateascSummary() {
         visit__c v = new visit__c (Account__c='001c000000Qm4kp', Contact__c = '003c000000N7Bl0');
         insert v;
        
          // Retrieve the contact from the visit
        v = [SELECT Contact__c FROM Visit__c WHERE Id =:v.Id];
    System.debug('Contact after visit created: ' + v.Contact__c);  
    }
}

 

 

  • September 04, 2013
  • Like
  • 0

Hey guys,

 

I thought that the primary selling point of Force.com sites is creating public web pages where you can display data to users without requiring a login where our VF pages could be accessed by the Site guest user provided we gave the right object access to the guest user profile.

 

We want to display a custom object and its chatter feed and we need it to be read only. I thought this will be possible but it turns out that the Guest user does not have access to the Chatter APIs.

 

Has anybody else run into this problem? We are hoping to avoid having to ask the users to login.

Any thoughts on this problem would be much appreciated.

 

Thanks.

I am getting this error when I go into Edit mode for a record. I'm using the same controller & VF page that I am using for a New record of the same object. 

SObject row was retrieved via SOQL without querying the requested field: Contract_Overview__c.Contract_Start_Date__c 

 

 

I thought it would solve the problem to retrieve the field in my query  (such as Name and Contract_Type_c) - but then I just get the same error for the next field which is included as an input field in the VF page. I guess I could solve the whole problem by just retrieving EVERY single field which is an input field in the VF page, but I don't want to have to do that. There's gotta be a better way. 

 

Here is the controller being used : 

 

public class MycontrollerSFDCBETA2{

    public String rightOptionsHidden { get; set; }

    public String leftOptionsHidden { get; set; }

    public MycontrollerSFDCBETA2() {

    }

    public Account selectedUser { get; set; }
    String contractid;
    public Contract_Overview__c contract{get;set;}
    public string relatedAccount{get;set;}
    public string names{get;set;}
    public string accountid{get;set;}
    public Name contractnew{get;set;}
    public string selectedaccountid{get;set;}
    public String message { get; set; }

    public List<SelectOption> selectedContacts { get; set; }
    public List<SelectOption> options { get; set; }

    public MycontrollerSFDCBETA2(apexpages.standardcontroller controller)
        {
        selectedContacts = new list<SelectOption>();
        contract = new Contract_Overview__c();
        contractid=system.currentpagereference().getparameters().get('id');
            if(contractid!=null)
            {
                contract=[select account__c,Name,Contract_Type__c,  Subsidiaries_On_Contract__c from Contract_Overview__c  where id =:contractid];
                relatedAccount=Contract.account__C;
            }
        }

    public pageReference  execute()
        {
        accountid=contract.Account__c;
        System.debug('########'+accountid);
        return null;
        }

    public list<selectoption> getitems()
        {
        
        List<selectoption> options= new list<selectoption>();
                    
        if(accountid != null)
            {
                account a =[select name , (select name from Subsidiaries_and_Brands__r) from account where id =:accountid];
        for(SubsidiariesAndBrands__c s : a.Subsidiaries_and_Brands__r)
                    {
                    options.add(new SelectOption(s.name,s.name));
                    }
            }
        else
            options.add(new SelectOption('None','None'));
            return options;
            
        }
            
    public void save()
        {
        
        System.debug('********************************' + names);
        
        message = null ;       
        Boolean first = true;
        for ( SelectOption so : selectedContacts ) {
            if (first) {
                message = message ;
            }
            
                
            message = message + ', ' + so.getValue() ;
            
            first = false;
            
        }
        
        message=message.removeStart('null, ');
        message='['+message+']';
        
        System.debug('********************************' + message);
        contract.Subsidiaries_On_Contract__c=message;
        
        insert contract;
        contract=new Contract_Overview__c  ();
        System.debug('********************************' + contract);
                  
        }
}

 

and here's part of the VF page : 

 

<apex:outputLabel value="Contract Overview Name : "/>
                    <apex:inputfield value="{!contract.Name}" />
                    <apex:outputfield value="{!contract.OwnerId}"/>
                    <apex:outputLabel value="Contract Type : "/>
                    <apex:inputfield value="{!contract.Contract_Type__c}" required="false"/><br></br>
                    <apex:outputLabel value="Contract Status : "/>
                    <apex:inputfield value="{!contract.Contract_Status__c}" required="false"/><br></br>
                    <apex:outputLabel value="Contract Start Date : "/>
                    <apex:inputfield value="{!contract.Contract_Start_Date__c}" required="false"/><br></br>

 

 

 

So, in other words, if I retrieve Status__c in the query I'll just get that same sObject error for Contract_Start_Date__c and so on and so on...

I'm sure there's gotta be a better way than this. Anybody know them ? 

Thank you very much for your help.

 

  • April 16, 2013
  • Like
  • 0

Hey Guys

I need some help

 

I have built the following apex trigger ( See below) however i need to apply the company search on a certain records types.

The Record types in question are  “FDMS Lead Generation  &  FDMS Sales Lead”, where do i add this into the code?

My apex trigger is


Trigger DuplicateLeadPreventer on Lead

                               (before insert, before update) {

 

    Map<String, Lead> leadMap = new Map<String, Lead>();

    for (Lead lead : System.Trigger.new) {

                               

        // Make sure we don't treat an Company name that 

       // isn't changing during an update as a duplicate. 

   

  if ((lead.company != null) &&

                (System.Trigger.isInsert ||

                (lead.company !=

                    System.Trigger.oldMap.get(lead.Id).company))) {

                               

            // Make sure another new lead isn't also a duplicate 

   

            if (leadMap.containsKey(lead.company)) {

                lead.company.addError('Another new lead has the '

                                    + 'same company name.');

            } else {

                leadMap.put(lead.company , lead);

            }

       }

    }

               

    // Using a single database query, find all the leads in 

   

    // the database that have the same company address as any 

   

    // of the leads being inserted or updated. 

   

    for (Lead lead : [SELECT company FROM Lead

                      WHERE company IN :leadMap.KeySet()]) {

        Lead newLead = leadMap.get(lead.company);

        newLead.company.addError('A lead with this company '

                               + 'name already exists.');

    }

}
  

  • April 11, 2013
  • Like
  • 0

Hi,

 

 I have a small doubt,

 

1) I am building a site for a exam which is internal to the orgn , How to restrict the site based on organisation ip,

 

2) The site should to be visible only to specific ip (within orgn)

 

Please tell me how to do it

 

Thanks in advance

We are trying to insert some records in lead object but APEX code that implement  this interface not executing during manage package installation ,Please review my code and advise us

   

 

global class InstallClass implements InstallHandler 
{
global void onInstall(InstallContext context) 
{
if(context.previousVersion() == null) {
lead ObjLead=new Lead();
ObjLead.LastName='InstallClass';
ObjLead.Company='InstallClass';
insert ObjLead;



}
public static testMethod void testRunAs() 
{
Test.testInstall(new InstallClass(),null);}

}

 

I want to embed javascript coding in visualforce. The javascript coding is for integrating 'Bitly' platform with salesforce.

 

My visualforce code is:

 

<apex:form >
<apex:inputText value="{!Candidate__c.Long_Url__c}" id="theText" onclick="javascript&colon;go('{!$Component.theText}')" ></apex:inputText>

  <script type="text/javascript" src="/js/functions.js"></script>
    <script src="/soap/ajax/11.1/connection.js"></script>
    
   <script language="javascript">
    
   function go(f) {
    var theText = document.getElementById(f).value;
   alert(theText);
   }
var xhr = new XMLHttpRequest(); 

xhr.open("GET", "http://api.bitly.com//v3/shorten?login=tseth&apiKey=R_948fa681da46221f969e83b2ba52d31e&longUrl="+theText);

xhr.onreadystatechange = function(){ 

alert('test');
if(xhr.readyState == 4) { 
if(xhr.status==200) { 
var jsonResponse = JSON.parse(xhr.responseText);
var bitlyUrl = jsonResponse.data.url; 

myFunc(bitlyUrl);
var t = xhr.send();
}
}
}

</script>
</apex:form>
<apex:form >
<apex:actionFunction name="myFunc" action="{!field}">
<apex:param name="param1" value=""/>
</apex:actionFunction>
</apex:form>

</apex:page>

 

Bitly is used for URL shortening. I want the shortened url to be passed to the controller through <apex:actionfunction>.

 

Please help. Its really urgent. I am completely stuck.

 

Thanks

 

 

hi I have a ApexScheduler Class which need to be test inorder to
deploy can anybody suggest me the way to achieve it to get the
coverage. I am posting the code below

 

global class ScheduleTerritoryInactiveMemberCheck implements 
Schedulable { 
    global void execute(SchedulableContext SC) { 
        TerritoryInactiveMemberCheck bcc = new 
TerritoryInactiveMemberCheck(); 
          bcc.query = 'select id,name from territory'; 
             Database.executeBatch(bcc,200); 
  }
 
} 

 cheers,

naga

 

  • December 03, 2010
  • Like
  • 0

I was wondering if someone could help a newb to SFDC come up with the code for an apex trigger.

 

Here's the scenario:

 

I have a custom object called payments (Payments__c) - a child object  of opportunities - and I would like a payment record to be created after a new opportunity record is created, but only if a checkbox is checked (Create_New_Payment__c).

 

There are a few fields on the new payment record that need to be pre-populated:

  1. The opportunity field (obviously)
  2. Payment amount (Amount__c) should equal the amount of the opportunity (the payment amount field is not a formula field and can't be, but maybe this can be accomplished with workflow - if Create_New_Payment__c is true, payment amount equals opportunity amount??)
  3. Paid__c checkbox equals true

So is this possible to do?

 

Thanks for any help.

Data.Com setup options don't appear in a developer instance I created in 2012, and now I verify they also don't appear in production instances created in 2012 and 2009.  My clients need the Data.Com functions, and I'm deploying new code that takes advantage of them.  Or I'm trying to.

Data.Com setup options should appear in the left menu bar:

Correct options showig for Data.Com
But my older development (and production) instances only show:

User-added image
I've spoken with the Data.Com tech support and they tell me that for the developer instance, I have to create a new developer instance and then migrate my code and data over to it.  The old template apparently doesn't support data.com fully.  Okay, I can live with that.

But now I'm worried that the same is also true of my clients' production instances which I created before 2012.  Their menus lack the Data.Com options as well.  Does this mean if I want to deploy code that relies on Data.Com I have to move them to a new instance and migrate all their data?  If so, that's a major problem. and it's hard to believe no one has raised a warning.

Somebody please tell me I'm crazy.  I'll update this when I hear back from tech support.