• JeremyKraybill
  • NEWBIE
  • 305 Points
  • Member since 2008

  • Chatter
    Feed
  • 11
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 161
    Replies

Hey guys,

 

I'm trying to have Visualforce render a pagesection dependent on whether or not a checkbox has been selected. I'm getting nowhere fast and was wondering if somebody could help?

<apex:pageblock title="Additional Required Information"> <apex:outputtext value="Is the status for a set period of time, set amount of units, or other?" /> <apex:pageblocksection columns="5"> <apex:pageblocksectionitem > <apex:outputlabel value="Time" for="TimeScope" /> <apex:inputcheckbox value="{!Opportunity.Period_of_Months__c}" id="TimeScope" />

</apex:pageblocksectionitem> <apex:pageblocksectionitem > <apex:outputlabel value="Amount of units" for="UnitScope" /> <apex:outputpanel > <apex:inputcheckbox value="{!Opportunity.Status_Number_of_Units__c}" id="UnitScope"> <apex:actionsupport event="onchange" rerender="ProductUnitsInformation" status="AjaxStatus" /> THIS SECTION SHOULD CAUSE THE SECTION AT THE BOTTOM TO RENDER (OR NOT) </apex:inputcheckbox> </apex:outputpanel> </apex:pageblocksectionitem> <apex:pageblockSectionItem > <apex:outputlabel value="Other" for="OtherScope" /> <apex:inputcheckbox value="{!Opportunity.Status_Other__c}" id="CarbonScope" /> </apex:pageblockSectionItem> <apex:pageblocksectionitem > </apex:pageblocksection>

<apex:pageblocksection> <apex:outputpanel id="ProductUnitsInformation"> THIS IS THE SECTION TO BE RE-RENDERED <apex:actionStatus id="AjaxStatus" startText="Requesting..."> <apex:facet name="stop"> <apex:pageblocksection rendered="{!Opportunity.Status_Number_of_Units__c}"> <apex:pageblocksectionitem > <apex:inputfield value="{!Opportunity.Number_of_Units__c}" /> <apex:inputfield value="{!Opportunity.Unit_Identifier__c}" /> </apex:pageblocksectionitem> </apex:pageblocksection> </apex:facet> </apex:actionStatus> </apex:outputpanel> </apex:pageblock>

 

What I'm trying to make happen is, upon selection of the checkbox (id = UnitScope, with the child apex:actionsupport tag), the apex:outputpanel (id=ProductunitsInformation) should render.

 

Currently, upon selection of the checkbox, the action status does not render, and the screen does not change. I'm sure I'm just being naive, but I've not had a great deal of success with the event handlers and AJAX updates.

 

If anybody could point me in the right direction, I'd be very thankful.

 

Andy

Is there an easy way to only display the Time of a DateTime object in VisualForce?

 

Also is there an easy way to display the Day-of-the-week like 'Friday' in VisualForce?

 

Currently, I'm using a switch statement taken from the pdf on Formulas, but am wondering if there is a better method:

{!CASE(MOD( TODAY() - DATE(1900, 1, 7), 7),0, "Sunday",1, "Monday",2, "Tuesday",3, "Wednesday",4, "Thursday",5, "Friday",6, "Saturday", "Error")}

 

Thanks

Parker

 

I am writing a trigger that checks to see when a Case is Closed, that there are no Open Child Cases associated with that Case.

I can get it working fine with plain trigger code:

 

trigger CloseCase_whenNoOpenChildCase on Case (after insert, after update) {

Case[] cc = Trigger.new;

for (Case c:cc)
{
if (c.IsClosed)
{

Integer OpenChildCase = 0;
for (Case ChildCase : [select id from case where ParentId = :c.id and (isClosed != true)])
OpenChildCase++;
if (OpenChildCase > 0)
c.addError('You are trying to Close a Parent Case that still has open child case! Parent Case number is '+c.casenumber+' or Parent Case id = '+c.id);
}
}
}
 
But now I want to use apex classes and so I created a CloseParentCase_NoOpenChildCase class with the CloseoutParentCase method and so replaced the trigger code to this:
trigger CloseCase_whenNoOpenChildCase on Case (after insert, after update) {

Case[] cc = Trigger.new;

for (Case c:cc)
{
if (c.IsClosed)
{
CloseParentCase_NoOpenChildCase.CloseoutParentCase(c);
}
}
}
And the class I created is as followed: 
public class CloseParentCase_NoOpenChildCase
{

public static void CloseoutParentCase (Case c)
{
if (c.isClosed)
{


Integer OpenChildCase = 0;
for (Case ChildCase : [select id from case where ParentId = :c.id and (isClosed != true)])
OpenChildCase++;
if (OpenChildCase > 0)
c.addError('You are trying to Close a Parent Case that still has open child case! Parent Case number is '+c.casenumber+' or Parent Case id = '+c.id);
}
}
 
 
 
And I wanted to create testmethods that will show when I try to close out a case that has child case, it will fail.  But the problem is it looks like when I run the test, it will fail because of the addError call within the class, so the running of the test will fail.
 For example, in my testmethod, I would do something like the code below, but the problem is it would fail at the statement:     update parent_case;
and this is because it would hit the logic in the the CloseoutParentCase method which issues the addError call.
 
So what is the proper way to write a test method when the logic of the trigger/class itself is to result in a failure when certain situation occurs? 
 
  static testmethod void testCloseoutParentCase ()
{


Case parent_case = new Case(RecordTypeId = '0120000000002Ld',Status ='New');
insert parent_case; // hit the trigger

// make sure Case is created
System.assert(parent_case.id != null);
System.assertEquals(parent_case.Status,'New');


Case SRchild_case0 = new Case(RecordTypeId = '0120000000002Ld',Status ='New',parentid=parent_case.id);
insert SRchild_case0; // hit the trigger

// make sure Case is created
System.assert(SRchild_case0.id != null);

// double check

Case SRchild_case = [ select Status from case where parentid = :parent_case.id];

// make sure Case is created
System.assert(SRchild_case.id != null);


// Now try to update the parent case to Closed, it should fail since we have an open child case
// and therefore parent case status should still be New

parent_case.Status='Closed';
update parent_case;

System.assertEquals(parent_case.Status,'New');
 

delete SRchild_case0;
delete SRchild_case;
delete parent_case;
}
}
 
 
 
 

 

  • February 06, 2009
  • Like
  • 0

Hi there.

Does anyone have any tips for setting the ownerId of a new Idea

when created from a site?

 

I have a vf page that captures data using inputText fields and sets values in

an Idea (newly instantiated) in the code and then inserts this. The reason 

I have to do it this way is because ideas are read only when exposed with sites

Thanks

  • February 05, 2009
  • Like
  • 0

So I have all these sales people images that they would like to have displayed on the sales page relative to the users alias. So I name all the images  the same as the users alias and load them up in the static resources. I just want to call them.  I am imagingin something liek this but I am not sure how to dynaically populate the name of the resource based on the users alias 

So heres a static example  where "initals" is the users alias name.

 

 <img id="repImage" src="{!$Resource.img_initials}" alt="{!Rep_Page__c.User__r.Name}" />

 

 

What I'd like to do is something like this. 

<img id="repImage" src="{!$Resource.img_{!Rep_Page__c.User__r.Alias}}" alt="{!Rep_Page__c.User__r.Name}" /> 

 

I am open to any other options ... ideas? 

  • January 29, 2009
  • Like
  • 0

I am getting the following errors

Trigger.FindOrCreateContact_Trigger: line 7, column 13
  caseAssignmentUpdateTest.caseAssignmentTest System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, FindOrCreateContact_Trigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.FindOrCreateContact_Trigger: line 7, column 13
  ContractClass.testCaseCreation System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, FindOrCreateContact_Trigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

 

My trigger Code:

 


Code:
trigger FindOrCreateContact_Trigger on Case (after insert) {
    Map<ID,Contact> contactMap;
    Map<Id, String> csMap;
    for (Case newCase:System.Trigger.new)
    {
        if(newCase.contactid == null){
            csMap.put(newCase.Id, newCase.Suppliedemail);             
            //Map<ID, Contact> m = new Map<ID, Contact>([Select id, c.email from Contact c WHERE email IN emails]);
        }
    }
    contactMap = new Map<ID, Contact>([select id, email from contact WHERE email IN :csMap.values()LIMIT 1]);
    for(Case updateCase: Trigger.new){
        if(csMap.containsKey(updateCase.id)){
            for(Contact c: contactMap.values()){
                if (updateCase.SuppliedEmail == c.Email) {
                    updateCase.ContactID = c.ID;
                }
            }
        }
    }
}

 

 

 

  • January 28, 2009
  • Like
  • 0

Hi,

 

I am getting this error message when running this query:

 

System.TypeException: Invalid date/time: Mon Jan 26 00:00:00 GMT 2009

 

System.debug(item.Start_Date__c);

myStartdate = datetime.valueOf(item.Start_Date__c);

myExpirationdate = datetime.valueOf(item.Expiration_Date__c);

 

 

Job_Posting_History__History[] jphh_items = [SELECT Id, CreatedBy.Id FROM Job_Posting_History__History WHERE (CreatedBy.ProfileId = '00e30000000mHRJ') AND (Field = 'Cross_Posted_to__c') AND (Parent.Id = :jphid) AND (CreatedDate > :myStartdate) AND (CreatedDate < :myExpirationdate) ORDER BY CreatedDate DESC];

 

 Here is piece of the System Log:

20090127223506.172:Class.Check_Package_Inventory_Cross_Posting.checkRHW_Package: line 30, column 21: 2009-01-26 00:00:00
System.TypeException: Invalid date/time: Mon Jan 26 00:00:00 GMT 2009

I have run out of ideas. Please help!

 

JD

 

  • January 27, 2009
  • Like
  • 0
Hello.

Our organization doesn't want our sales reps to see the leads of other reps... but they do want the reps the ability to just check and see if a lead exists in the system before they can enter it in themselves, to prevent competition.

I wasn't able to accomplish this with the Sharing Settings in the UI. I did put together a trigger that, upon actual entering of the lead, it will prevent the lead from being entered if a lead with the same email address already exists. But, they want the reps to be able to do a quick search and see if the lead exists (and what rep it belongs to) before they enter in all of the additional Lead information.

I put together a Visualforce page that has three fields: Last Name, Company, and Email, and will issue a SOQL query to see if any Leads exist that match those values. It will then display the Lead name, company, email and owner to the rep so they know not to enter it themselves (I plan to update the trigger to prevent entry as well). If it doesn't exist, a link will be provided to go ahead and finish entering the Lead details, picking up the last name, company, and email address that they already put in.

This page is basically functional at this point. It needs some tweaking and CSS, but it's working. I'm new to Visualforce, and when I attempted to actually override the "New" button on the Lead tab, I learned that I can only override that button with a Visualforce page that uses the standard Lead controller.

The code for the page and the class is below. Any help would be very much appreciated.

Page:
Code:
<apex:page controller="ProspectDupeSearch" tabStyle="Lead">
    <apex:form >
        <apex:pageBlock title="Prospect Duplicate Search">
                <strong>Enter the last name, company, and/or email address for a new prospect you are looking to add.</strong>
                <br/><br/>
                Last Name<br /><apex:inputText id="searchName" value="{!searchName}"/>
                <br/><br/>
                Company<br /><apex:inputText id="searchCompany" value="{!searchCompany}"/>
                <br/><br/>
                Email<br /><apex:inputText id="searchEmail" value="{!searchEmail}"/>
                <br/><br/>
                <apex:commandButton value="Check for Duplicates" action="{!doSearch}" rerender="resultPanel"/>
        </apex:pageBlock>

        <apex:pageBlock title="Search Results">
            <apex:outputPanel id="resultPanel" layout="block">
                <apex:outputLink value="/00Q/e—name_lastlea2={!searchName}&lea3={!searchCompany}&lea11={!searchEmail}&retURL=%2F00Q%2Fo">Create new Prospect</apex:outputLink> 
                <apex:dataTable value="{!results}" var="r" cellPadding="4" border="1">
                    <apex:column >{!r.Name}</apex:column>
                    <apex:column >{!r.Company}</apex:column>
                    <apex:column >{!r.Email}</apex:column>
                    <apex:column >{!r.Owner.Name}</apex:column>
                </apex:dataTable>

                <apex:outputText id="sOutput" value="{!results}"/>
            </apex:outputPanel>
        </apex:pageBlock>
   
    </apex:form>
</apex:page>

Class:
Code:
public class ProspectDupeSearch {

    String searchName;
    String searchCompany;
    String searchEmail;
    List<Lead> results;

    public String getSearchName() { return searchName; }
    public void setSearchName(String s) { searchName = s; }

    public String getSearchCompany() { return searchCompany; }
    public void setSearchCompany(String s) { searchCompany = s; }
    
    public String getSearchEmail() { return searchEmail; }
    public void setSearchEmail(String s) { searchEmail = s; }
    
    // Return info
    public List<Lead> getResults() { return results; }

    public PageReference doSearch() {
        String queryString = 'SELECT Id,Name,Company,Email,Owner.Name FROM Lead WHERE IsConverted=False';
        queryString = queryString + ' AND Lead.Name LIKE \'%' + String.escapeSingleQuotes(searchName) + '%\'';
        queryString = queryString + ' AND Lead.Company LIKE \'%' + String.escapeSingleQuotes(searchCompany) + '%\'';
        queryString = queryString + ' AND Lead.Email LIKE \'%' + String.escapeSingleQuotes(searchEmail) + '%\'';
        queryString = queryString + ' ORDER BY LastName ASC';
        results = Database.query(queryString);
        return null;
    }
}


Thanks in advance.

-Greg

 

Hi All,

When rendering a Visualforce page as PDF , does anyone know how to create a page break? (Force a new page)

Thanks so much

Ben
  • November 23, 2008
  • Like
  • 0
Sorry, my original text is missing for some reason...... (user error I suspect!)
 
I have searched for an answer to this and found no solution.  My understanding is that on a normal SF page, it remembers at the user level if the user wants a section open or closed by default.  This works for me on normal pages.  On VisualForce pages this functionality does not work.
 
But what I would really like is to either set a parameter on my VF page so that permanently sections are closed by default.  Alternatively have it possible to manipulate the state of the section via the controller.


Message Edited by GerhardNewman2 on 11-06-2008 01:57 PM
Hello.  I am currently doing pdf generation using an external web service that i wrote - but i'm looking to move the functionality into sfdc using the new apex to pdf.  The pdf that i generate has multiple pages - all with a common header (with images).  I've seen from other threads that this isn't quite supported in any automated fashion (http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=3205).  So I guess the alternative is to foce page breaks and re-draw the header. 

My pdf will have either one or two dynamic pages (based on the number of line items), and 4 static pages (terms of sale, etc).  So the static pages are easy, but my question is, can I conditionally draw the second dynamic page?  That is, if I have more than 6 line items, draw the second dynamic page.  Otherwise, go straight to the static pages.  Is this possible using the VF markup?  Are there any samples with forced page breaks?  I found one thread where a page break is forced, but there's no conditional logic around it (http://community.salesforce.com/sforce/board/message?board.id=Visualforce&message.id=3880).  Do I just throw all of the necessary logic into the apex:repeat block?

Thanks
Chris
  • August 05, 2008
  • Like
  • 0

Hi all,

 

I'm seeing some differing behavior between our Winter sandbox and our Spring 09 sandbox. This snippet of code (from a testMethod) runs fine in Winter:

AccountContactRole acr = new AccountContactRole(); acr.ContactId = contact.Id; acr.AccountId = acct.Id; acr.Role = 'EC'; insert acr;

But in Spring 09, I get an error in the second line above stating "System.SObjectException: Field is not writeable: AccountContactRole.ContactId"

 

I see no mention in the release notes about Contact Roles changing. Is this not the correct way to create a contact role programmatically? Is this possibly a bug? Anyone else seeing this?

 

Jeremy Kraybill

Austin, TX

 

I am running into an issue in Apex outbound email. If I have an email message that is using a template, and that I am sending to a User (via setTargetObjectId), Apex won't let me set WhatId -- if I do, it gives me this error message

"System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds."

Is there any easy way around this limitation? Obviously via workflow rules I am able to send emails to users that have a "What" context sent (for instance, send an email to Opportunity owner when stage change X occurs). Seems like a big limitation of the Apex email service to not allow this.

For now, I am intending to set up temporary Contact objects for Users who do not have them, just so I can send them email.

Here is the code that is hitting this error. "UserId" is the ID of a User object and "WhatId" is the ID of an Opportunity.

Code:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
EmailTemplate template = [select Id from EmailTemplate where DeveloperName = :emailTemplateUniqueName];
mail.setTemplateId(template.Id);
mail.setReplyTo('no-reply@mycompany.com');
mail.setSenderDisplayName('Salesforce');
mail.setTargetObjectId(userId);
mail.setWhatId(whatId);
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
Any pointers much appreciated. If (as I suspect) this is just a straight Apex issue and cannot be done, I'll open an Idea to fix it.

Jeremy Kraybill
Austin, TX
In this thread, someone hit a limitation of VF where they wanted to contribute actual JS to the &lt;head&gt; element of a page, something VF does not allow except through the includeScript and CSS components. Both of those have the obvious limitation that you can't generate script or css on the fly via VF to be included in the head element.

I submitted an Idea which would allow all kinds of additional cross-component and page contribution of HTML / JS / etc. It would allow VF code to contribute code or attributes to the rest of the entire HTML document tree, including the HEAD element.

If you think it would be useful, please vote on it! The idea is here.
In this thread, Doug Chasman wrote:
You are correct on the controller lifecycle - the request to get the content to be converted to pdf is a separate HTTP GET request and the viewstate/controller is not preserved on a GET. This is primarily because of some internal Visualforce details and does not have to be this way forever but it is going to be this way for awhile.

For now you will need to manage data passing yourself, e.g. either by using query parameters or using an sobject(s) that have been saved (this will be visible to the PDF generation request).
We just ran into this - I have a StandardSetController extension which backs a visualforce page. The controller acts on the selected records from a standard list view page (via stdController.getSelected()), and then renders a page with a bunch of data from those selected records.

The page works 100% fine if it is not rendered as pdf, but as soon as I throw the "renderAs="PDF"" in the page tag, the selections get lost and no relevant data is displayed.

If what Doug says is correct, is there a recommended way around this if the controller is managing a large amount of data? Is the solution really as Doug says, to use query parameters or saved SObjects?

Since we will have this need in several pages, I am thinking of implementing a general purpose "presisted developer hashmap" for passing data to PDF controllers. It would basically consist of a master-detail relationship between 2 objects, something like ApexRequest and ApexRequestEntry.

ApexRequest is just a header, maybe we add an "expireDate" to support periodic data cleanup. ApexRequestEntry has just 2 custom fields, probably both strings, as a key/value pair.

Our standardSetControllers that need to render PDF's will do whatever pre-processing / data retrieval they need to do and then put the results in a bunch of ApexRequestEntry objects under a single ApexRequest. They will then render a PageReference redirect to the actual PDF-backing page controller, passing the ID of the ApexRequest as a query parameter. Then the controller for the PDF can read all the key/value pair entries and do what it needs to do. For most of the stuff we're envisioning, the ApexRequestEntry objects would just hold other SObject ID's as values, and the target PDF controllers would know to use them in aggregate as the various "IN" clauses for their queries.

It is a pretty elaborate fix, but we will need to do this in quite a few places and I don't want some hack solution that involves every controller parsing a 32k text field :)

Has anyone found a more elegant solution for this dire limitation of PDF-backing page controllers?

Salesforce doc team, if you are listening, this limitation REALLY needs to be documented! It is not mentioned in any of the 4 pages in the VF guide that refer to PDF generation. It cost my team a couple hours in debugging before realizing it was purely related to the renderAs attribute changing controller behavior.

Jeremy Kraybill
Austin, TX
I have a set of views which operate on the child (detail) object of a master-detail relationship. This object is called "Service Booking". One of these views which will be used by most of our users uses the "My Service Bookings" option in the view to only show the user bookings that belong to them. I assume since OwnerId only exists on master objects, not child objects, that this causes the view to look at the OwnerId of the parent.

On the list screen, I have a custom button backed by a VisualForce controller. This controller has a StandardSetController constructor, and uses the getSelected() call on the parent StandardSetController to determine which records the user has checked the checkboxes for in the list view.

The controller works 100% fine if the records I select in the list view come from a view that does NOT use the "My Service Bookings" option in the view. However, if I first view the records in a personalized "My Service Bookings" view, then check off one or more records and click the custom button, I get the following error in a normal exception screen:

FROM Service_Booking__c WHERE ((OwnerId = '005R0000000ECDR') AND ^ ERROR at Row:1:Column:43 No such column 'OwnerId' on entity 'Service_Booking__c'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.

This error is thrown by (I believe) the StandardSetController, and (I am certain) occurs before the constructor of my controller is touched. I verified this by throwing an Exception in the first line of the constructor and the exception was never thrown, I still got the above error. This is confirmed by the system debug logs, which indicate that no custom code was executed.

Is this a known issue with StandardSetControllers when operating on the child/detail objects in a master-detail relationship? Or is there some other controller I can use?

The only workaround I can think of is to have a field on the child object which either looks up or gets copied the OwnerId of the parent, and then use that field in the view instead of the "My <object name>" radio button.

Any ideas much appreciated!
I am running into an issue in Apex outbound email. If I have an email message that is using a template, and that I am sending to a User (via setTargetObjectId), Apex won't let me set WhatId -- if I do, it gives me this error message

"System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds."

Is there any easy way around this limitation? Obviously via workflow rules I am able to send emails to users that have a "What" context sent (for instance, send an email to Opportunity owner when stage change X occurs). Seems like a big limitation of the Apex email service to not allow this.

For now, I am intending to set up temporary Contact objects for Users who do not have them, just so I can send them email.

Here is the code that is hitting this error. "UserId" is the ID of a User object and "WhatId" is the ID of an Opportunity.

Code:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
EmailTemplate template = [select Id from EmailTemplate where DeveloperName = :emailTemplateUniqueName];
mail.setTemplateId(template.Id);
mail.setReplyTo('no-reply@mycompany.com');
mail.setSenderDisplayName('Salesforce');
mail.setTargetObjectId(userId);
mail.setWhatId(whatId);
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
Any pointers much appreciated. If (as I suspect) this is just a straight Apex issue and cannot be done, I'll open an Idea to fix it.

Jeremy Kraybill
Austin, TX

Hi.

 

Several triggers I've written call class functions that wrap database operations with the goal that calling functions can perform a database rollback if a wrapped operation fails.

 

Since this is my first real attempt at APEX coding and after some head scratching, I've gotten everything covered except two lines I'm not sure how or even if I can test.

 

For example, given a simple wrapper class:

 

 

public class PackageHelper { public class PackageHelperException extends Exception {} public static Boolean addAccountNote(Account a, String title, String body) { if( null == a) throw new PackageHelperException('####addAccountNote: a == null'); System.debug('#################### >> addAccountNote'); title = (null == title || title.length() < 1) ? 'No title provided' : title; body = (null == body || body.length() < 1) ? 'No body provided' : body; try { insert new Note( ParentId = a.Id, Title = title, Body = body); } catch ( System.DmlException e) { System.debug('#################### addAccountNote ' +'could not insert note:'+e.getMessage()); return false; } return true; } // test for addAccountNote private static testMethod void test_addAccountNote() { String title = 'Note Title'; String body = 'Note Body';

Account a;

Note t;

Boolean result;

try { result = addAccountNote((Account)null, title, body); } catch (Exception e) { System.assert(e.getMessage().contains('a == null')); }

System.assertEquals(null, result);

a = new Account(Name='Test Account'); insert a;

 

// add a note

System.assertEquals(true, addAccountNote(a, (String)null, ''));

// was note added?

t = [ select Id, Title, Body from Note where ParentId = :a.Id limit 1 ]; System.assertEquals('No title provided', t.title); System.assertEquals('No body provided', t.body);

 

// ok, delete it delete t;

 

// add another System.assertEquals(true, addAccountNote(a, '', (String)null)); t = [ select Id, Title, Body from Note where ParentId = :a.Id limit 1 ]; System.assertEquals('No title provided', t.title); System.assertEquals('No body provided', t.body); delete t;

 

// and another System.assertEquals(true, addAccountNote(a, title, body)); t = [ select Id, Title, Body from Note where ParentId = :a.Id limit 1 ]; System.assertEquals(title, t.title); System.assertEquals(body, t.body); delete a; } }

 

 

Running the tests on this class reports full coverage except for these two highlighted lines:

 

 

try {
insert new Note( ParentId = a.Id, Title = title, Body = body);
}
catch ( System.DmlException e) {
System.debug('#################### addAccountNote '
+'could not insert note:'+e.getMessage());
return false;
}

 

Perhaps I'm missing something fundamental, but how can I test for an exception which, in the best of all worlds, never occurs and over which I have no control?

 

Thanks.

 

 

Hi,

 

I have a Visualforce page which is embedded on a Custom object detail page.

The height of the Visualforce page gets changed dynamically.

If only one record is displayed, the remaining section is shown in white colour.

If there are more records, then most of the content is not shown because of the section height.

 

So how can i adjust the height dynamically.

 

Is there any other solution, through which i can achieve this.

 

Thanks in advance,

OnDem 

 

I have a requirement to send out an email to a selectable list of Contacts based on a specific contact role  from an opportunity using Professional Edition. The email is a Bid For Service that is sent out from an Opportunity to Contacts on Accounts (with an Account type of "Service Provider") whose roll is "Candidate Bidder."  Not all "Candidate Bidders" will be included, so the list must be selectable.  Using the API and creating a wrapper class makes this easy, but, that is not available.

 

 

 I have tried a variety of options: Account Contact Roles are not avail able in a List View; I've created a report that creates the list of records, but don't seem able to access report records in a VF page; Account Contact Roles are not available as a standard List Controller (would have also made this easier).

 

I created a page using a component that set the filterId to a specific listview and retrieved all the Accounts.  However, I am unsure of how to proceed and get all the correct contacts using the Account contact roles, selecting the contacts, and pass their email address to a VF template.

 

Thanks

  • February 10, 2009
  • Like
  • 0

Had a VF page and controller that was working fine until Spring '09 was installed.  It appears that any values in any public variables are maintained fine when rendered as HTML output and we get a single debug log.  However, if we renderAs="pdf", we end up with multiple log entries and the controller values are lost between the two separate logs resulting in a bunch of null value errors.  What's changed in Spring '09 and how do we accomodate for this?  An simple pseudo-code example would be:

 

public Account myAcct; public Account getAccount() { myAcct = ([SELECT name FROM Account where somecriteria]) System.debug('myAcct Name='+myAcct.name); } public getAcctName() { System.debug('myAcct Name='+myAcct.name); return myAcct.name;}

 


 

This is a simple example but the first debug statement works fine.  The second one returns a null error/value when rendering as PDF.  However, rendering as HTML doesn't have a problem.

 

Hey guys,

 

I'm trying to have Visualforce render a pagesection dependent on whether or not a checkbox has been selected. I'm getting nowhere fast and was wondering if somebody could help?

<apex:pageblock title="Additional Required Information"> <apex:outputtext value="Is the status for a set period of time, set amount of units, or other?" /> <apex:pageblocksection columns="5"> <apex:pageblocksectionitem > <apex:outputlabel value="Time" for="TimeScope" /> <apex:inputcheckbox value="{!Opportunity.Period_of_Months__c}" id="TimeScope" />

</apex:pageblocksectionitem> <apex:pageblocksectionitem > <apex:outputlabel value="Amount of units" for="UnitScope" /> <apex:outputpanel > <apex:inputcheckbox value="{!Opportunity.Status_Number_of_Units__c}" id="UnitScope"> <apex:actionsupport event="onchange" rerender="ProductUnitsInformation" status="AjaxStatus" /> THIS SECTION SHOULD CAUSE THE SECTION AT THE BOTTOM TO RENDER (OR NOT) </apex:inputcheckbox> </apex:outputpanel> </apex:pageblocksectionitem> <apex:pageblockSectionItem > <apex:outputlabel value="Other" for="OtherScope" /> <apex:inputcheckbox value="{!Opportunity.Status_Other__c}" id="CarbonScope" /> </apex:pageblockSectionItem> <apex:pageblocksectionitem > </apex:pageblocksection>

<apex:pageblocksection> <apex:outputpanel id="ProductUnitsInformation"> THIS IS THE SECTION TO BE RE-RENDERED <apex:actionStatus id="AjaxStatus" startText="Requesting..."> <apex:facet name="stop"> <apex:pageblocksection rendered="{!Opportunity.Status_Number_of_Units__c}"> <apex:pageblocksectionitem > <apex:inputfield value="{!Opportunity.Number_of_Units__c}" /> <apex:inputfield value="{!Opportunity.Unit_Identifier__c}" /> </apex:pageblocksectionitem> </apex:pageblocksection> </apex:facet> </apex:actionStatus> </apex:outputpanel> </apex:pageblock>

 

What I'm trying to make happen is, upon selection of the checkbox (id = UnitScope, with the child apex:actionsupport tag), the apex:outputpanel (id=ProductunitsInformation) should render.

 

Currently, upon selection of the checkbox, the action status does not render, and the screen does not change. I'm sure I'm just being naive, but I've not had a great deal of success with the event handlers and AJAX updates.

 

If anybody could point me in the right direction, I'd be very thankful.

 

Andy

I've spent some time trying to get some dynamic elements onto a page that is rendered as a pdf.  I've isolate what I believe to be a bug and would like for someone to verify.  In order to combat the various problems around losing state of member variables in page flows that contain the same controller, I've packed the url that I redirect to with query string parameters that will then be used by the target page to fill content.  Like so:

 

String url = '/apex/PrintMultipleSOs?id=' +
        ApexPages.currentPage().getParameters().get('id');
        Integer counter = 0;
        signaturePageItems = myServiceMap.values();
        for (Service_Order__c eachSO: signaturePageItems){
            if (counter == 0){
                //i'm hacking this because having trouble with the map and the signature page items array
                url = '/apex/PrintMultipleSOs?id=' + eachSO.id;   
            }
            else {
                url += '&so'+counter+'='+eachSO.Id;
            }
            counter++;
        }
        PageReference sigPage = new PageReference(url);
        sigPage.setRedirect(true);
        return sigPage;

 

So if I have 3 SOs, I'll end up with a query string that is {url}?id={firstRowID}&so1={secondRowID}&so2={thirdRowID}.

 

So now in my target page, I'll need to query for these so I want to just iterate over the map of values from 

ApexPages.currentPage().getParameters().  (side note that when working in dev mode there is a query string parameter that was causing my iteration to fail until I removed it from my user profile)

 

//this will never work for a user that is in dev mode b/c there is an additional qs parameter for the dev mode
              Map<String, String> soList = ApexPages.currentPage().getParameters();
              //todo: pull the query into a list return, rather than adding to temp array and potentially hitting soql limit
              for (String eachSOID:soList.values()){
                  tempService = [select Id,Name,Order_Stage__c, Product__c, Term__c, Product_Category__c,
                Hub_Circuit_ID__c, Flex_Facility_ID__c, Ring_Name__c, Bandwidth__c,Customer_Circuit_Id__c,
                Customer_PO__c, Auto_Switching__c,Card_Protection_Required__c,Core_Network_Protection_Required__c,
                Colocation_Type__c, Cabinet_Rack_Provided_By__c, Primary_Power__c, Redundant_Power__c,
                Address_A__c, Suite_Room_A__c, City_A__c, State_A2__c, Zip_A__c, Address_Z__c, Suite_Room_Z__c, City_Z__c, State_Z__c, Zip_Z__c,
                Account__c from Service_Order__c where id = :eachSOID];
                myServiceMap.put(tempService.id, tempService);
               
              }

 

So this works fine when the target page is not a pdf.  I'm guessing there's another hidden querystring param (like the dev mode stuff)  However, brute force does appear to work on the target page.  Like so:

 

String so1 = ApexPages.currentPage().getParameters().get('so1');
              tempService = [select Id,Name,Order_Stage__c, Product__c, Term__c, Product_Category__c,
                Hub_Circuit_ID__c, Flex_Facility_ID__c, Ring_Name__c, Bandwidth__c,Customer_Circuit_Id__c,
                Customer_PO__c, Auto_Switching__c,Card_Protection_Required__c,Core_Network_Protection_Required__c,
                Colocation_Type__c, Cabinet_Rack_Provided_By__c, Primary_Power__c, Redundant_Power__c,
                Address_A__c, Suite_Room_A__c, City_A__c, State_A2__c, Zip_A__c, Address_Z__c, Suite_Room_Z__c, City_Z__c, State_Z__c, Zip_Z__c,
                Account__c from Service_Order__c where id = :so1];
                myServiceMap.put(tempService.id, tempService);
               
                String so2 = ApexPages.currentPage().getParameters().get('so2');
                tempService = [select Id,Name,Order_Stage__c, Product__c, Term__c, Product_Category__c,
                Hub_Circuit_ID__c, Flex_Facility_ID__c, Ring_Name__c, Bandwidth__c,Customer_Circuit_Id__c,
                Customer_PO__c, Auto_Switching__c,Card_Protection_Required__c,Core_Network_Protection_Required__c,
                Colocation_Type__c, Cabinet_Rack_Provided_By__c, Primary_Power__c, Redundant_Power__c,
                Address_A__c, Suite_Room_A__c, City_A__c, State_A2__c, Zip_A__c, Address_Z__c, Suite_Room_Z__c, City_Z__c, State_Z__c, Zip_Z__c,
                Account__c from Service_Order__c where id = :so2];
                myServiceMap.put(tempService.id, tempService);

 

Why is this misbehaving?

  • February 09, 2009
  • Like
  • 0

I need a trigger to create a Dummy Account record every time a Contact is saved with its AccountID field empty (so that Contact is not marked Private and thereby inaccesssible to all beside Owner and Admin). Would the following work? Do I need to add something so that it ONLY creates a dummy record when the AccountID field is empty?

 

trigger create_dummy_accnt on Contact (before insert) {

 

  // create a container to bulk insert accounts
  List<Account> accountsToInsert = new List<Account>(); 

 

  // loop through trigger records
  for (int i=0; i<Trigger.new.size(); i++)
  {
    {
      Account CreateAccnt = new Account();
      CreateAccnt.Name = 'Dummy Account';
      accountsToInsert.add( CreateAccnt );
    }
  }

  // bulk insert accounts
  if (!accountsToInsert.isEmpty()) {
    insert accountsToInsert;
  }
}

 

Also, can anyone think of a way to keep the resulting dummy accounts off the recently viewed items list?

 

Ideally I'd like to drop this workaround and somehow prevent the system from marking Contacts with blank Account ID private - there's no way to do that programatically I don't suppose?

 

The only other workaround I know is to make everyone a system admin. Yikes!

Is there an easy way to only display the Time of a DateTime object in VisualForce?

 

Also is there an easy way to display the Day-of-the-week like 'Friday' in VisualForce?

 

Currently, I'm using a switch statement taken from the pdf on Formulas, but am wondering if there is a better method:

{!CASE(MOD( TODAY() - DATE(1900, 1, 7), 7),0, "Sunday",1, "Monday",2, "Tuesday",3, "Wednesday",4, "Thursday",5, "Friday",6, "Saturday", "Error")}

 

Thanks

Parker

 

I am writing a trigger that checks to see when a Case is Closed, that there are no Open Child Cases associated with that Case.

I can get it working fine with plain trigger code:

 

trigger CloseCase_whenNoOpenChildCase on Case (after insert, after update) {

Case[] cc = Trigger.new;

for (Case c:cc)
{
if (c.IsClosed)
{

Integer OpenChildCase = 0;
for (Case ChildCase : [select id from case where ParentId = :c.id and (isClosed != true)])
OpenChildCase++;
if (OpenChildCase > 0)
c.addError('You are trying to Close a Parent Case that still has open child case! Parent Case number is '+c.casenumber+' or Parent Case id = '+c.id);
}
}
}
 
But now I want to use apex classes and so I created a CloseParentCase_NoOpenChildCase class with the CloseoutParentCase method and so replaced the trigger code to this:
trigger CloseCase_whenNoOpenChildCase on Case (after insert, after update) {

Case[] cc = Trigger.new;

for (Case c:cc)
{
if (c.IsClosed)
{
CloseParentCase_NoOpenChildCase.CloseoutParentCase(c);
}
}
}
And the class I created is as followed: 
public class CloseParentCase_NoOpenChildCase
{

public static void CloseoutParentCase (Case c)
{
if (c.isClosed)
{


Integer OpenChildCase = 0;
for (Case ChildCase : [select id from case where ParentId = :c.id and (isClosed != true)])
OpenChildCase++;
if (OpenChildCase > 0)
c.addError('You are trying to Close a Parent Case that still has open child case! Parent Case number is '+c.casenumber+' or Parent Case id = '+c.id);
}
}
 
 
 
And I wanted to create testmethods that will show when I try to close out a case that has child case, it will fail.  But the problem is it looks like when I run the test, it will fail because of the addError call within the class, so the running of the test will fail.
 For example, in my testmethod, I would do something like the code below, but the problem is it would fail at the statement:     update parent_case;
and this is because it would hit the logic in the the CloseoutParentCase method which issues the addError call.
 
So what is the proper way to write a test method when the logic of the trigger/class itself is to result in a failure when certain situation occurs? 
 
  static testmethod void testCloseoutParentCase ()
{


Case parent_case = new Case(RecordTypeId = '0120000000002Ld',Status ='New');
insert parent_case; // hit the trigger

// make sure Case is created
System.assert(parent_case.id != null);
System.assertEquals(parent_case.Status,'New');


Case SRchild_case0 = new Case(RecordTypeId = '0120000000002Ld',Status ='New',parentid=parent_case.id);
insert SRchild_case0; // hit the trigger

// make sure Case is created
System.assert(SRchild_case0.id != null);

// double check

Case SRchild_case = [ select Status from case where parentid = :parent_case.id];

// make sure Case is created
System.assert(SRchild_case.id != null);


// Now try to update the parent case to Closed, it should fail since we have an open child case
// and therefore parent case status should still be New

parent_case.Status='Closed';
update parent_case;

System.assertEquals(parent_case.Status,'New');
 

delete SRchild_case0;
delete SRchild_case;
delete parent_case;
}
}
 
 
 
 

 

  • February 06, 2009
  • Like
  • 0

Hello all,

I'm working on a project to give users the ability to create secure notes on any object.  The design is going fine except for the last piece: how to encrypt or obfuscate the note so that even administrators browsing cannot read them.

 

Apex does not do encryption (only hashing), so I have to come up with a method for obfuscating the note.  

 

I can do this with JavaScript, but how do I:

1. Obfuscate some text in JavaScript and then save it back to a salesforce field?

 

A secondary question, is there any other way anyone can think of to do this other than javascript?

 

Thanks,

C.

We're having a problem with handling a fault coming back from a Callout.  We are getting an exception stating we received a SOAP fault (we want the fault for the purposes of testing error handling), and I'm unclear on the real problem-- is the problem with our ability to get to the fault data, or did we create a problem with the content of our fault, hence triggering the exception.

 

I have a couple of questions:

 

1) Normally, does any fault throw an exception, or would a fault appear in the response?  I haven't found anything in the documentation that explicitly explains how faults are handled.

 

2) What other methods and members are available for me to examine in the CalloutException other than the common methods (getCause()/getMessage())?  Again, the documentation is vague, and I can't find anything absolute that says CalloutException exactly what CalloutException provides (e.g. like JavaDocs for the APIs).

 

3) The exception we recieve manages to display the standard faultcode and faultstring, and the faultstring appears as what is provided by the exceptions's getMessage() method.  This gives me the sense that the fault is completely successfully parsed, or I'm getting a really poor error message from the API.  Below is the full SOAP Fault we receive.  I read another forum message indicating namespace prefixing was required for items in the detail of the message.  As far as I can tell, this is legal syntax, and other tools importing this WSDL handle faults properly: 

 

 

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
    <ns2:Fault xmlns:ns2="
http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns3="http://www.w3.org/2003/05/soap-envelope">
      <faultcode>ns2:Client</faultcode>
      <faultstring>"IGI0120:CBM5644:The Telephone Number Area Code is incorrect."</faultstring>
      <detail>
        <AAAError:AAAError xmlns="AAA" xmlns:AAAError="AAA">
          <AAAError>
            <RC>1495</RC>
            <MQQ>1</MQQ>
            <MSGNO>1495</MSGNO>
            <MSGTEXT>"IGI0120:CBM5644:The Telephone Number Area Code is incorrect."</MSGTEXT>
          </ICOMSError>
        </AAAError:ICOMSError>
      </detail>
    </ns2:Fault>
  </S:Body>
</S:Envelope>

Does anybody know of a way to perform field level validation in VisualForce.   I would like to enter a field value and if there is an invalid entry, I would like to display an error before the page proceeds to the next field. 

Hi,


Does anyone have an idea of how to work around the string limits in this case.

 

I have an apex code that reads a document object. I can get that fine, and it's a CSV fine. I then want to run through the document and parse it line by line. I can get the body into a blob with document.body, then get the body as a string with the body.toString() method.

 

But the problem here is the limits on a string are 100,000 characters. If my blob is larger than 100,00 characters, then what can I do? I don't have to have it all at once. A loop is find but I don't see a way to do blob.tostring(start byte, end byte).

 

Any ideas?

 

Thanks!

Hey,

I have an apex class that is called when i send an email in my application,
sometimes the class throw this error message:

Attempt to execute a class that never successfully parsed: Static initialization: Myclass.cls

It doesn't happen every time i call the class.
I have done some research at this forum and the apex docs but this message are not listed.

anyone knows what means ? and how to fix it?

thanks,
Hi fellow developers,

I'm trying to emulate the sample in the vf dev guide (Adding Custom List Buttons using Standard List Controllers), but with a twist: using a detail from a master-detail (Account = Master, detail = Flavor_Request__c).

I have both the Apex Class and controller similar to the example in the dev guide:

Code:
public class OpptyFlavorListButton
{
    public OpptyFlavorListButton(ApexPages.StandardSetController controller) {
            controller.setPageSize(10);
    }
}

<apex:page standardController="Flavor_Request__c" recordSetVar="flavors"
    tabStyle="Flavor_Request__c" extensions="OpptyFlavorListButton">
<apex:form >
    <apex:pageBlock title="Edit Status" mode="edit">
        <apex:pageMessages />
        <apex:pageBlockButtons location="top">
            <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandButton value="Cancel" action="{!cancel}"/>
        </apex:pageBlockButtons>

        <apex:pageBlockTable value="{!selected}" var="f">
            <apex:column value="{!f.name}"/>
            <apex:column value="{!f.Request_Type__c}"/>
            <apex:column value="{!f.Sample_Size__c}"/>
            <apex:column headerValue="Status">
                <apex:inputField value="{!f.Status__c}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

 



The buttons are added to the appropriate layouts, however, I keep getting the following errors:
1. Invalid variant 'parent': value 'Account'
2. Invalid variant 'parent': value 'Opportunity'

I get error #1 when trying this from the Account page (related list of flavors)
I get error #2 when trying this from the Opportunity page (related list of flavors)

I'm hitting these errors as the System Administrator who wrote the code...

Any feedback/suggestions would greatly be appreciated.

Thanks,
Larry


Message Edited by Legerdemain on 12-04-2008 08:38 PM

Message Edited by Legerdemain on 12-04-2008 08:39 PM