• Ron Hess
  • PRO
  • 4195 Points
  • Member since 2003

  • Chatter
    Feed
  • 108
    Best Answers
  • 6
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 2514
    Replies

My entire APEX trigger is wrapped in a try/catch block, catching the generic Exception object, but I'm still hitting a fatal System.LimitException.

 

What's the point of try/catch if it doesn't actually catch an exception? 

How can I make sure my try / catch block prevents a fatal error?

 

Here's the relevant snippet:

 

for (Contact c : [SELECT Email, Id FROM Contact WHERE AccountId = :account_id LIMIT 10]) {
  if(c.Email != null){
    try {
      Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
      message.setTemplateID(email_template.Id);
      message.setWhatId(detail.Id);
      message.setTargetObjectId(c.Id);
      Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
    }    

    catch (System.LimitException e) {

      // I don't really care if the email fails.

      // I just don't want it to break my data entry process.

     }

     catch (Exception e) {

      // I don't really care if the email fails.

      // I just don't want it to break my data entry process.
    }
  }

}

 

updated: even explicitly catching system.limitexception fails.

Are there any examples to creating a time-based trigger? I am needing to remove the value in a lookup field after 30 days field was populated.

Seems like the guide is trying to be clear about this, but not for me. Most of the examples in other questions I've found about this topic are WAYYYY too long to read through, so I'll try to make mine simple:

 

Here's the first part of my controller extension:

 

 

public class Controller_OppItemEdit_OverRide
{

OpportunityLineItem OLI public Controller_OppItemEdit_OverRide (ApexPages.StandardController stdController) { this.OLI = (OpportunityLineItem)stdController.getRecord(); }

Now according to the APEX Guide:

"Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other fields, including fields from any related objects, must be queried using a SOQL expression."

 

That would seem to mean that if I reerence a field that is on the Controller Object in the VF Page, I don't have to query for it using SOQL. But from my experence, I'm not sure I believe this. To continue:

 

 

public OpportunityLineItem getOLI()
    {
    	return OLI;
    }
    
    public void setOLI(OpportunityLineItem LI)
    {
    	this.OLI = LI;
    }

 

 

Adding these getter and setter methods or the standard Controller seems redundant to me, but someone else did this in an example and said it worked for them in their instance, so I include it here. Maybe that;s the problem, maybe not - I don't know.

 

 

public PageReference Save()
    {
system.debug('MRC is '+OLI.MRC__c+' and NRC is '+OLI.NRC__c);
    	
OLI.TotalPrice = OLI.MRC__c + OLI.NRC__c;
    	
update OLI;

return null;

}

 

 

That's it for the Controller code in its simplest form. All of the fields are referenced in the VF Page as inputFields. So, I would assume that if I change one of those inputFields, and click a button that calls an Update to the record, that the record would be updated with the new values.

This assumption is clearly wrong as the record does not get updated.

Here is the essence of the Page:

 

 

<apex:page standardController="OpportunityLineItem" extensions="Controller_OppItemEdit_OverRide" >
<apex:form >
<apex:outputPanel id="thePanel">
<apex:pageBlock id="theBlock" >
<apex:pageBlockButtons >

<apex:CommandButton action="{!save}" value="Save Changes" rerender="thePanel"/>

 </apex:pageBlockButtons>
<apex:PanelGrid columns="2"> New MRC:&nbsp; <apex:inputField value="{!OpportunityLineItem.MRC__c}"/> New NRC:&nbsp; <apex:inputField value="{!OpportunityLineItem.NRC__c}"/> </apex:PanelGrid> </apex:pageBlock> </apex:outputPanel> </apex:form> </apex:page>

  So that's pretty much it. I add a value to the inputField, and click the Save button. The values in the page remain, however the debug statement indicates the values being set are still null, even though the debug log says the update went through as expected. Nows the previously saved values for the record are appearing in the page, but the new values do not appear to be getting to the database.

 

To resolve this I added a query for the Line Item record in the Constructor method:

 

 

OpportunityLineItem OLI;

public Controller_OppItemEdit_OverRide (ApexPages.StandardController stdController) 
    {
        this.OLI = (OpportunityLineItem)stdController.getRecord();
         OLI=[SELECT id, OpportunityID, MRC__c, NRC__c, ...
    		 FROM OpportunityLineItem
    		 WHERE id = :OLI.id];
    }

// And then I added individual properties for each of the fields:

    public decimal MRC {get; set;}
    public decimal NRC {get; set;}

 

 

Now, I can change the inputFields into InputText boxes in the page. And because there is now a property to receive and provide these values, I can now set the OLI record values from the properties:

 

 

public PageReference Save()
    {
        if (MRC != null)
    		OLI.MRC__c = MRC;
    	if (NRC != null)
    		OLI.NRC__c = NRC;
    update OLI;
    }

 

 

This does update the values in the record, which is great - except that I'm having to write customized logic for what should be already available by virtue of using a standard controller and inputFields. I would go ahead and use this except that one of the fields I need is a picklist, and setting up the SelectOptions for a field that is already available on the object means the list of values has to be updated whenevfer someone changes them in SFDC. I realize I could write some long getDescribe method to extrsact the current set of field values, but that seems kind of stupid in this case.

When I add the inputField for this field, all of the current options are already availavble for selection - except the selection doesn't save.

 

I can only guess at this point that I'm declaring the extension incorrectly, or overwriting something but the Dev guide is pretty clear:

 

 

public class myControllerExtension {

    private final Account acct;
    
    public myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }

By the way, above this example is the following statement:

   ApexPages.StandardController sc = new ApexPages.StandardController(sObject);

The example below it doesn't use this statement. Obviously its a way to create and instantiate a new Standard Controller variable, but there is no indication as to why I would want to use this statement, or if I would need to use it, or if the example below is the equivalent of this statement when used as part of an extension.

 

So, in order to actually get the values I input into the inputFields in a page using a StandardController extension, what am I missing??

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

sdf

Hi,

I have a custom apex class (which works properly when executed anonymously through the IDE) and would like to be able to invoke the class with the click of a button on a visual force page.  I have a feeling it's really simply, but i just can't seem to figure it out.

 

Here's what I have so far:

 

 

<apex:page >
<apex:enhancedList type="SPC_Settings__c" height="358" rowsPerPage="10" id="SPCSettings" />
<apex:form >
<br />
<apex:commandButton style="float:right;" action="sforce.apex.execute('SPCSettingsUpdate',{},{}" value="Update" id="btnUpdate" />
</apex:form>
</apex:page>

 

Any help would be greatly appreciated!

 

  • April 13, 2010
  • Like
  • 0
Can we perform database operations on chatter related objects using the existing Adobe Flex toolkit version for Flex. If no then is the new toolkit available by which I can access chatter objects in my Adobe Flex applications? 
I've got code (written by a consultant) that has approx. 15K lines split across about 20 .page files. The first 40 or so lines of each page is basically identical (info about the Account, etc.) This is bloated code! Is there a way I can make things more readable by simple having one .page which is then "imported" or "included" by the other 20? Thanks.
  • March 18, 2010
  • Like
  • 0

I'm trying to create a picklist using <apex:selectList>, populate it with my own selections, and require the field to contain a value. Here's my code:

 

 

<apex:selectList required="true" size="1" value="{!SDQA__c.Inspector_Stamp1__c}" > <apex:selectOption itemLabel="{!SDQA__c.Inspector_Stamp1__c}" itemValue="{!SDQA__c.Inspector_Stamp1__c}" /> <apex:selectOption itemLabel="{!$User.FirstName} {!$User.LastName}" itemValue="{!$User.FirstName} {!$User.LastName}" /> <apex:selectOption itemLabel="N/A" itemValue="N/A" /> </apex:selectList>

 

The first value defaults to whatever the field currently contains (which will initially be null). The other two options are either the users First Name+Last Name, or N/A. The problem is that even though I have required="true", there is no validation enforced on this field (The red "required" bar doesn't even show up beside it). Anybody have an idea as to why that is?

 

 

Hi everyone,

 

I am having avisualforce page with customfields,and i want to assign  a value stored in a variable ti it iam tryimg to do it like this but its not working plz help me with an example...

 

var duplicate=anu;

 

 document.getElementById('{!$Component.form1.name}').value=duplicate;

 

<apex:inputField id="name" value="{!CAF_Bank__c.Bank_Name__c}">

 

can i do this ..

 

  plz some one help me how can i assign a variable  to the current field in a form...

         

                                                                                        Thanks&Regards,

                                                                                                Anu...

 

 

   

 

 

Apex Gurus,

 

I'm trying to create Account Team members and setting the Account Share as 'Read/Write' for all objects but am getting the error  INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST. Here's the code:

 

Database.SaveResult[] saveResults = Database.insert(members,false);

AccountShare[] newShare = new AccountShare[]{}; //list of new shares to add

integer newcnt1=0;

for(Database.SaveResult sr : saveResults){

if(!sr.isSuccess()){

Database.Error emsg = sr.getErrors()[0];

system.debug('\n\nERROR ADDING TEAM MEMBER:'+emsg);

}else{

newShare.add(new AccountShare(UserOrGroupId = members[newcnt1].UserId, AccountId=members[newcnt1].Accountid, AccountAccessLevel='Read/Write', OpportunityAccessLevel='Read/Write', CaseAccessLevel='Read/Write', ContactAccessLevel='Read/Write'));

}

newcnt1++;

}

if(newShare.size()>0){

System.debug('No. of shares to be created: '+newShare.size());

Database.SaveResult[] lsr0 =Database.insert(newShare,false); //insert the new shares

Integer newcnt0=0;

for(Database.SaveResult sr0:lsr0){

if(!sr0.isSuccess()){

Database.Error emsg0=sr0.getErrors()[0];

system.debug('\n\nERROR ADDING SHARING:'+newShare[newcnt0]+'::'+emsg0);

}

newcnt0++;

}

System.debug('No. of shares created: '+newcnt0);

}


 

I get an error each line of team share that i'm trying to insert:

 

Bad value for restricted picklist field: Read/Write;getStatusCode=System.StatusCode.INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST 

Been stuck at it for 2 days now so appreciate any help possible to eradicate the above!

 

Thanks in advance,

-Manu 

Message Edited by md1 on 15-12-2009 02:55 PM
  • December 15, 2009
  • Like
  • 0

The following code is working well in a VF page, but fails when deployed to Sites with error message {faultcode: 'UNKNOWN_EXCEPTION', faultstring: 'UNKNOWN_EXCEPTION: Site under construction'}.  

 

I'm guessing {!$Api.Session_ID} is not supported under the Sites Guest User?

 

I'm not using a controller. All AJAX methods call into static WebServices on a global class. 

 

<apex:page sidebar="false" showHeader="false">

<apex:includeScript value="/soap/ajax/17.0/connection.js"/>

<apex:includeScript value="/soap/ajax/17.0/apex.js"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript">

$(function() {

sforce.connection.sessionId = '{!$Api.Session_ID}';

$("#testLink").click( function(){

sforce.apex.execute("MyWebService", "GetSomething", {},

{

onSuccess : function(result, source) { //databind JSON result to DIV output },

onFailure : function(error){//handle failure}

});

});

}

</script>

<a href="#" id="testLink">Test Link</a>

<div id="output"></div> 

</apex:page>

 

Before it's suggested, I'm aware <apex:actionFunction> provides an async AJAX interface and I've tried this, but most UI controls today databind to JSON on callback. The actionFunction oncomplete attribute appears to only notify the page that rerendering has occurred, and doesn't actually provide access to the response payload for use in custom data binding (please correct me if I'm wrong and can achieve the same results using actionFunction).

  

 

Hi all,

 

I have a custom input field called Start Date and i want to use a calander widget on it.

 

Any pointers on how to do that in Visualforce?

 

Here is where i would want to attach it...Any help is much appreciated!

 

 

<apex:pageBlockSectionItem > <apex:outputLabel value="Start date(YYYY-MM-DD):" for="startDate"/> <apex:outputPanel layout="block" styleClass="requiredInput"> <apex:outputPanel layout="block" styleClass="requiredBlock"/> <apex:inputText value="{!startDate}" id="startDate" required="true"/> </apex:outputPanel> </apex:pageBlockSectionItem>

 

 Thanks!

Mukul

 

  • July 26, 2009
  • Like
  • 0

Is there any way to retrieve the Report data? I didnt find the any API call for salesforce which supports this.

Your response is appreciated. 

 

Thanks

shaan 

  • July 22, 2009
  • Like
  • 0

 I have a visual force page which needs to be rendered as a PDF, but when I set renderAs = "PDF"  it ignores my Javascript entirley. I can't even do a document.write('test');   My issue is that the field labels in the PDF I am rendering need to be dynamic based on the users language. I have written a class to do this for me based on the API field name, but when I try and call it in this page I get nothing.  Anyone have any suggestions on how to dynamically pass field labels to a VF page that will be rendered as a pdf? 

 

 

 

Hi All,

 

I  registered for Force.com Site Free Edition. And I created one sample app. I am facing one issue while configuring Site for public access. I am not able to allow users of my customer portal for Login. When I clicked on Login Settings. It simply says , Login not Allowed.

 

 

Can anyone please tell me how to enable this option same as Developer Edition. ??

 

In developer edition we can enable login by going to Customize --> Customer Portal --> Settings.

 

But in Free Edition there is not Customer Portal Option.

 

One more help. As mentioned in docs  , The only difference between Free Edition and Developer Edition is we can deploy application on Free Edition , but not it Developer Edition.

 

Can anyone please tell me the  procedure to deploy the app on Free Edition  or please refer any doc,  so that I can learn it from there.

 

Thanks in Advance,

Brijesh Thakur

Hi, 

 

I want to display some text in bold style. I try to store it in differnt way but salesfoce do not parce that tag and display it as it is. Please help!

 

e.g.

 

Data in Database :-  

Visual Force development for creating <b>new</b> sites.  

 

page Output :- 

Visual Force development for creating <b>new</b> sites.  (It should display new as bold.)

 

please help! 

 

 

 

 

 

I have a VisualFoce page that I've created to perform a quick case add function.  This page is called from a custom object, via button, called Projects__c.  What I would like to do is save my new cases with the userID of the user who is logged in.

 

Can I use the UserInfo.getUserId() method directly in VF or do I need a controller extension to do this?  If so, how do I return the value from the class to the VF page?

 

Thanks

 

 

Hi all,

 

I have this issue where i cant display my custom object;s fields on the page. Can anyone help me out?

 

Here is my Controller Code:

 

public class newScoreRuleController {

public List<ScoringRule__c> ScoringRule { get; private set;}

public String getFieldName() {
String s = ApexPages.currentPage().getParameters().get('fld');
return s;
}

public List<SelectOption> GetFieldsForObject(Map<String, Schema.SObjectField> objFields, string lblPrefix, string fldPrefix) {
// Build a list of field names to use to iterate the Map of field object pointers
Set <string> flds = new Set <String>();
flds = objFields.keySet();

// Add the keyset of field names to a list so that it can be sorted
List<String> fldList = new List<String>();
for (string f : flds) {
fldList.add(f);
}
fldList.sort();

List<SelectOption> options = new List<SelectOption>();
for (string f : fldList) {
string fldName = objFields.get(f).getDescribe().getName();
string fldLabel = objFields.get(f).getDescribe().getLabel();
string fldType = ('' + objFields.get(f).getDescribe().getType()).replace('Schema.DisplayType.', '') ;
if (fldType <> 'REFERENCE' && fldType <> 'ID' && fldName <> 'IsDeleted' && fldName <> 'SystemModstamp') options.add(new selectOption(fldType + '/' + fldPrefix + fldName, lblPrefix + fldLabel ));
if (fldName == 'OwnerID') {
options.add(new selectOption('STRING/' + fldPrefix + 'Owner.Name', lblPrefix + 'Owner.Name'));
options.add(new selectOption('STRING/' + fldPrefix + 'Owner.Alias', lblPrefix + 'Owner.Alias'));
options.add(new selectOption('STRING/' + fldPrefix + 'Owner.Department', lblPrefix + 'Owner.Department'));
options.add(new selectOption('STRING/' + fldPrefix + 'Owner.Division', lblPrefix + 'Owner.Division'));
} else if (fldName == 'LastModifiedByID') {
options.add(new selectOption('STRING/' + fldPrefix + 'LastModifiedBy.Name', lblPrefix + 'LastModifiedBy.Name'));
options.add(new selectOption('STRING/' + fldPrefix + 'LastModifiedBy.Alias', lblPrefix + 'LastModifiedBy.Alias'));
} else if (fldName == 'CreatedByID') {
options.add(new selectOption('STRING/' + fldPrefix + 'CreatedBy.Name', lblPrefix + 'CreatedBy.Name'));
options.add(new selectOption('STRING/' + fldPrefix + 'CreatedBy.Alias', lblPrefix + 'CreatedBy.Alias'));
}
}

return options;
}


public List<SelectOption> getLeadFields() {
Map<String, Schema.SObjectField> leadFields = Schema.SObjectType.Lead.fields.getMap();
newScoreRuleController critClass = new newScoreRuleController();
//searchCriteria critClass = new searchCriteria();
// Return SelectOption lists for the Contact and Account objects
List<SelectOption> sel1 = critClass.GetFieldsForObject(leadFields, '', '');
List<SelectOption> options = new List<SelectOption>();
options.add(new selectOption('', '- select field -'));
for (Selectoption selOpt : sel1) {
options.add(selOpt);
}
return options;
}

public List<SelectOption> getScoreRules() {
List<SelectOption> options = new List<SelectOption>();
options.add(new selectOption('eq', 'Equals'));
options.add(new selectOption('ne', 'Not Equal'));
options.add(new selectOption('gt', 'Greater Than'));
options.add(new selectOption('ge', 'Greater or Equal To'));
options.add(new selectOption('lt', 'Less Than'));
options.add(new selectOption('le', 'Less or Equal To'));
options.add(new selectOption('starts', 'Starts With'));
options.add(new selectOption('contains', 'Contains'));
options.add(new selectOption('notcontain', 'Does Not Contain'));
options.add(new selectOption('in', 'Includes'));
options.add(new selectOption('notin', 'Excludes'));
return options;
}

public List<SelectOption> getScoreVal() {
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('A','A'));
options.add(new SelectOption('B','B'));
options.add(new SelectOption('C','C'));
return options;
}

public List<SelectOption> getWeightList() {
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('0','0'));
options.add(new SelectOption('1','1'));
options.add(new SelectOption('2','2'));
options.add(new SelectOption('3','3'));
options.add(new SelectOption('4','4'));
options.add(new SelectOption('5','5'));
options.add(new SelectOption('6','6'));
options.add(new SelectOption('7','7'));
options.add(new SelectOption('8','8'));
options.add(new SelectOption('9','9'));
return options;
}

public PageReference step1() {
return Page.scoreRuleStep1;
}

public PageReference step2() {
// Save some stuff here
// Pass it through URL to the next page
return Page.scoreRuleStep2;
}

public PageReference cancel() {
PageReference leadsPage = new ApexPages.StandardController(lead).view();
leadsPage.setRedirect(true);
return leadsPage;
}


public PageReference save() {
PageReference leadPage = new ApexPages.StandardController(lead).view();
leadPage.setRedirect(true);
return leadPage;
}

}

 Here is my Visual Force Code:

 

<apex:page controller="newScoreRuleController" tabStyle="Lead">
<script>
function confirmCancel() {
var isCancel = confirm("Are you sure you wish to cancel?");
if (isCancel) return true;

return false;
}
</script>
<apex:sectionHeader title="Scoring Rule Wizard" subtitle="Step 2 of 2"/>
<apex:form >
<apex:pageBlock title="Choose a scoring rule" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton action="/apex/scoreRuleStep1" value="Previous"/>
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Choose a scoring rule">
<apex:pageBlockTable value="{!ScoringRule}" var="sr" id="theTable" rowClasses="odd,even"
styleClass="tableClass" rows="5">
<apex:column >
<apex:facet name="header">Field</apex:facet>
<apex:facet name="footer"></apex:facet>
<apex:outputText value="{!fieldName}"/>
</apex:column>
<apex:column width="25%">
<apex:facet name="header">Rule 1</apex:facet>
<apex:inputField value="{!sr.ScoringRule_Rule1__c}"/>
</apex:column>
<apex:column width="25%">
<apex:facet name="header">Value 1</apex:facet>
<apex:inputText value="{!sr.ScoringRule_Val1__c}"/>
</apex:column>
<apex:column width="25%">
<apex:facet name="header">Rule 2</apex:facet>
<apex:inputField value="{!sr.Rule2__c}"/>
</apex:column>
<apex:column width="25%">
<apex:facet name="header">Value 2</apex:facet>
<apex:inputField value="{!sr.Val2__c}"/>
</apex:column>
</apex:pageBlockTable>

<!-- Within a pageBlockSection, inputFields always display with their
corresponding output label. -->
</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:page>

 

I am very new to Apex code development. 

  • June 16, 2009
  • Like
  • 0

I have an outputPanel that has a radioList within it that I am using with an actionSupport .  I am using the actionSupport to rerender another outputPanel through the use of AJAX.  Now I would like the radioList selection to rerender more than one Panel.  I know I can obviously move the second pageBlock within the already controlled outputPanel but I was wondering if you can rerender multiple outPutPanels off of a single actionSupport?

 

Hi,

 

I have a custom payment object that is the basis for a page to save new payments.

 

I also want to attach multiple sales orders to these payments using a list with checkboxes.

 

So the process:

1.  New payment

2.  Choose Account for payment

      2.5  The list of sales orders without payments for this account rerenders (onblur event)

3.  Enter the amount and Date

4.  Check from the list which sales orders apply to this payment

5.  Click Save (actually process records at the moment)

 

All of that works great.

 

Unfortunately, when I go to save the Payment - only information that was input before the onblur event kicked off is saved.

 

For instance, usually the user enter's the Description(name) and then the Account.  The list of sales orders is refreshed based on the Account. On save, the amount and date don't get saved.  If you enter the amount, then the Description and then the Account - the amount is saved.

 

I have tried every thing I can think of and none of it made a dent.  Any help would be greatly appreciated.

 

note on the code: its got left over stuff in it at the moment commented out from various attempts - i also removed the checkboxsave since the problem happens before that.

<apex:page standardController="PF_Payment__c" extensions="PaymentsExtension"> <p/> <apex:form > <apex:pageBlock title="Payments"> <table> <tr cellpadding="4"> <td>Description:</td> <td> <apex:inputField value="{!PF_Payment__c.name}" required="true"/></td> </tr> <tr> <td>Account: </td> <td><apex:inputField id="ifAccount" value="{!PF_Payment__c.Account__c}"> <apex:actionSupport event="onblur" rerender="salesorderlistblock"/> </apex:inputField></td> </tr> <tr> <td>Amount:</td> <td><apex:inputField id="pAmount" value="{!PF_Payment__c.Amount__c}"/> </td> </tr> <tr> <td>Date Paid:</td> <td><apex:inputField value="{!PF_Payment__c.Date_Paid__c}"/> </td> </tr> <tr> <td>Status:</td> <td><apex:inputField value="{!PF_Payment__c.Status__c}"/> </td> </tr> </table> </apex:pageBlock> </apex:form> <apex:form > <apex:pageblock id="salesorderlistblock"> <apex:pageBlockButtons > <apex:commandButton value="Process Selected" action="{!Save}" rerender="returninfo"/> </apex:pageBlockButtons> <apex:pageBlockTable value="{!Sales_Order}" var="salesorder" cellpadding="4" border="2"> <apex:column headervalue="Sales Order">{!salesorder.so.name}</apex:column> <apex:column headervalue="Record Type">{!salesorder.so.recordtype.name}</apex:column> <apex:column headervalue="Creation Date">{!salesorder.so.createddate}</apex:column> <apex:column headervalue="Description">{!salesorder.so.Description__c}</apex:column> <apex:column headervalue="Price">{!salesorder.so.Price__c}</apex:column> <!-- <apex:column headervalue="Payment">{!salesorder.so.Payment__c}</apex:column> --> <!-- <apex:column headervalue="Payment">{!salesorder.so.Payment__r.name}</apex:column> --> <apex:column headervalue="Add to Payment"> <!-- onclick="!setCurrentStatus('something happened')" --> <apex:inputCheckbox value="{!salesorder.selected}"/> <!--<input id="thecheckbox" type="checkbox" value="{!salesorder.selected}" name="thecheckbox" /> --> <!-- <apex:actionSupport action="{!CurrentStatus}" event="onclick" rerender="returninfo"/> --> </apex:column> </apex:pageBlockTable> </apex:pageBlock> <apex:pageblock id="returninfo"> Current Status: {!CheckBoxDebug} </apex:pageblock> </apex:form> </apex:page>

and the extension

 

 

public class PaymentsExtension { public PF_Payment__c pymt; ApexPages.StandardController controller; public PaymentsExtension(ApexPages.StandardController controller) { this.pymt = (PF_Payment__c)controller.getRecord(); this.controller = controller; } private String CurrentStatus = 'Nothing has happened'; public String getCheckBoxDebug() { return CurrentStatus; } public PageReference CurrentStatus() { CurrentStatus = CurrentStatus + ' something '; return null; } List<saleswrapper> salesorderList = new List<saleswrapper>(); List<Sales_Order__c> selectedsalesorders = new List<Sales_Order__c>(); public PageReference Save() { controller.save(); /*upsert this.pymt didn't work*/ /*this.pymt.save(); didnt work*/ PageReference home = new PageReference('/a08/o'); home.setRedirect(true); return home; /* return home; */ } public PageReference getSelected() { selectedsalesorders.clear(); for(saleswrapper sw : salesorderList) if(sw.selected == true) selectedsalesorders.add(sw.so); /* CurrentStatus='something happened'; */ return null; } public List<saleswrapper> getSales_Order() { string queryid = pymt.Account__c; /*= Accountif */ if (queryid != null) { salesorderlist.clear(); for(Sales_Order__c s : [Select id, name, RecordTypeid, RecordType.Name, CreatedBy.Name, CreatedDate, Description__c, Price__c, Payment__c, Payment__r.name from Sales_Order__c where Payment__c = NULL AND Account__c = :queryid]) { salesorderlist.add(new saleswrapper(s)); } } else { for(Sales_Order__c s : [Select id, name, RecordTypeid, RecordType.Name, CreatedBy.Name, CreatedDate, Description__c, Price__c, Payment__c, Payment__r.name from Sales_Order__c where Payment__c = NULL AND Account__c = :System.currentPageReference().getParameters().get('accountid')]) salesorderlist.add(new saleswrapper(s)); /*return salesorderlist; */ } return salesorderlist; } public class saleswrapper { public Sales_Order__c so {get; set;} public Boolean selected {get; set;} public string sonumber {get; set;} public saleswrapper(Sales_Order__c s) { so = s; selected = false; } } }

 

 

 

Message Edited by Dpal on 06-11-2009 11:50 PM
  • June 12, 2009
  • Like
  • 0

Hi All,

I am trying to integrate public sites to show data from google blogs, but the issue is that everytime I fetch data I am asked to provide access to gdata API. I am using Google toolkit and AuthSub authentication process. Also I want this authentication process to be hidden from end user and should actually be once. Is there a API where i can send google signing credentials in URL and that returns me token to access my data anytime.

 

Thanks

Siddharth

I've reported a bug to the partner portal, case 08197046

 

I'd like to understand if anyone else has reported this issue or worked around it.

 

we have a simple rule to identify duplicates on the Name field.

 

AND(OR(ISNEW(),ISCHANGED(Name)), VLOOKUP( $ObjectType.Supplier__c.Fields.Name , $ObjectType.Supplier__c.Fields.Name ,Name)<>NULL)

 

 

and a simple testmethod 

 

System.assertEquals( 0, [ select id from Supplier__c ].size() );
Supplier__c supplierObj = new Supplier__c();
supplierObj.Name= 'Test Supplier';    
insert supplierObj;

 

My API setting is 25.0, and the assert passes, since no data is visible to my test method.

 

now, i run my test method and it fails on the insert statement ( yes the database has a Test Supplier )

 

 

18:05:03.386 (5386958000)|SOQL_EXECUTE_BEGIN|[64]|Aggregations:0|select id from Supplier__c
18:05:03.388 (5388301000)|SOQL_EXECUTE_END|[64]|Rows:0
18:05:03.388 (5388663000)|DML_BEGIN|[67]|Op:Insert|Type:Supplier__c|Rows:1
18:05:03.400 (5400613000)|CODE_UNIT_STARTED|[EXTERNAL]|Validation:Supplier:new
18:05:03.400 (5400628000)|VALIDATION_RULE|03dE00000000EbW|Unique_Name
18:05:03.400 (5400914000)|VALIDATION_FORMULA|AND(OR(ISNEW(),ISCHANGED(Name)), VLOOKUP( $ObjectType.Supplier__c.Fields.Name  ,  $ObjectType.Supplier__c.Fields.Name ,Name)<>NULL)|Name=Test Supplier , $ObjectType.Supplier__c.Fields.Name=Supplier__c.Name
18:05:03.400 (5400929000)|VALIDATION_FAIL
18:05:03.404 (5404672000)|CODE_UNIT_FINISHED|Validation:Supplier:new
18:05:03.405 (5405933000)|DML_END|[67]
18:05:03.408 (5408566000)|VF_PAGE_MESSAGE|This Supplier already exists
18:05:03.408 (5408686000)|EXCEPTION_THROWN|[67]|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This Supplier already exists: [Name]
18:05:03.409 (5409633000)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This Supplier already exists: [Name]

 

I can conclude that VLOOKUP() can see data even if called from a test method that cannot see data.

 

This makes validation rules look like a serious hazard when writing test methods, how could i know what data is already in the org ? How can i protect my test methods from data that exists ?

 

I turned off this validation rule, and sure enough the test method behaves as expected.

 

thanks for any ideas.

 

 

I've updated the connector for PE to allow use of the 16.0 API and office toolkit 4.0

 

All new downloads are located here : http://code.google.com/p/excel-connector/

 

The old site will redirect to the new site on code.google.com

 

Downloads:

http://code.google.com/p/excel-connector/downloads/list

 

enjoy.

:smileyvery-happy:

 

PS: connector downloads hit 100,000 earlier this year.

I had to write this today, may be usefull to others
 
I used this to fetch the body of large text fields which contain data greater than 4096 bytes.

Code:
Sforce.Dynabean.prototype.getLargeText = function(propName) { 
 // like get(), but will unpack document body elements which are greater than 4096...
 var body=''; 
 try { 
  var tmp = this.getItem(propName).value; // still could return a null, watch for that when calling
  
  if ( Sforce.Util.dltypeof(tmp) == "domelement" ) {  // see what type of object tmp is...
   for (var i=0; i < tmp.childNodes.length; i++) { 
    body += tmp.childNodes[i].textContent; 
   } 
  } else { // normal string if body is < 4096 bytes 
   body = tmp; 
  } 
 } catch (e) { throw(e); }
  
 return body; 
};

 

Download Version 6.13

requires this Outlook Edition for the new COM object (thanks foghorn..)

guess it should be AppExchange connector...

my favorite new feature is the live clickable hyperlink created in your worksheet when the conenctor reads a HYPRELINK() formula field in your sforce database.

have fun, report issues,
share & enjoy

Message Edited by Ron Hess on 01-21-2006 11:05 PM

fresh doc, pushed yesterday on the appexchange resource page, new publisher info.

http://www.salesforce.com/appexchange/resources_appexchange.jsp

Download the step-by-step guide to publishing apps on the AppExchange
http://www.salesforce.com/us/appexchange/resources/salesforce_appexchange_publish_guide.pdf

Also, please let us know what other doc you feel is missing to help tie together the entire AppExchange vision with complete documentation on how to develop and publish for the platform. We are working on more docs, so I want to make sure these cover the areas that are of concern to this community.

thanks,

not that you would ever need this, however it appears that the AJAX sforceClient does not like 15 charID's in Retrieve, so I ported this late last night from the java version posted elsewhere.

only tested for a short time, but it appears to work.

function normaliseSforceID( id) { // fluff up a 15 char id to return an 18 char id
 if (id == null) return id;
 id = id.replace(/\"/g, ''); // scrub quotes from this id
 if (id.length != 15) {
  //print('well, id is not 15, bye' + id + ' ' + id.length);
  return null;
 }
 var suffix = "";
 for (var i = 0; i < 3; i++) {
  var flags = 0;
  for (var j = 0; j < 5; j++) {
   var c = id.charAt(i * 5 + j);
   if (c >= 'A' && c <= 'Z') {
    flags += 1 << j;
   }
  }
  if (flags <= 25) {
   suffix += "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(flags);
  } else {
   suffix += "012345".charAt(flags-26);
  }
 }
 return id + suffix;
}

 

I am trying to write a query, using SOQL which locates a double value which is less than zero.

I can store a negative number, query the record by ID and get the negative number back, but in SOQL i can't specify this in a where clause.

so, using sforce explorer:

Select lat__c, lon__c from Account where lat__c > 37.36033397019124 and lat__c < 37.426343057829385 and lon__c > -121.97999954223633
and lon__c < -121.84335708618164

generates an error MALFORMED QUERY
unexpected char: "-"

if i try to escape the minus sign i get unexpected char "\"

i'm sure this is somewhere in the doc, but i couldn't find it on first pass search.

thanks

I have created a scontrol which grabs some information from objects within the system and then opens the "send an email" dialog using javascript like this

location.replace("/email/author/emailauthor.jsp?" +
    "retURL=%2F" + opp_id +
    "&p3_lkid=" + opp_id +
    "&p2_lkid=" + to_id +
    "&p4=" + cc_line +
    "&p6={!Account_Name} request for connection to "+supplier.Item('Name').Value +
    "&p7=" +body_str
    );

This works, unless body_str is too long ( more than  ~ 1K ), but I know the Select Template feature does write larger strings into this body window, I'm looking for an example or tips on how this is done.

I suspect that the Select Template function (openTemplateSelector(event)) does it's thing then writes the finished body back into opener.document.editPage.p6.innerHTML to populate the body.

Am I on the right track with this ?

I would like to do this same thing to create a larger body than is possible using the "on the url" method

does anyone have tips / tricks / examples handy ?

it appears that i need to wait until the location.replace has finished drawing before making any change to the new location form.

thanks !

I'm stumped on making my web to case trigger any workflow rules, has anyone tried this ?

I'd like a new case submited via the web-to-case to trigger a "created, contains subject" rule in the workflow, however nothing I have tried has worked yet.

has anyone seen this issue ?
gotten it to work ?

if this does not work I'm forced to write a polling job.
http://sforce.sourceforge.net/excel/downloads.htm

I got excited at the recent user group after talking with some of the folks using the connector to get day to day chores done quickly, so i went home and worked out a new feature.

One comment that came up was that inserting records one by one required you to watch over the process as one bad record would stop the bulk load.

After clarifying with Benji and Adam how the create() call works in the office toolkit i was able to refactor my create() code to easily pass a batch of rows to create(), then pick up the return values (id or fail msg) directly from the array which was constructed and passed in to create().

The user interface available within excel for delivering these messages required a bit of creativity, I used the "comment" object on the cells which contain the row which failed to insert. The msg is taken directly from the SObject returned by the toolkit.

The result is that one or several failed create calls will not stop the batch from proceeding. If there are failed create()'s then i message the user at the end of the operation, leaving "new" in the rows which failed, writing the object ID's where we got a successful record inserted.

fixed one other bug with nul group names, also fixed some references to custom objects which were passed into ref_id() and overwritten by a nul string.

The user groups are cool, check them out if you are able.

I'm posting this version here to try and get some more feedback on the new features before posting on sourceforge, which I hope will be soon.


This version, 5.30 has lots of minor fixes but a few cool new features


Option Dialog to configure the ServerURL, ( allows you to default to 5.0)


Option to trigger assignment rules for Lead and Case insert


Option to use API Names not labels


new feature in a query filter allows you to use TODAY , TODAY - 1 or TODAY + 1 , handy for pulling a window of data


Not to mention the most recent change a method or three of building a Join between two or more tables is described in the On line Help file


added mapping for record types and owner ID's now will display the names instead of the actual ID's, also fix a bug with large queries


http://sforce.sourceforge.net/excel/index.htm


After a bit more testing I will post this out on the primary download link under sforce.sourceforge, but you can try it out now, please let me know if you see problems or regressions.



PS: I've posted the latest version on the http://sforce.sourceforge.net/excel/index.htm
site, this version is now one rev back

have fun,


Ron Hess


Message Edited by Ron Hess on 12-17-2004 10:47 PM

Message Edited by Ron Hess on 01-25-2005 05:55 PM

handy tool i've written to request and later download the weekly backups.  I put this in my scheduled tasks for Wed night and Friday morning, first time requests the backup, second fetches it.

it's not really using sforce, but it sure is handy, you will have to modify it to locate the backup file to your own network name space.

It could easliy be modified to use sforce to get the session id, because it arrives at the frontdoor.jsp early on.  This depends on the contents of the web pages, so it's bound to break someday... (aka: scraping)

I put it here because it's written in perl

have fun

Ron Hess

With the new url format my simple smart tags dll just got smarter (after I tweaked the patern)

now works for many entities

here is the code for the recognizer, the rest I got from the samples in the smart tags resource kit

it matches anything with 15 chars starting with 00, simple but i've found it handy when staring at spreadsheets full of account ID's

-----------------------------------------
Public Sub ISmartTagRecognizer_Recognize(ByVal Text As String, _
    ByVal DataType As SmartTagLib.IF_TYPE, ByVal LocaleID As Long, _
    ByVal RecognizerSite As SmartTagLib.ISmartTagRecognizerSite)
   
    Dim regEx, Match, Matches   ' Create variable.
    Set regEx = New RegExp   ' Create a regular expression.
    regEx.Pattern = "00............."   ' Set pattern, this is for accounts and oppo and ?
    regEx.IgnoreCase = False ' case sensitivity.
    regEx.Global = True   ' Set global applicability.
    Set Matches = regEx.Execute(Text)   ' Execute search.
    Dim index As Integer, termlen As Integer
    Dim propbag As SmartTagLib.ISmartTagProperties
    For Each Match In Matches   ' Iterate Matches collection.
        index = InStr(Text, Match)
        termlen = 15
        Set propbag = RecognizerSite.GetNewPropertyBag
        RecognizerSite.CommitSmartTag _
            "schemas-neoforma-com/neofsalesforce#oppo", _
            index, termlen, propbag
   Next
done:
End Sub

perhaps the most exciting feature of S3 for our support team, but I cannot find the link ?

from the help:

Installing Outlook Edition

To download and install Outlook Edition:

  1. Shut down Outlook before beginning the installation.
  2. Click My Setup | Personal Setup | Outlook Edition.
  3. Click Install Now.


I'm not able to find the link "Outlook Edition" in my presonal setup??

i've opened a case in self serv...

well, the backwards compat feature (mentioned on this board), to support old style ".jsp" driven web integration links appears to be not working.

In the new release I've found most of my WIL's are returning the :

URL No Longer Exists
You have attempted to reach a URL that no longer exists on salesforce.com.
looks like I will be working on cleaning these up over the weekend after all...

I suspect there will be a few supprised administrators on monday morning.

I've been using this as a basis for developing simple scripts to locate duplicates , verify key fields are filled in properly ( I would love a lookup field type ! ) and integerate with our production system for auditing data.

It's not well documented or packaged for CPAN type install (yet) but you may get some ideas.

I just drop this in ...perl/site/lib/Sfdc.pm to get started

you may also need to install Date::Calc from CPAN to get conversions to and from sforce date formats

enjoy

Here is the primary routine to access the sforce api from perl, assumes you have the Sfdc::Serializer, I will send the full package to adam to attach.  Note the code to retry upon rate limit.

this is called to login, query, update ...

my $login = call('sfdc.login', username => $n, password => $p);

etc...

####################

sub call { my $method = shift;
 my %args = (client => $client,version => type(string => $sfdcversion));  
 my ($name,$value);
 while ($name = shift, $value=shift ) { %args = (%args, $name,$value); }
 
 # make xml string
 my $content = Sfdc::Serializer->method( $method => {%args} );
 my $ua = LWP::UserAgent->new; $ua->agent($client);
 my $req = POST $proxy;  
 
 # store the string into the user agent
 $req->content( $content );  

 # add a cookie header for SF.com to look at the session id
 if ( $session_id ) {  
  $req->push_header('Cookie',"sid=$session_id");
 }
 retry:
 # send request
 my $res = $ua->request($req);       
 $res->is_success or die "method $content failed \n";   
 # check for success
 my $result = XMLRPC::Deserializer->deserialize($res->content);
 # return SOM
 if ($result->fault) {
  # if 1010, we are asked to wait and re-try
  # parse the number mil seconds , wait and retry
  if ( $result->faultcode == 1010 ) {
   print "rate limit encountered \n";
   print $result->faultcode, " ",
    $result->faultstring, "\n";
   # pull off the number of ms to wait
   my $retry_time = $result->faultstring;
   $retry_time =~ s/^(\d+)ms delay.*$/$1/;
   print "retry time is $retry_time or ",
    $retry_time/1000," seconds\n";
   sleep (($retry_time/1000)+1) ; # 2 seconds is 2000 ms
   goto retry; # TODO, ouch, this can loop forever...
  }
  print $result->faultcode, " fault ",
   $result->faultstring, "\n";
   
 }
 if ( wantarray ) {
  if ( defined $result->result ) { return @{$result->result}; }
  else { return (); }
 }
 return $result;
}

The guts of my sforce perl class is the serializer , it's sublcassed from XMLRPC which does most of the work, however the array,value,dateTime and hash need to be formed slightly different to pass to sforce.

here is the serializer package

#####################################
package  Sfdc::Serializer;
@Sfdc::Serializer::ISA = qw(XMLRPC::Serializer) ;
sub new {
  my $self = shift;

  unless (ref $self) {
    my $class = ref($self) || $self;
    $self = $class->SUPER::new(
      typelookup => {
        base64 => [10, sub {$_[0] =~ /[^\x09\x0a\x0d\x20-\x7f]/}, 'as_base64'],
 int    => [20, sub {$_[0] =~ /^[+-]?\d+$/}, 'as_int'],
        double => [30, sub {$_[0] =~ /^(-?(?:\d+(?:\.\d*)?|\.\d+|NaN|INF)|([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?)$/}, 'as_double'],
        dateTime => [35, sub {$_[0] =~ /^\d{8}T\d\d:\d\d:\d\d$/}, 'as_dateTime1'],
 string => [40, sub {1}, 'as_value'],
      },
      attr => {},
      namespaces => {},
      @_,
    );
  }
  return $self;
}
sub as_value  {  
    my $self = shift;
    my($value, $name, $type, $attr) = @_;
    return ['value', {}, $value];  
}
sub encode_array {
  my($self, $array) = @_;
  return ['array', {},
     [map {$self->encode_object($_)} @$array]
  ];
}
sub as_dateTime1  {  my $self = shift;
    my($value, $name, $type, $attr) = @_;
    return ['dateTime.iso8601', {}, $value];
}

sub encode_hash {
  my($self, $hash) = @_;
  return ['struct', {}, [
    map {
      ['member', {}, [['name', {}, $_], $self->encode_object($hash->{$_})]]
    } keys %$hash
  ]];
}

1;

Has anyone else built a Office XP SmartTags DLL, I'd like to generate a few more ideas / features for my implementation.

My dll is written in visual basic.

I've developed a perl module which subclasses XMLRPC::Lite   ie:

package Sfdc;
use LWP::UserAgent;
use XMLRPC::Lite; 
use HTTP::Request::Common qw(POST);
import SOAP::Data 'type'

If anyone is curious, let me know I'll try to post something.

I use simple perl scripts built on this class to handle my data integrity issues and locate and simplify the merge of duplicates

this is ActiveState Perl, running on windows under a cygwin shell, but should work on unix also.

 

I had to write this today, may be usefull to others
 
I used this to fetch the body of large text fields which contain data greater than 4096 bytes.

Code:
Sforce.Dynabean.prototype.getLargeText = function(propName) { 
 // like get(), but will unpack document body elements which are greater than 4096...
 var body=''; 
 try { 
  var tmp = this.getItem(propName).value; // still could return a null, watch for that when calling
  
  if ( Sforce.Util.dltypeof(tmp) == "domelement" ) {  // see what type of object tmp is...
   for (var i=0; i < tmp.childNodes.length; i++) { 
    body += tmp.childNodes[i].textContent; 
   } 
  } else { // normal string if body is < 4096 bytes 
   body = tmp; 
  } 
 } catch (e) { throw(e); }
  
 return body; 
};

 

Download Version 6.13

requires this Outlook Edition for the new COM object (thanks foghorn..)

guess it should be AppExchange connector...

my favorite new feature is the live clickable hyperlink created in your worksheet when the conenctor reads a HYPRELINK() formula field in your sforce database.

have fun, report issues,
share & enjoy

Message Edited by Ron Hess on 01-21-2006 11:05 PM

fresh doc, pushed yesterday on the appexchange resource page, new publisher info.

http://www.salesforce.com/appexchange/resources_appexchange.jsp

Download the step-by-step guide to publishing apps on the AppExchange
http://www.salesforce.com/us/appexchange/resources/salesforce_appexchange_publish_guide.pdf

Also, please let us know what other doc you feel is missing to help tie together the entire AppExchange vision with complete documentation on how to develop and publish for the platform. We are working on more docs, so I want to make sure these cover the areas that are of concern to this community.

thanks,

not that you would ever need this, however it appears that the AJAX sforceClient does not like 15 charID's in Retrieve, so I ported this late last night from the java version posted elsewhere.

only tested for a short time, but it appears to work.

function normaliseSforceID( id) { // fluff up a 15 char id to return an 18 char id
 if (id == null) return id;
 id = id.replace(/\"/g, ''); // scrub quotes from this id
 if (id.length != 15) {
  //print('well, id is not 15, bye' + id + ' ' + id.length);
  return null;
 }
 var suffix = "";
 for (var i = 0; i < 3; i++) {
  var flags = 0;
  for (var j = 0; j < 5; j++) {
   var c = id.charAt(i * 5 + j);
   if (c >= 'A' && c <= 'Z') {
    flags += 1 << j;
   }
  }
  if (flags <= 25) {
   suffix += "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(flags);
  } else {
   suffix += "012345".charAt(flags-26);
  }
 }
 return id + suffix;
}

 

I've been trying to use the Excel Connector for the last two weeks to manage the data in our organisation, but I'm having a problem where I get the following error in Excel which is preventing me from using this tool:

 

Error Generated by request::An internal server error has occured while processing your request.
Url:https://www.salesforce.com/services/Soap/c/13.0

ExceptionCode : 5103

The first couple of times I tried to use Excel Connector it worked fine. However I then started seeing this error every time I tried to use it - the error appears after I put in my password in Excel Connector and click Login.

 

We are on Salesforce Professional. I have tried uninstalling and reinstalling the toolkit and connector, but it hasn't made a difference. I'm using Excel 2010 32-bit on Windows 7 64-bit.

 

I can log in to Salesforce in my browser on the same computer.

 

I've checked that IE is not in Offline Mode, and verified that Excel can actually connect to the internet (pinged a URL using VBA script).

 

I've tried disabling my antivirus (MSE) and windows firewall.

 

I've tried changing the server url as suggested by this thread (had to modify registry keys to do this as that field was not editable in the connector.

 

None of these resolutions worked.

 

Has anyone experienced and managed to resolve this, or can anyone suggest any other possible resolutions?

Hi, 

 

I would want to get the quantity from the input text of the table. I need it so that I can update the quantity for quote_line_items object.

 

<apex:page standardController="Product2" extensions="ProductListController">
<apex:form >
    <apex:pageBlock title="Products List">
        <apex:pageBlockSection title="List of Available Address" columns="1">
            <apex:pageBlockTable value="{!productsList}" var="prod"> 
                
                <apex:column headerValue="Select"> 
	    	 		<apex:commandLink value="Select" onclick="return confirm('Are you sure?')" action="{!selectId}" >
		          		<apex:param name="prodid" value="{!prod.id}" />
		          	</apex:commandLink>
		        </apex:column> 
                </apex:column>
                <apex:column headerValue="Product Name" >{!prod.Name}</apex:column>
                <apex:column headerValue="Size/Dimensions" >{!prod.Size_Dimensions__c}</apex:column>
                <apex:column headerValue="Total Quantity" >{!prod.Total_Quantity__c}</apex:column>
                <apex:column headerValue="Available Quantity" >{!prod.Available_quantity__c}</apex:column>
                <apex:column headerValue="Quantity Required" >
                    <apex:inputText value="{!quantity}"></apex:inputText>
                </apex:column>              
            </apex:pageBlockTable>
        </apex:pageBlockSection>    
    </apex:pageBlock>   
</apex:form>
</apex:page>

 

public with sharing class ProductListController{
    public Product2 product;
    public List<Product2> productsList = null;
    public id quoteId {get; set;}
    public String productId {get; set;}
    public Integer quantity;
    
    public ProductListController(ApexPages.StandardController controller)
    {
        product = (Product2) controller.getRecord();
        quoteId = ApexPages.currentPage().getParameters().get('quoteId');
    }
    
    public Integer getQuantity()
	{
	  return quantity;
	}
	
	public void setQuantity(Integer newTD)
	{
	   quantity=newTD;
	}
    
    public List<Product2> getProductsList()
    {   
        try{
            String query = 'SELECT ID, NAME, Available_quantity__c, Total_Quantity__c,  Size_Dimensions__c FROM Product2 ';
            productsList = Database.query(query);
        }
        catch(Exception e)
        {
            System.debug(e.getMessage());
        }   
        return productsList;
    }
    
    public PageReference selectId(){
    	productId = System.currentPageReference().getParameters().get('prodid');
    	Quote__c quote = [Select id,Name from Quote__c where id=:quoteId];
    	if(productId.length()>15){
			productId = (productId).substring(0,15);	
		}
    	Quote_Line_Item__c quoteLineItem = new Quote_Line_Item__c();    	
    	Product2 product = [Select id, Name from product2 where id=:productId];
    	quoteLineItem.Name = 'PROD - '+quote.Name+'  '+product.Name;
    	quoteLineItem.Product__c =  product.Id;
    	System.debug('*********Quantity*********' + quantity);
    	quoteLineItem.Quantity__c = quantity; 
    	quoteLineItem.Quote__c = quoteId;  	
    	insert quoteLineItem;
    	
    	return new PageReference('/' + quoteId);
    	 
    }
    
}

 But the quantity value does not pass into the variable. Can you please help me out.

 

 

My entire APEX trigger is wrapped in a try/catch block, catching the generic Exception object, but I'm still hitting a fatal System.LimitException.

 

What's the point of try/catch if it doesn't actually catch an exception? 

How can I make sure my try / catch block prevents a fatal error?

 

Here's the relevant snippet:

 

for (Contact c : [SELECT Email, Id FROM Contact WHERE AccountId = :account_id LIMIT 10]) {
  if(c.Email != null){
    try {
      Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
      message.setTemplateID(email_template.Id);
      message.setWhatId(detail.Id);
      message.setTargetObjectId(c.Id);
      Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
    }    

    catch (System.LimitException e) {

      // I don't really care if the email fails.

      // I just don't want it to break my data entry process.

     }

     catch (Exception e) {

      // I don't really care if the email fails.

      // I just don't want it to break my data entry process.
    }
  }

}

 

updated: even explicitly catching system.limitexception fails.

I have a before trigger that calls this class which auto assigns the region and the ownerid to the account based on the recordtype, state and zip of the region object. the region object holds all the assignments. It works great but when I execute a batch load through data laoder I hit too many script statements 200001 error. any way i can fix?

 

 

public with sharing class AccountUtilities
{
public static void acctAssign(List<Account> aList)
{
List<region__c> rList = [select id, zip_start__c, zip_end__c, state__c,sales_user__c, business_unit__c, recordTypeId from region__c];
Map<Id,RecordType> rtMap = new Map<Id,RecordType>([Select id,Name from RecordType where sObjectType IN ('Account','region__c')]);
for(Account a:aList)
{
try
{
for(integer i= 0; i< rList.size(); i++)
{
String billingPostalCode= String.valueOf(a.BillingPostalCode);
if(a.billingstate== rList.get(i).state__c && a.Protected__c != true && rtMap.get(a.recordtypeid).Name == rtMap.get(rList.get(i).recordtypeid).Name && a.business_unit__c == tList.get(i).business_unit__c)
{
if(a.billingPostalCode >= rList.get(i).zip_start__c && a.billingPostalCode<=rList.get(i).zip_end__c || rList.get(i).zip_start__c ==null && rList.get(i).zip_end__c ==null )
{
a.region__c = rList.get(i).id;
a.OwnerId = rList.get(i).sales_user__c;
}
}
}
}
catch (System.Exception e)
{
// process exception
}

}
}



Are there any examples to creating a time-based trigger? I am needing to remove the value in a lookup field after 30 days field was populated.

Hi All

 

my dobut is

 

my trigger code coverage is 80% and my organization code coverage is 60 %..so can it possible to move this trigger in to production environmnet??

 

how  to calculates the codecoverages it takes as individual apexclass or overall organization code coverages

 

thanks in advance

thanks

neeru

  • November 29, 2012
  • Like
  • 0

We have a class that's listed like this in our org:

 

Version: 24.0

Status: Active

Size without Comments: 2076

Coverage: 14% (32/216)

 

This class is, in total, 38 lines, covered like this:

 

5 "white" lines, not counted.

10 "red" lines, not covered.

23 "blue" lines, covered.

 

How is it that the coverage could be this screwed up?

I've reported a bug to the partner portal, case 08197046

 

I'd like to understand if anyone else has reported this issue or worked around it.

 

we have a simple rule to identify duplicates on the Name field.

 

AND(OR(ISNEW(),ISCHANGED(Name)), VLOOKUP( $ObjectType.Supplier__c.Fields.Name , $ObjectType.Supplier__c.Fields.Name ,Name)<>NULL)

 

 

and a simple testmethod 

 

System.assertEquals( 0, [ select id from Supplier__c ].size() );
Supplier__c supplierObj = new Supplier__c();
supplierObj.Name= 'Test Supplier';    
insert supplierObj;

 

My API setting is 25.0, and the assert passes, since no data is visible to my test method.

 

now, i run my test method and it fails on the insert statement ( yes the database has a Test Supplier )

 

 

18:05:03.386 (5386958000)|SOQL_EXECUTE_BEGIN|[64]|Aggregations:0|select id from Supplier__c
18:05:03.388 (5388301000)|SOQL_EXECUTE_END|[64]|Rows:0
18:05:03.388 (5388663000)|DML_BEGIN|[67]|Op:Insert|Type:Supplier__c|Rows:1
18:05:03.400 (5400613000)|CODE_UNIT_STARTED|[EXTERNAL]|Validation:Supplier:new
18:05:03.400 (5400628000)|VALIDATION_RULE|03dE00000000EbW|Unique_Name
18:05:03.400 (5400914000)|VALIDATION_FORMULA|AND(OR(ISNEW(),ISCHANGED(Name)), VLOOKUP( $ObjectType.Supplier__c.Fields.Name  ,  $ObjectType.Supplier__c.Fields.Name ,Name)<>NULL)|Name=Test Supplier , $ObjectType.Supplier__c.Fields.Name=Supplier__c.Name
18:05:03.400 (5400929000)|VALIDATION_FAIL
18:05:03.404 (5404672000)|CODE_UNIT_FINISHED|Validation:Supplier:new
18:05:03.405 (5405933000)|DML_END|[67]
18:05:03.408 (5408566000)|VF_PAGE_MESSAGE|This Supplier already exists
18:05:03.408 (5408686000)|EXCEPTION_THROWN|[67]|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This Supplier already exists: [Name]
18:05:03.409 (5409633000)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This Supplier already exists: [Name]

 

I can conclude that VLOOKUP() can see data even if called from a test method that cannot see data.

 

This makes validation rules look like a serious hazard when writing test methods, how could i know what data is already in the org ? How can i protect my test methods from data that exists ?

 

I turned off this validation rule, and sure enough the test method behaves as expected.

 

thanks for any ideas.

 

Hi,
Since the latest Winter release we have had trouble with one of our Visualforce pages that uses a custom Apex controller. The page displays a list of leads with the Most Recently Responded to Campaign Name and the Response Date.  See image below of what it used to look like (But with a Date in the Response Date column):

This image is not available because: You don’t have the privileges to see it, or it has been removed from the system

We are getting the following error on the page: 
     "Invalid CurrencyIsoCode for SObject CampaignMember"

If we hide the Campign Response Date column from the page, or use a different field then the page renders ok. It seems to only error when we are picking a field from the CampaignMember object.

Is someone able to help us?? I haven;t got a response from Salesforce yet and am rather perplexed about this error as we dont really use the Currency fields in our org, everything is in USD.
I have included the snippets of VS Page code and Apex Controller code that seem relevant.



------------- Start VisualForce Snippet -----------------
    <apex:pageBlockTable value="{!leads}" var="l" id="table">
        <apex:column >
            <apex:outputLink style="font-weight:bold" value="/{!l.Id}/e?retURL={!l.Id}"> Edit </apex:outputLink>                   
        </apex:column>
       
        <apex:column >
            <apex:facet name="header">Owner</apex:facet>
            <apex:outputLink value="/{!l.owner.Id}"> <apex:outputText value="{!l.owner.name}"/> </apex:outputLink>                   
        </apex:column>
        <apex:column >
            <apex:facet name="header">Rating</apex:facet>
            <apex:outputText value="{!l.rating}"/>           
        </apex:column>
        <apex:column >
            <apex:facet name="header">Status</apex:facet>
            <apex:outputText value="{!l.status}"/>                   
        </apex:column>
    
        <apex:column >       
            <apex:facet name="header">
            <!--     <apex:commandLink value="{!$ObjectType.Lead.Fields.Name.Label}" action="{!doSort}" rerender="theForm">
                    <apex:param name="sortField" value="Name" assignTo="{!sortField}"/>                           
                </apex:commandLink>  -->
                Name
            </apex:facet>
       
            <apex:outputLink value="/{!l.Id}"> <apex:outputText value="{!l.name}"/> </apex:outputLink>                   
        </apex:column>
                
        <apex:column width="200px" >
            <apex:facet name="header">Title</apex:facet>
            <apex:outputText value="{!l.title}"/>                  
        </apex:column>
        <apex:column width="200px" >
            <apex:facet name="header">Company</apex:facet>
            <apex:outputText value="{!l.company}"/>                   
        </apex:column>
        
     
        <apex:column >
            <apex:facet name="header">Campaign Most Recently Responded To</apex:facet>
            <apex:repeat value="{!l.CampaignMembers}" var="cm">
                <apex:outputField value="{!cm.Campaign.Name}"/>
            </apex:repeat>  
        </apex:column>
      
       <apex:column >
            <apex:facet name="header">Response Date</apex:facet>
            <apex:repeat value="{!l.CampaignMembers}" var="cm">
                <apex:outputField value="{!cm.FirstRespondedDate}"/>
            </apex:repeat>   
        </apex:column>

    </apex:pageBlockTable>

------------- End VisualForce Snippet -----------------



------------- Start Apex Controller Snippet -----------------
    public ApexPages.StandardSetController ssc {
        get {
            if(ssc == null) {
                if (userQuery == 'All') {
                    ssc = new ApexPages.StandardSetController(Database.getQueryLocator(
                        [SELECT id, name, status, owner.id, owner.name, rating, title, company,
                            (SELECT Campaign.name,Campaign.status, FirstRespondedDate,HasResponded FROM CampaignMembers
                               WHERE NOT FirstRespondedDate = null
                               ORDER BY FirstRespondedDate DESC
                               LIMIT 1)
                        FROM Lead
                        WHERE Owner.UserRole.Name like '%sales%' AND (Rating = 'A' OR Rating = 'B') AND IsConverted = false AND ( NOT ( Status = 'Nurture' OR Status = 'Unqualified' ) )
                        ORDER BY LastModifiedDate DESC]));
                }
                else { 
               
                    if (userQuery == '') {userQuery = UserInfo.getUserId();}
                     
                    ssc = new ApexPages.StandardSetController(Database.getQueryLocator(
                        [SELECT id, name, status, owner.id, owner.name, rating, title, company,
                            (SELECT Campaign.name,Campaign.status, FirstRespondedDate,HasResponded FROM CampaignMembers
                               WHERE NOT FirstRespondedDate = null
                               ORDER BY FirstRespondedDate DESC
                               LIMIT 1)
                        FROM Lead
                        WHERE owner.id =:userQuery AND (Rating = 'A' OR Rating = 'B') AND IsConverted = false AND ( NOT ( Status = 'Nurture' OR Status = 'Unqualified' ) )
                        ORDER BY LastModifiedDate DESC]));                   
                    }                                                     
                ssc.setPageSize(20);
            }
            return ssc;
        }
        set;
    }
   
    public List<Lead> getLeads() {
        leads = (List<Lead>) ssc.getRecords();
        return leads;
    }

------------- End Apex Controller Snippet -----------------

Is there a way to use the Google Doc authentication that a Salesforce org already has to store/retrieve documents from an organization's exisitng Google Doc account?

 

If not, the example of authenication shows a visualforce page to capture and generate the authenication token.   Is it possible to do the authenication instead in an apex class where the account name and password would come from the "Configuration" object instead.  If so, can someone post an example of how this is done.

Hi ,

 

I am fetching data from salesforce objects in apex class and I want to display it with the help of JSON in VF Page. Is there any plugin or transformer class which can transform them into JSON array for display

 

Help will be appreciable

 

Regards

 

Praz

  • August 26, 2010
  • Like
  • 0

I'm trying to build an inventory catalog from some data stored in a custom object in Salesforce. One of the fields on the custom object stores the Id of a document that is an externally available image.

 

I'm trying to build this catalog in a Sites page and make this image appear. I'm currently doing this:

 

 

<apex:image url="/servlet/servlet.FileDownload?file={!Inventory__c.Image_URL__c}" />

 This works fine when I'm logged into Salesforce and viewing the Visualforce page directly.

 

Once I navigate to the sites page and try to view it, nothing comes up. I'm confirmed that the image is externally available, and I've set the Sites profile to "Read" for Document objects.

 

Does anyone know how you actually take advantage of externally available images and make them VISIBLE externally?

 

can anybody suggest me where can i download google visualizations App from.I tried in App Exchange but i didnt find it.

Seems like the guide is trying to be clear about this, but not for me. Most of the examples in other questions I've found about this topic are WAYYYY too long to read through, so I'll try to make mine simple:

 

Here's the first part of my controller extension:

 

 

public class Controller_OppItemEdit_OverRide
{

OpportunityLineItem OLI public Controller_OppItemEdit_OverRide (ApexPages.StandardController stdController) { this.OLI = (OpportunityLineItem)stdController.getRecord(); }

Now according to the APEX Guide:

"Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other fields, including fields from any related objects, must be queried using a SOQL expression."

 

That would seem to mean that if I reerence a field that is on the Controller Object in the VF Page, I don't have to query for it using SOQL. But from my experence, I'm not sure I believe this. To continue:

 

 

public OpportunityLineItem getOLI()
    {
    	return OLI;
    }
    
    public void setOLI(OpportunityLineItem LI)
    {
    	this.OLI = LI;
    }

 

 

Adding these getter and setter methods or the standard Controller seems redundant to me, but someone else did this in an example and said it worked for them in their instance, so I include it here. Maybe that;s the problem, maybe not - I don't know.

 

 

public PageReference Save()
    {
system.debug('MRC is '+OLI.MRC__c+' and NRC is '+OLI.NRC__c);
    	
OLI.TotalPrice = OLI.MRC__c + OLI.NRC__c;
    	
update OLI;

return null;

}

 

 

That's it for the Controller code in its simplest form. All of the fields are referenced in the VF Page as inputFields. So, I would assume that if I change one of those inputFields, and click a button that calls an Update to the record, that the record would be updated with the new values.

This assumption is clearly wrong as the record does not get updated.

Here is the essence of the Page:

 

 

<apex:page standardController="OpportunityLineItem" extensions="Controller_OppItemEdit_OverRide" >
<apex:form >
<apex:outputPanel id="thePanel">
<apex:pageBlock id="theBlock" >
<apex:pageBlockButtons >

<apex:CommandButton action="{!save}" value="Save Changes" rerender="thePanel"/>

 </apex:pageBlockButtons>
<apex:PanelGrid columns="2"> New MRC:&nbsp; <apex:inputField value="{!OpportunityLineItem.MRC__c}"/> New NRC:&nbsp; <apex:inputField value="{!OpportunityLineItem.NRC__c}"/> </apex:PanelGrid> </apex:pageBlock> </apex:outputPanel> </apex:form> </apex:page>

  So that's pretty much it. I add a value to the inputField, and click the Save button. The values in the page remain, however the debug statement indicates the values being set are still null, even though the debug log says the update went through as expected. Nows the previously saved values for the record are appearing in the page, but the new values do not appear to be getting to the database.

 

To resolve this I added a query for the Line Item record in the Constructor method:

 

 

OpportunityLineItem OLI;

public Controller_OppItemEdit_OverRide (ApexPages.StandardController stdController) 
    {
        this.OLI = (OpportunityLineItem)stdController.getRecord();
         OLI=[SELECT id, OpportunityID, MRC__c, NRC__c, ...
    		 FROM OpportunityLineItem
    		 WHERE id = :OLI.id];
    }

// And then I added individual properties for each of the fields:

    public decimal MRC {get; set;}
    public decimal NRC {get; set;}

 

 

Now, I can change the inputFields into InputText boxes in the page. And because there is now a property to receive and provide these values, I can now set the OLI record values from the properties:

 

 

public PageReference Save()
    {
        if (MRC != null)
    		OLI.MRC__c = MRC;
    	if (NRC != null)
    		OLI.NRC__c = NRC;
    update OLI;
    }

 

 

This does update the values in the record, which is great - except that I'm having to write customized logic for what should be already available by virtue of using a standard controller and inputFields. I would go ahead and use this except that one of the fields I need is a picklist, and setting up the SelectOptions for a field that is already available on the object means the list of values has to be updated whenevfer someone changes them in SFDC. I realize I could write some long getDescribe method to extrsact the current set of field values, but that seems kind of stupid in this case.

When I add the inputField for this field, all of the current options are already availavble for selection - except the selection doesn't save.

 

I can only guess at this point that I'm declaring the extension incorrectly, or overwriting something but the Dev guide is pretty clear:

 

 

public class myControllerExtension {

    private final Account acct;
    
    public myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }

By the way, above this example is the following statement:

   ApexPages.StandardController sc = new ApexPages.StandardController(sObject);

The example below it doesn't use this statement. Obviously its a way to create and instantiate a new Standard Controller variable, but there is no indication as to why I would want to use this statement, or if I would need to use it, or if the example below is the equivalent of this statement when used as part of an extension.

 

So, in order to actually get the values I input into the inputFields in a page using a StandardController extension, what am I missing??

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

sdf

I am trying to create a trigger that sends an Email Alert (or just an email though Apex code) to the original Idea poster whenever a comment is left for their idea. In looking through the Apex documentation, I noticed it says you can only define triggers for top-level standard objects, but not for standard child objects. When I try to do something like this:

 

 

trigger commentEmail on IdeaComment (after insert) {
// send email code here
}

 

I get "Error: Compile Error: SObject type does not allow triggers: IdeaComment at line 1 column 25". Can anyone point in the right direction to get around this?