• Eric_Santiago
  • NEWBIE
  • 5 Points
  • Member since 2005

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 27
    Replies

Recently, I was writing some classes that needed to detect if the org they were in was a sandbox or not and determine which endpoint to call accordingly. Since there isn's an isSandbox method in Apex, I had to create my own. This will work in visualforce controllers/extensions and from standard classes. You can read the full details at http://www.ericsantiago.com/eric_santiago/2011/12/determining-salesforce-server-pod-and-if-sandbox-via-apex.html

 

Code as follows

 

public String currentPod { 
            String server;
            
            if (ApexPages.currentPage() != null){ //called from VF page
            		server = ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
            } else { //called via standard class
            		server = URL.getSalesforceBaseUrl().getHost();
            }
            
            if ( server != null && server.length() > 0){
                server = server.substring(0 ,server.indexOf('.'));
                
            }
            return server ; 
   }

   public Boolean isSandbox {
            String pod = currentPod();
            if (pod != null && pod.length() > 0 && pod.toUpperCase().startsWith('C')){
                return true;
            }
            return false;
   }

 

Is there a way to render the merge fields in a string in Apex. As an example, I want to use email templates for a task. I've
written a VF page to override new task creation. It has a function that retrieves the body of the template but when its displayed
in the inputField it show the merge field syntax; i.e. Dear {!Contact.FirstName}.

 

public PageReference changeTemplate() {
EmailTemplate template = [Select TemplateType, Subject,
Name, Id, HtmlValue, Body, Description From EmailTemplate where id =:ApexPages.currentPage().getParameters().get('templateId')];

msg.Subject__c = template.Subject;
msg.Description__c = template.Body; //includes {!merge fields} as literal
}
return null ;
}

 

 I'm not sending an email as part of this process, so I need some way to render the merge fields in the string. What complicates this is that while the whoId can only be a Lead or Contact, the whatId on the task can any object. So a simple find and replace on the string gets very complex. Any suggestions?

Is there a way to render the merge fields in a string in Apex. As an example, I want to use email templates for a task. I've
written a VF page to override new task creation. It has a function that retrieves the body of the template but when its displayed
in the inputField it show the merge field syntax; i.e. Dear {!Contact.FirstName}.

 

public PageReference changeTemplate() {
EmailTemplate template = [Select TemplateType, Subject,
Name, Id, HtmlValue, Body, Description From EmailTemplate where id =:ApexPages.currentPage().getParameters().get('templateId')];

msg.Subject__c = template.Subject;
msg.Description__c = template.Body; //includes {!merge fields} as literal
}
return null ;
}

 

 I'm not sending an email as part of this process, so I need some way to render the merge fields in the string. What complicates this is that while the whoId can only be a Lead or Contact, the whatId on the task can any object. So a simple find and replace on the string gets very complex. Any suggestions?
I have a VF component that takes a number of optional string Attributes, url encodes them, and sends them back to the VF page. Is there a way to programtically loop through all the Attributes similarly to $ApexPages.getParameters() method?
I'm trying to write a simple trigger that renames a record. I keep getting the error "CallLineItemRename: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.CallLineItemRename: line 18, column 9" . What am I missing here?

 

 

 

trigger CallLineItemRename on Call_Line_Item__c (before insert, before update) { // this triger renames the call line item id to be // the specified inventory item name or the product name List<Call_Line_Item__c> callItems = new List<Call_Line_Item__c>(); callItems = Trigger.new; for (Call_Line_Item__c callItem : callItems) { //check if inventory or product was specified if (callItem.Inventory_Item__c <> NULL) { callItem.Name = callItem.Inventory_Item__r.Name; callItem.Name = 'inv item name'; } else if (callItem.Products__c <> NULL) { callItem.Name = callItem.Products__r.Name; } } update callItems; }

 

 

 

I've got an issue with a test class. I'm stuck at 56% coverage. My test method creates all the objects referenced in my controller and works fine. When I run the tests, it tells me the whole catch (QueryException ex) section of the methods is not covered. Here's a sample of what I have so far.

Code:
public static Employee__c getEmployee() {
     try {
      Employee__c employee=  [select id, kiosk__r.name, kiosk__c from Employee__c where user_name__c = :UserInfo.getUserId() Limit 1];
      return employee;
      } catch (QueryException ex) {
          ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'No employee record found for current user!');
          ApexPages.addMessage(myMsg);
          return null;
     }
    }

 

Code:
public static testMethod void testDashboardControllerMethods()
      {
      //create employee      
            Employee__c employee1=new Employee__c();
            employee1.Name='Test emp 1';
            employee1.Emp_ID__c='xtyooyuoowow';
            employee1.Kiosk__c=kiosk.Id;
            employee1.Quota_Status__c='Active';
            employee1.Sys_ID__c='127uijo90';
            employee1.User_Name__c=[Select Id from user where Isactive=true Limit 1].Id;
            employee1.Weekly_Hours__c=20;
            insert employee1;
            dashboardController.getEmployee();
       }

I tried creating a QueryException in the test method by adding a second test method that creates a employee record but not specifying user_name__c.

Code:
public static testMethod void testDashboardControllerMethods2() {
            //test the exception errors
            Employee__c employee1=new Employee__c();
            insert employee1;
            dashboardController.getEmployee();
      }

That doesn't seem to work. Any suggestions?

http://community.salesforce.com/sforce/board/message?board.id=Visualforce&message.id=2452

http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_validation.htm

http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=2298

http://www.salesforce.com/us/developer/docs/pages/Content/apex_pages_message.htm

OK. I've read all of the above thoroughly and I'm still having trouble kicking back a custom error message to a visualforce page using apex:messages. Any suggestions would be appreciated greatly.


Code:
public class dashboardController {

    public Employee__c getEmployee() {
    return [select id, kiosk__r.name, kiosk__c from Employee__c where user_name__c = :UserInfo.getUserId() Limit 1];
    }
    
    public Rep_Quota__c getRepQuota() {
      try {
Rep_Quota__c repquota = [select id, Perf_Day__c, Perf_Week__c, Perf_Month__c from Rep_Quota__c Where Quota_Start_Date__c = THIS_MONTH and Employee__c = :getEmployee().id Limit 1];
return repquota;
} catch (QueryException e) {
ApexPages.Message msg= new ApexPages.Message(ApexPages.Severity.ERROR, 'No Rep Quota record found for current month!', 'No Rep Quota record found for current month!');
ApexPages.addmessage(msg);
return null; } } } <apex:page controller="dashboardController"> <apex:sectionHeader title="Rep Dashboard"></apex:sectionHeader> <apex:pageMessages/> <apex:pageBlock title="{!$User.FirstName} {!$User.LastName}" mode="view"> <apex:image id="user_graph1" value="http://chart.apis.google.com/chart—chs=300x200&cht=gom&chd=t:{!RepQuota.Perf_Day__c}&chl={!RepQuota.Perf_Day__c}&chds=0,200&chf=bg,s,EFEFEF&chtt=Yesterday"/> <apex:image id="user_graph2" value="http://chart.apis.google.com/chart–chs=300x200&cht=gom&chd=t:{!RepQuota.Perf_Week__c}&chl={!RepQuota.Perf_Week__c}&chds=0,200&chf=bg,s,EFEFEF&chtt=This Week"/> <apex:image id="user_graph3" value="http://chart.apis.google.com/chart˜chs=300x200&cht=gom&chd=t:{!RepQuota.Perf_Month__c}&chl={!RepQuota.Perf_Month__c}&chds=0,200&chf=bg,s,EFEFEF&chtt=This Month"/> <hr width="90%"/> <div align="center" style = "font-size:12pt;"><b>Quota Performance</b></div> </apex:pageBlock> </apex:page>

I'm testing a stituation where I know I get a QueryException error (without the catch I get "System.QueryException: List has no rows for assignment to SObject"). I've tried variations with catch(Exception e) and Apex.Messages(e) and ApexPages.addmessage(e.getMessage()); but nothing works. Any suggestions?


 



Message Edited by Eric_Santiago on 07-09-2008 11:59 PM

Message Edited by Eric_Santiago on 07-10-2008 12:15 AM
Is there any definitive documentation on using the Dojo Toolkit (http://dojotoolkit.org) in Salesforce Scontrols?

There is a small mention about Dojo in the AJAX Toolkit document (http://www.salesforce.com/us/developer/docs/ajax/index.htm). Other posts in this forum have mentioned that Salesforce now hosts version 0.4.1 of the Dojo toolkit. However, there is little documentation to be found on the paths necessary to call the required files.

I'd like to create an scontrol that uses the Dojo Editior (http://dojotoolkit.org/book/dojo-book-0-9/part-2-dijit/advanced-editing-and-display/editor-rich-text) to give the user WYSIWYG controls for a text area.

Code:
<script src="/js/dojo/0.4.1/dojo.js"></script> 
<script type="text/javascript">
  dojo.require("dijit.Editor");
  dojo.require("dojo.parser");
</script>
<script src="/soap/ajax/8.0/connection.js"></script>

.....

<textarea dojotype="dijit.Editor" stylesheets="/js/dojo/0.4.1/resources/dojo.css"> <p>
  This editor is created from a textarea .
 </p>
</textarea>

 Unfortunately, its hard to find out A) what is the latest version of the toolkit Salesforce is hosting/supporting and B) what are the proper relative urls for dojo.js and dojo.css.

I'd greatly appreciate any assistance. I'll even offer to add this information and working code to the Wiki to pay it forward.



Message Edited by Eric_Santiago on 02-28-2008 10:39 AM
I was able to create a nice call button for intializing skype calls to contacts. Add a field called 'Skype_Name' to the contacts object. Then create a formula field with the following;

IF(OR(ISNULL({!Skype_Name__c}),LEN({!Skype_Name__c}) < 1) , "" , HYPERLINK("callto://"& {!Skype_Name__c} ,IMAGE("http://download.skype.com/share/skypebuttons/buttons/call_blue_transparent_70x23.png", "Skype Call")))

If the person's skype name field is blank nothing appears. Otherwise it shows a small skype icon with a link that opens skype and starts calling your contact. Works in IE and Firefox.

Here's the question I need help with. Skype lists other methods rather than using callto:\\ . See http://share.skype.com/tools_for_sharing/skype_buttons/advanced_skype_buttons/

So according to that page I should be able to replace callto:\\ with skype: in the formula above. But that does not work. I get #ERROR where the image should be. After much trial and error I found that the Hyperlink formula will not accept skype: within the URL. (I also tried skype:// as a variation to no avail) I'd like to be able to add additional buttons to initiate chats and file transfers as described in Skype's page.

Unfortunately it seems to be an issue with the Hyperlink function not the syntax I'm using. The image formula help even illustrates an example similar to what I'm doing using Yahoo's IM.

HYPERLINK("ymsgr:sendIM?" & {!Yahoo_Name__c}, IMAGE("http://opi.yahoo.com/online?u=" & {!Yahoo_Name__c} & "&m;=g&t;=0", "Yahoo"))

That ymsgr: tag works fine but not skype:. Anyone have any ideas? It would seem odd if Salesforce didn't allow that function to use the skype tab since Skype provided an app for the exchange (which I couldn't get to work btw. One issue at a time though.).

Also as a gift, here's another great skype formula. Skype is beta testing a presence awareness server. This formula will create an image field that shows a contact's skype status.

IF(OR(ISNULL({!Skype_Name__c}),LEN({!Skype_Name__c}) < 1) , "n/a" , HYPERLINK("callto://"& {!Skype_Name__c} ,IMAGE("http://mystatus.skype.com/"& {!Skype_Name__c} & "/smallclassic"
, "Skype Call")))

Right now it only shows an image that says 'I'm not telling'. I assume when the service goes live this will work perfectly. See skype's website for more info on tweaking this. http://share.skype.com/sites/devzone/2006/01/skypeweb_beta_is_here.html
Google talk was just released as an im/voip client.
http://www.google.com/talk/index.html

I noticed the Skype integration for Salesforce and was wondering if anyone was looking into a Google Talk integration?

Recently, I was writing some classes that needed to detect if the org they were in was a sandbox or not and determine which endpoint to call accordingly. Since there isn's an isSandbox method in Apex, I had to create my own. This will work in visualforce controllers/extensions and from standard classes. You can read the full details at http://www.ericsantiago.com/eric_santiago/2011/12/determining-salesforce-server-pod-and-if-sandbox-via-apex.html

 

Code as follows

 

public String currentPod { 
            String server;
            
            if (ApexPages.currentPage() != null){ //called from VF page
            		server = ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
            } else { //called via standard class
            		server = URL.getSalesforceBaseUrl().getHost();
            }
            
            if ( server != null && server.length() > 0){
                server = server.substring(0 ,server.indexOf('.'));
                
            }
            return server ; 
   }

   public Boolean isSandbox {
            String pod = currentPod();
            if (pod != null && pod.length() > 0 && pod.toUpperCase().startsWith('C')){
                return true;
            }
            return false;
   }

 

I'm trying to write a simple trigger that renames a record. I keep getting the error "CallLineItemRename: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.CallLineItemRename: line 18, column 9" . What am I missing here?

 

 

 

trigger CallLineItemRename on Call_Line_Item__c (before insert, before update) { // this triger renames the call line item id to be // the specified inventory item name or the product name List<Call_Line_Item__c> callItems = new List<Call_Line_Item__c>(); callItems = Trigger.new; for (Call_Line_Item__c callItem : callItems) { //check if inventory or product was specified if (callItem.Inventory_Item__c <> NULL) { callItem.Name = callItem.Inventory_Item__r.Name; callItem.Name = 'inv item name'; } else if (callItem.Products__c <> NULL) { callItem.Name = callItem.Products__r.Name; } } update callItems; }

 

 

 

Recently, I was writing some classes that needed to detect if the org they were in was a sandbox or not and determine which endpoint to call accordingly. Since there isn's an isSandbox method in Apex, I had to create my own. This will work in visualforce controllers/extensions and from standard classes. You can read the full details at http://www.ericsantiago.com/eric_santiago/2011/12/determining-salesforce-server-pod-and-if-sandbox-via-apex.html

 

Code as follows

 

public String currentPod { 
            String server;
            
            if (ApexPages.currentPage() != null){ //called from VF page
            		server = ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
            } else { //called via standard class
            		server = URL.getSalesforceBaseUrl().getHost();
            }
            
            if ( server != null && server.length() > 0){
                server = server.substring(0 ,server.indexOf('.'));
                
            }
            return server ; 
   }

   public Boolean isSandbox {
            String pod = currentPod();
            if (pod != null && pod.length() > 0 && pod.toUpperCase().startsWith('C')){
                return true;
            }
            return false;
   }

 

Hi,

 

I have a button on a page, onclick of which i am creating tasks and attachments related to those tasks. This works fine when i launch the page from the salesforce org. However, when i use this page as a site page, i get the below error:

 

"Insufficient Privileges

Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []"

 

Below is my function:

      public void saveEmailAsActivity(String appId, Messaging.SingleEmailMessage email)
        {
            /* Start - Added on 12th September 2011*/
            User objUser = new User();
            String strUserName = 'test@sfdcsiteuser.com';
            objUser = [Select Id from User where username=:strUserName];
            /* End - Added on 12th September 2011*/
            
            //Create an activty related to Applicant.
            Task objTask = new Task();
            objTask.Status = 'Completed';
            objTask.whatId = appId;
            objTask.Subject = 'Email:' + email.subject;
            objTask.Description = 'Body:' + email.getHTMLBody();
            objTask.OwnerId = objUser.Id; //Added on 12th September 2011
            insert objTask;

            //Create Attachment(s) if present within the email related to the above activity.
            List<Attachment> lstAttach = new List<Attachment>();
            if(email.getFileAttachments() != null)
            {
                for(Messaging.EmailFileAttachment objEFA: email.getFileAttachments())
                {              
                    Attachment objAttach = new Attachment();
                    objAttach.ParentId = objTask.Id;
                    objAttach.Name = objEFA.getFileName();  
                    objAttach.Body = objEFA.getBody();
                    objAttach.ownerId = objUser.Id;
                    lstAttach.add(objAttach);
                }
                if(lstAttach.size() > 0)
                    insert lstAttach;
            }      
        }

 

Now if i comment out the "insert lstAttach" portion, the code works fine. However it gives an error only when i try to insert the attachment.  I cannot remove the "objAttach.ownerId = objUser.Id" line, because it gives me another error saying that the "Owner of the attachment must be the same as that of parent task" and if i keep that line i get the "Insufficient Cross Reference Entity" Error.

 

Can anybody help me with this?

 

Thanks,

Shailesh.

Is it possible to use a trigger to automate the creation of Campaign Member Status? For example, when a campaign of certain type is created, I would like to automatically add 'Show', 'No show' i nthe list of Campaign Member Status. Is it possible?

Thanks

Pierre 

Is there a way to render the merge fields in a string in Apex. As an example, I want to use email templates for a task. I've
written a VF page to override new task creation. It has a function that retrieves the body of the template but when its displayed
in the inputField it show the merge field syntax; i.e. Dear {!Contact.FirstName}.

 

public PageReference changeTemplate() {
EmailTemplate template = [Select TemplateType, Subject,
Name, Id, HtmlValue, Body, Description From EmailTemplate where id =:ApexPages.currentPage().getParameters().get('templateId')];

msg.Subject__c = template.Subject;
msg.Description__c = template.Body; //includes {!merge fields} as literal
}
return null ;
}

 

 I'm not sending an email as part of this process, so I need some way to render the merge fields in the string. What complicates this is that while the whoId can only be a Lead or Contact, the whatId on the task can any object. So a simple find and replace on the string gets very complex. Any suggestions?

Below is some Apex code I found to copy an opportunity.  However, I have a custom field "Membership_Expires" on the opportunity tab.  I would like the new opportunity to add 365

 

 

try{

   {!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")}

 

   // ** EDIT THIS QUERY TO LIST THE FIELDS YOU WANT TO COPY **

   var result = sforce.connection.query("Select o.Type, o.StageName,  o.Membership_Expires__C, o.CampaignId,  o.Amount, o.AccountId From Opportunity o WHERE o.Id = '{!Opportunity.Id}'");

   var newOpp = result.getArray("records");

 

   // Reset the Opp Id and reset fields to default values

   newOpp[0].Id = '';
   newOpp[0].Name = " {!Opportunity.Name}";
  

   // ** EDIT THESE FIELDS TO SET DEFAULT ANY VALUES **
   newOpp[0].StageName = "Pledge";
  newOpp[0].CloseDate = new Date(2099, 0, 1);
  

  newOpp[0].Membership_Expires__c  = {!Opportunity.Membership_Expires__c}

//This was my attempt to get the field to copy but that failed... once I got it to copy I was going to fiquer out how to add 365 days to the filed// 

 

   var saveResult = sforce.connection.create(newOpp);

   if (saveResult[0].getBoolean("success")) {
      newOpp[0].id = saveResult[0].id;
      alert("Opportunity cloned without line items");
   }
   else {
      alert("Failed to create clone: " + saveResult[0]);
   }

   // Refresh the page to display the new oppportunity
   window.location = newOpp[0].id;
}
catch (err) {
   alert (err.description );
} days to this custom field.  

I need to set server url and sesssion id on apx controlle when page loads, Any thoughts!!!!!!!!!!!!!
I need to set Session ID and Server URL when page loads in controller class. This is required to call external synchronous web service call
I'm trying to write a simple trigger that renames a record. I keep getting the error "CallLineItemRename: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.CallLineItemRename: line 18, column 9" . What am I missing here?

 

 

 

trigger CallLineItemRename on Call_Line_Item__c (before insert, before update) { // this triger renames the call line item id to be // the specified inventory item name or the product name List<Call_Line_Item__c> callItems = new List<Call_Line_Item__c>(); callItems = Trigger.new; for (Call_Line_Item__c callItem : callItems) { //check if inventory or product was specified if (callItem.Inventory_Item__c <> NULL) { callItem.Name = callItem.Inventory_Item__r.Name; callItem.Name = 'inv item name'; } else if (callItem.Products__c <> NULL) { callItem.Name = callItem.Products__r.Name; } } update callItems; }

 

 

 

Looking at writing a simple Apex trigger to update a lead or contact field based on a task being added.

 

Have written an after insert Task trigger.  Quick question...

 

What is the best way to determine if the WhatID references a lead or contact?  Can the ID field be treated as a string and what are the ID prefixes for the Lead and Contact table?

 

Thanks!

my apex class method is trying to call an external webservice function, and it gives this
 
Failed to invoke future method 'public static void mycall()'

Debug Log:
System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':html'
 
any idea of how to fix this? what should I do to make it work?
  • January 14, 2009
  • Like
  • 0
hi
 
i want to retrieve the Server URL in trigger or in APEX class?
 
Actual my requirement is:
 
i had an object RelatedAttachement. in that Hyperlink field is of URL type. in that i am saving the URL like /servlet/servlet.FileDownload?file=00PR0000000MqVH. For this i want to retrieve the server URL and concatenate that Server URL to this field and updating this field.  in one server it looks like http://cs2.salesforce.com/servlet/servlet.Download?file=00PR0000000MqVH and in another server it looks like http://na2.salesforce.com/servlet/servlet.Download?file=00PR0000000MqVH so for this one i want to retrieve the server URL and i want to concatenate that URL to that field.
 
So please tell me how to retrieve the Server URL in trigger or in APEX class? 
Hi,
I am sending emails through my Apex class(NOT VisualForce APEX class). The text body of EMail contains the hyperlink to one of my Visualforce page. But depending on the Salesforce account type the instance name in the URL changes.(Example: https://cs2.salesforce.com/apex/myTimeSheets).

In above case cs2 can be na1 or na2 depending on instance type.
Is there any method in APEX by which I can get the name of the SF instance?
This is very simple in SControl but I am not getting anything in Apex fopr the same.

http://community.salesforce.com/sforce/board/message?board.id=Visualforce&message.id=2452

http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_validation.htm

http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=2298

http://www.salesforce.com/us/developer/docs/pages/Content/apex_pages_message.htm

OK. I've read all of the above thoroughly and I'm still having trouble kicking back a custom error message to a visualforce page using apex:messages. Any suggestions would be appreciated greatly.


Code:
public class dashboardController {

    public Employee__c getEmployee() {
    return [select id, kiosk__r.name, kiosk__c from Employee__c where user_name__c = :UserInfo.getUserId() Limit 1];
    }
    
    public Rep_Quota__c getRepQuota() {
      try {
Rep_Quota__c repquota = [select id, Perf_Day__c, Perf_Week__c, Perf_Month__c from Rep_Quota__c Where Quota_Start_Date__c = THIS_MONTH and Employee__c = :getEmployee().id Limit 1];
return repquota;
} catch (QueryException e) {
ApexPages.Message msg= new ApexPages.Message(ApexPages.Severity.ERROR, 'No Rep Quota record found for current month!', 'No Rep Quota record found for current month!');
ApexPages.addmessage(msg);
return null; } } } <apex:page controller="dashboardController"> <apex:sectionHeader title="Rep Dashboard"></apex:sectionHeader> <apex:pageMessages/> <apex:pageBlock title="{!$User.FirstName} {!$User.LastName}" mode="view"> <apex:image id="user_graph1" value="http://chart.apis.google.com/chart—chs=300x200&cht=gom&chd=t:{!RepQuota.Perf_Day__c}&chl={!RepQuota.Perf_Day__c}&chds=0,200&chf=bg,s,EFEFEF&chtt=Yesterday"/> <apex:image id="user_graph2" value="http://chart.apis.google.com/chart–chs=300x200&cht=gom&chd=t:{!RepQuota.Perf_Week__c}&chl={!RepQuota.Perf_Week__c}&chds=0,200&chf=bg,s,EFEFEF&chtt=This Week"/> <apex:image id="user_graph3" value="http://chart.apis.google.com/chart˜chs=300x200&cht=gom&chd=t:{!RepQuota.Perf_Month__c}&chl={!RepQuota.Perf_Month__c}&chds=0,200&chf=bg,s,EFEFEF&chtt=This Month"/> <hr width="90%"/> <div align="center" style = "font-size:12pt;"><b>Quota Performance</b></div> </apex:pageBlock> </apex:page>

I'm testing a stituation where I know I get a QueryException error (without the catch I get "System.QueryException: List has no rows for assignment to SObject"). I've tried variations with catch(Exception e) and Apex.Messages(e) and ApexPages.addmessage(e.getMessage()); but nothing works. Any suggestions?


 



Message Edited by Eric_Santiago on 07-09-2008 11:59 PM

Message Edited by Eric_Santiago on 07-10-2008 12:15 AM
Hello all,

Unless I've missed a tick, I can't see how to unit test the presence of Error messages on a VF page.

Here's my controller method:

Code:
public PageReference save() {
  Code_Project__c project = new Code_Project__c(Name=this.metaData.Name__c, Description__c = this.metaData.Description__c);
  try {
   insert project;
   Project_Link__c[] links = new List<Project_Link__c>();
   links.add(new Project_Link__c(Name='Contact', URL__c=this.metaData.Contact_URL__c, Project__c=project.Id));
   links.add(new Project_Link__c(Name='Download', URL__c=this.metaData.Download_URL__c, Project__c=project.Id));
   if(this.metaData.Homepage_URL__c != '') {links.add(new Project_Link__c(Name='Homepage', URL__c=this.metaData.Homepage_URL__c, Project__c=project.Id));}
   insert links; 
  }
  catch (System.DMLException de) {
   ApexPages.addMessages(de);
   return null;
  } 
  catch (Exception e) {
   ApexPages.addMessages(e);
   return null;
  }
  return Page.ProjectCreateSuccess;
 }

 
I then call a test method where I don't set a required field:
Code:
static testMethod void testProjectCreateNoDescription() {
  Test.setCurrentPage(Page.ProjectWizardPage);
  CreateProjectWizardController testController = new CreateProjectWizardController();
  String name = 'Test Project ' + String.valueOf(System.currentTimeMillis());
  testController.metaData.Name__c = name;
  testController.metaData.Contact_URL__c = 'mailto:test@test.com';
  testController.metaData.Download_URL__c = 'http://test_project.google.com/files/release1.zip';
  testController.metaData.Homepage_URL__c = 'http://code.google.com/p/test_project';
  String nextPage = testController.save().getUrl();
  System.assertEquals('/apex/projectcreatesuccess', nextPage);
  Code_Project__c testProject = [select Name, Description__c, Status__c, (Select Name, URL__c from Links__r) from Code_Project__c where Name = :name];
  System.assertEquals(name, testProject.Name);
  System.assertEquals('Test Description', testProject.Description__c);
  System.assertEquals('Submitted', testProject.Status__c);
  System.assertEquals(3, testProject.Links__r.size());
  for (Project_Link__c link : testProject.Links__r) {
   if (link.Name == 'Contact') {System.assertEquals('mailto:test@test.com', link.URL__c);}
   if (link.Name == 'Download') {System.assertEquals('http://test_project.google.com/files/release1.zip', link.URL__c);}
   if (link.Name == 'Homepage') {System.assertEquals('http://code.google.com/p/test_project', link.URL__c);}
  }
 }

When I run this test, I receive the following run-time error:
System.Exception: ApexPages.addMessages can only be called from a Visualforce page

Any ideas?

Best regards,
Dan
 

Is it possible to add a day to a Datetime variable, for example myDate contains 31/08/2008, how can I add one day to it, which will make it become 01/09/2008?

Cheers
Is there any definitive documentation on using the Dojo Toolkit (http://dojotoolkit.org) in Salesforce Scontrols?

There is a small mention about Dojo in the AJAX Toolkit document (http://www.salesforce.com/us/developer/docs/ajax/index.htm). Other posts in this forum have mentioned that Salesforce now hosts version 0.4.1 of the Dojo toolkit. However, there is little documentation to be found on the paths necessary to call the required files.

I'd like to create an scontrol that uses the Dojo Editior (http://dojotoolkit.org/book/dojo-book-0-9/part-2-dijit/advanced-editing-and-display/editor-rich-text) to give the user WYSIWYG controls for a text area.

Code:
<script src="/js/dojo/0.4.1/dojo.js"></script> 
<script type="text/javascript">
  dojo.require("dijit.Editor");
  dojo.require("dojo.parser");
</script>
<script src="/soap/ajax/8.0/connection.js"></script>

.....

<textarea dojotype="dijit.Editor" stylesheets="/js/dojo/0.4.1/resources/dojo.css"> <p>
  This editor is created from a textarea .
 </p>
</textarea>

 Unfortunately, its hard to find out A) what is the latest version of the toolkit Salesforce is hosting/supporting and B) what are the proper relative urls for dojo.js and dojo.css.

I'd greatly appreciate any assistance. I'll even offer to add this information and working code to the Wiki to pay it forward.



Message Edited by Eric_Santiago on 02-28-2008 10:39 AM
Hello.  I am writing an scontrol which overrides the New button on a Custom Object.   I want the button to take me to an edit screen, but I want to pass a few parameters.  I'm able to pass constant string parameters into fields, but I can't make dynamic fields work.  My basic scontrol is pasted below.  The "static text here" is displayed in the input field in the edit screen.  However I can't make the Project__c.Name value appear.  I've tried all sorts of things - enclosing it in quotes (then the quoted text appears), using the merge notation (error when saving), etc.

Note that I'm trying to create a new Timecard__c record from inside the Project__c record's related list.  (If using the New button from anywhere else, these fields will be blank which is fine...)  So my question is - what is the proper notation that I use to pass the value of Project__c.Name?

<script type="text/javascript">
window.parent.location.href="{! URLFOR($Action.Timecard__c.New, null, [CF00N50000001S4Rz="static text here", CF00N50000001Ru1r=Project__c.Name], true)}";
</script>

Thanks for your time.

Chris


  • May 21, 2007
  • Like
  • 0