• Whyser
  • NEWBIE
  • 310 Points
  • Member since 2007

  • Chatter
    Feed
  • 11
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 25
    Questions
  • 153
    Replies

I'm writing a trigger in which I need to test if a record already exists in sf before I can proceed.

 

currently I am using this method:

 

if([select count() from account where id = :trigger.new[i].ParentId] > 0) {}

 

however this is not very governer limit friendly.  In the past I've tried using the isNull method wrapped around a try{ } catch  but that returned a null pointer exception (or whatever the equiv. is called in sf, I forget at the moment.

 

i have tried to use

if([select count() from account where id in :accIds] > 0){}

 

but as I understand, this statement works like this:  it will return as many  account records as there are  matching acound id's in thet set.  I just want to know if ONE particular account is in the set.

 

I hope that was clear.  If you  need any further explanation from me just let me know and I'll do my best to provide!

 

  • March 11, 2009
  • Like
  • 0

Hi

 

My requirement is as follows

 

I have a master detail relationship between 2 objects. For 1 master record there can be multiple detail record. I need to find the highest detail record for a particular master record. If there are 3/4 detail for 1 master I need to find out the highest detail record.

 

The detail record has a field a auto number field which is listed under the standard fields.  How would I extract the highest auto number that was inserted (in a detail record) for a master record

 

Also the apex explorer does not list the auto number field . how would I view it?

 

Thanks much for all your time 

 

 

  • March 11, 2009
  • Like
  • 0

All,

 

I have had a request from a user, and I am struggling with how to accomodate it. 

 

My user works with Leads, and is frustrated that the address information input for the Leads is not transferred to the new Contact created when the Lead is converted.  I have looked into the standard functionality, and have found that this information is instead transferred to the Account which is created.  I can create a new set of custom fields for both the Lead and Contact records to transfer this information, but I don't feel this adequately meets my users' needs.

 

Instead, I am trying to determine if I can update the Contact information as it is being created by the 'Convert Lead' process, using an APEX trigger.  Unfortunately, I can find little information about how triggers relate to the 'Convert Lead' process.  I have looked at the discussion boards, blogs, and developer's guide, but cannot seem to find the information I need. 

 

I am aware that I may need to request that the 'Enforce Validation and Triggers from Lead Convert' functionality be enabled in my org, and that this will allow me to use the 'before create' trigger setting to create a trigger on the Contact object which will allow me to update the fields in the Contact record before it is saved.  However, how do I access the original Lead in the trigger to allow me to grab the address information stored in the Lead?

 

Any help would be greatly appreciated.

Message Edited by m_roark on 03-10-2009 03:03 PM

I downloaded the Quote Sale Line app from app excahnge written by salesforce.com. I have two scenarios:

  • where if the user is not the admin and sales_discount is more then 30% then they can not edit the sales discount.
  • Now if the reseller is on the reseller table and the discount follows through but if it is more then 30% that above rule applies and does not insert the record from the code below and it comes up with an error.

Here is the code I modified but do not know how to place in the correct parameters for a validation or a new trigger rule:

 

// copy lines from the oppportunity to this quote public void copyLineItemsFromOpptyToQuote() { // delete any existing quote lines OpportunityLineItem[] olist; olist = [Select Id, OpportunityId, SortOrder, PricebookEntryId, Quantity, TotalPrice, UnitPrice, ListPrice, ServiceDate, Description, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, IsDeleted , PricebookEntry.Name, PricebookEntry.Product2id From OpportunityLineItem where OpportunityId = :quote.Opportunity__c ]; // create new quote lines SFDC_520_QuoteLine__c[] qlines = new list<SFDC_520_QuoteLine__c>(); for ( OpportunityLineItem oitem : olist) { Reseller__c[] r =[Select Name, License__c from Reseller__c where Name=:quote.Partner_Direct__c]; if(r.isEmpty()){ SFDC_520_QuoteLine__c ql = new SFDC_520_QuoteLine__c( Quote__c = quote.id, Sales_Discount__c = 0.0, Qty_Ordered__c = oitem.Quantity, Unit_Price__c = oitem.UnitPrice, Description__c = oitem.Description, ServiceDate__c = oitem.ServiceDate, Product2__c = oitem.PricebookEntry.Product2id ); qlines.add(ql); } if(!r.isEmpty()){ SFDC_520_QuoteLine__c ql = new SFDC_520_QuoteLine__c( Quote__c = quote.id, Sales_Discount__c =r[0].License__c, Qty_Ordered__c = oitem.Quantity, Unit_Price__c = oitem.UnitPrice, Description__c = oitem.Description, ServiceDate__c = oitem.ServiceDate, Product2__c = oitem.PricebookEntry.Product2id ); qlines.add(ql); } } delete quote.Quote_Lines__r; if ( qlines.size() > 0 ) { insert qlines; } }

 

 Any help would be truly appreciated....

Thanks

 

 

 

The page will not be loaded from a link/button on the User page, so I cant add a User Id parameter to the link/button, i.e.

 


/apex/myPage?id={!User.id} where t.User__r.id = :ApexPages.currentPage().getParameters().get('Id')

 

I would like to be able to place the link anywhere but have the page only display the record for the current user viewing the page.

 

 

My Class:

 

 

public class tobExtension { private final Time_Off_Info__c tob; public tobExtension(ApexPages.StandardController stdController) { this.tob = (Time_Off_Info__c)stdController.getRecord(); } List<Time_Off_Info__c> tobRecords; public List<Time_Off_Info__c> getTobRecords() { if( tobrecords == null) tobrecords = [Select t.User__c, t.Total_Time_Off_Available_Hours__c, t.Total_Pending_PTO_Requests__c, t.Total_PTO_Hours_Accrued_2__c, t.Total_PTO_Available__c, t.Total_PTO_Accrued__c, t.Pending_PTO_Balance_Hours__c, t.Payroll_System__c, t.PTO_Balance_Hours__c, t.PTO_Balance_Days__c, t.PTO_Available_current_as_of__c, t.Name, t.Id, t.Employee_Number__c From Time_Off_Info__c t where t.User__r.id = '$User.id']; return tobrecords; } }

 

My Page:

 

 

<apex:page standardcontroller="Time_Off_Info__c" extensions="tobExtension"> <apex:sectionHeader title="My Time Off Balance"/> <apex:pageBlock title="Current User: {!$User.Username}"> <apex:pageBlockTable value="{!tobrecords}" var="tob"> <apex:column value="{!tob.Employee_Number__c}" /> <apex:column value="{!tob.User__c}"/> <apex:column value="{!tob.Total_PTO_Accrued__c}"/> <apex:column value="{!tob.PTO_Available_current_as_of__c}"/> <apex:column value="{!tob.Total_Pending_PTO_Requests__c}"/> <apex:column value="{!tob.Total_PTO_Available__c}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>

 

 Thank you.

 

 

 

Hi all,

 

I call an external web service and I would like to write the answer into an account's field.

By now I'm able to do the callout and I get the response and to edit account's field I use a query. But I'm forced to use a particular name of the account.

The cose is the following:

 

String r = np.GetPrimeNumbers(8);

               String varName = 'Test triggerB';         

               Account[] la = [select Name, Phone, Fax, Account_Credit_Check__c from Account where name = :varName];

 

I'm forced to use Test triggerB as account name. How can I call the field account name, instead of its value?

Hi all I have the following code:

How do I move it to next record when the SFD_WEEK_No__c changes...

Basically I have two recordsets of data performing the same thing twice.. but I needed to get totals by week..

This kind of works but it does not sum up the records if the week no is the same.. it just keeps it the same as the first record...

 

 

 

 

for(SFDCFEDFLE__c o:[Select SFD_WEEK_NO__c,SFD_MOFR_NET_AVG__c,True_Draw_MOFR__c,amount__c from SFDCFEDFLE__c where User__c ='00550000000mLBs']) { if(o.SFD_WEEK_NO__c != a.SFD_WEEK_NO__c) total.SFD_MOFR_NET_AVG__c+= o.SFD_MOFR_NET_AVG__c; tot.amount__c += o.True_Draw_MOFR__c;

 

 

 

Anyone know how to write an apex trigger that will copy the parent account team details to all child account teams everytime a change is made to the parent?

 

 Hi,

 

  Please help me to resolve the query error. :smileysad:

 

 String purgeType = String.valueOf(bs.Purging_Type__c);
            if(bs.Purging_Type__c == 'LAST_N_DAYS') {
                 Integer nDays = Integer.valueOf(bs.Last_n_days__c);
            }
     if (purgeType == 'LAST_N_DAYS') {
                 List<ConnectCompiere_Log__c> lastNDays = new List<ConnectCompiere_Log__c>([SELECT Id FROM ConnectCompiere_Log__c WHERE CreatedDate = LAST_N_DAYS : nDays]);
                 for(ConnectCompiere_Log__c rec:lastNDays) {
                      delete rec;
                 }

 

I am getting Error: Compile Error: expecting a number, found 'nDays' at above marked line.

 

How i can use custom varaiable(like nDays) instaed of using some number in place of nDays. Values for nDay, I will be getting from front end as Integer values.

 

Please help me. 

 

Thnks in advance.

I have a picklist field called "Operational Status" on my Account Object.  When "Operational" is picked from the picklist I want to require that an associated custom object called "Entity Account" is in place before the user can save.

 

The Entity Account object has a master-detail relationship with the Account object. 

 

So if I have account ABC and I want to change its Operational Status to "Operational" I first need to create an Entity Account where account ABC is its master. 

 

I am attempting to write a trigger to make an error pop-up if an account entity associated to the account is not created first. If an entity account is already exising then all is good.

 

I just cant figure out how to check if an Entity Account object is already created for the account or not.  Is there a way to relate two objects like this and how would I go about doing it?

 

Thanks in advance!

  • February 23, 2009
  • Like
  • 0
Hi,

Anyone done this before, any tips?

I'd like to create a list of subordinate roles for a user that is running my s-control. This would be used to populate a selection list with all user's subordinates.

-Aki
  • June 02, 2008
  • Like
  • 0
i'm running into an issue using Visualforce trying to reference a static resource imageon my Salesforce Production instance from my Salesforce Sandbox instance. 

The Static Resource has it's cache control set to Public.

I'm aware that referencing external images require that the Remote site settings are set on my Salesforce Sandbox instance 

Remote Site Name: test
Remote Site URL: https://images.metropuzzle.com

Remote Site Name: Salesforce_Production
Remote Site URL: https://[mydomain].my.salesforce.com/

And with the following code
<apex:image value="https://images.metropuzzle.com/tmp/rgb-HP1361-3D2-1000px-300dpi_medium.jpeg" />

<apex:image value="https://[mydomain].my.salesforce.com/resource/XXXXXXXXX/Logo" />



I get the following results:
User-added image

What am I doing wrong?
I have a scenario in which a department wants to leverage email-to-case functionality to trigger the creation of a custom object.

The plan is simply
Send Email -> Email forward to Email-To-Case Servicing Address -> Email-To-Case creates a Case -> Case triggers a Flow that will create custom object.

During the course of the Flow, after the custom object is created, I wanted the Flow to DELETE the trigger case that was created from Email-to-Case.

However, whenever I add a Delete Record element to the Flow after the Custom Object is created, the Flow runs into an error: ENTITY_DELETED.

How would I go about deleting the triggering Case that instantiated the Flow automatically?
  • October 06, 2022
  • Like
  • 0
Right now I have an Account query that retrieves Case information

(simplified code)
 
global without sharing class TicketPortal
{
    Id AccountId;
    // Assume in this sample code that AccountId has been populated

    a = [SELECT
                   Id, Name,             
                   (SELECT 
                       Id, CaseNumber, Subject, Status, RecordType.Name, CreatedDate, IsClosed, OwnerId, Owner.Name, Owner.Email, Owner.Phone, Contact.Name 
                    FROM Cases
                    WHERE 
                        RecordType.Name in ('Issue Record Type','Premium Plus Record Type')
                        AND ( ContactId != null OR SuppliedEmail != null )
                        AND Origin in ('Phone','Email','Customer Portal')
                        
                    ORDER BY CreatedDate DESC
                   )
     
                 FROM Account
                 WHERE Id = :AccountId ];                           
        }
}

The data queried is used to display case history with an account. When I preview it through Visualforce Pages preview (with the above-code as the controller), I can see all the relevant data.

However, if I try to view this from a Sites page (with guest user), I can get the Account and Case information back, but for data like the Case.Contact.Name, I am unable to retrieve. On my VS page, the Contact Name appears blank, though it does not appear blank when viewing it from previewing my VS page in Salesforce

I checked my Share settings and the Site Guest User has read access to Accounts/Cases/Contacts. I have reviewed the Site Guest User's Public Access Settings -> Object Settings -> Cases -> Field Permissions, and all the Contact fields that I need have Read Access..

Is there anything else that I'm missing?
According to Salesforce Help:

https://help.salesforce.com/articleView?id=workflow_time_dependent.htm&type=5  (http://https://help.salesforce.com/articleView?id=workflow_time_dependent.htm&type=5 )
 
Time-dependent actions are executed at a specific time, such as 10 days before a record’s close date. When that specific time passes, the workflow rule re-evaluates the record to make sure that it still meets the rule criteria. If the record does, the workflow rule executes those actions.

So here is my situation:

I have a custom object, Instance, that stores Customer Identifier information for their subscription to our products. One of the fields is ExpirationDate, which indicates when their subscription with us expires.

A Customer can have multiple Instances, such as Trials, Sandboxes, and Production Instances.

The Instance object can be associated to an Opportunity. What we are trying to accomplish is that an Instance that is of Type "Trial" can have their "Expiration Date" extended if the related Opportunity is still in an open state. This way, we can allow the customer to continue extend their trial with us automatically until the Opportunity goes into a Closed stage.

To accomplish this, we have set up a workflow rule against the Instance Object, with the following rule:
 
AND(

CONTAINS("#Stage1#Stage2#Stage3#Stage4#Stage5#Stage6#Stage7#Stage8#Stage9#", "#"+ TEXT(Opportunity__r.StageName) + "#"),

NOT( ISBLANK( Expiration_Date__c ) )
)

Which basically checks to see if the Instance's related Opportunity Stage is a specific stage, and whether the Instance Expiration Date is not blank.

When those conditions are fulfilled, we have a Time-Based action that will run 4 days prior to the Instance.Expiration_Date__c to update the Expiration Date by a certain number of days.

The workflow rule works as described. However, there is a specific scenario that does not work.

When the Opportunity Stage that is related to the Instance is updated to a value that should fail the workflow rule criteria, the Time Based workflow action is still scheduled to run. This was not a problem to me, because I was thinking (as Salesforce Help has indicated above) that before the actual action is run, that Salesforce will re-evaluate the workflow criteria for the record to ensure that it still fulfills the conditions before running the action.

But what we are seeing is that, even though the workflow criteria is no longer fulfilled, the time-based action still runs.

Is there a reason why this is the case? And is there a better workaround for this?

A follow up to more questions regarding the Guest User.

We have a customer portal that allows customers to manage their licenses via Sites ( an iframe in our product that passes very specific parameters to our Site VisualForce page that allows us to determine the customer we are dealing with ) so that customers can manage their licenses to our product ( adding or renewing ).

When a customer has made a purchase to add/renew, one of the things that happens is that an Opportunity is created from it. This doesn't cause any problems since we can grant permission to Guest Users to create specific objects under the Guest User Profile.

However, in addition to creating an Opportunity, it initiates an Opportunity trigger (BEFORE INSERT) that tries to:

  • Update the End Date (custom field) of an Opportunity, based on the Contract that it is associated to, and recalculate prorated months (custom field) on the Opportunity
  • Update the Contract Months (custom field) of the related Opportunity Line Items.

Understanding that Salesforce is going to soon be enforcing Guest User Record Access to be limited to Create and Read-Only, I am assuming that Salesforce will not allow the Guest User to perform these kinds of updates.

What would be the best practice to allow the Guest User to perform these actions?

The development best practices state:
https://www.learncommunitycloud.com/s/news/guest-user-record-access-development-best-practices-20Y1U000000UkITUA0

which suggests that the update action should be moved into a "without sharing" class.

But considering that this is a trigger, the updates to the fields happen prior to the insertion (is that a problem for the Opportunity since it hasn't been technically inserted yet),

But the trigger does have to query the Opportunity Line Items and perform updates on those, and I suppose that based on best practices, I would now have to move that functionality into a "without sharing" class?

  • March 06, 2020
  • Like
  • 0
I'm late to the game when it comes to securing sties/communities and I'm trying to make the appropriate changes before Salesforce enforces the guest rules.

I'm updating my test methods to simulate having our Site run as the Guest User for the Site ("Portal Site Guest User"), but I set up things like Account creation etc prior to running the tests under the "Portal Site Guest User", but for some reason if I try retrieving records created prior to the System.RunAs... it cannot pull up any records created earlier.

I use the @isTest(SeeAllData=true) so that I can retrieve the Portal Guest User.

Sample code:
 
@IsTest(SeeAllData=true)
static testMethod void PortalTest()
{
    Account a = new Account( Name = 'test', BillingCountry = 'United States', Type = 'Prospect', CurrencyISOCode = 'USD' );

    insert a;

    User PortalGuest = [SELECT Id FROM User WHERE Name = 'Portal Site Guest User'][0];

    System.RunAs( PortalGuest )
    {
        List< Account> accList = [SELECT Id FROM Account WHERE Id = :a.Id];
        System.assert( accList.size() == 1, 'Unable to retrieve created record; accList.size() = ' + accList.size() );
    }
}

 

The System.Assert flags and indicates that the accList.size() = 0.

I have set up Account Sharing Rules for "Portal Site Guest User" to include Account Type = 'Prospect'.

Not sure if I'm missing anything else to be able to access the record from the Guest User. Help?

  • March 05, 2020
  • Like
  • 0
Hi everyone, I'm relatively new to Lightning so please be gentle.

I'm in the process of trying to replace javascript buttons with Lightning buttons, and I've come across and Opportunity button that navigates to an external URL that passes along a variety of parameters:

I wanted to create a Lightning button that navigates to this URL with a confirmation dialog prior to navigation, so I created a Lightning Component to try to achieve this.

At the time of this post, I did not create any apex controllers for this.

Component:
 
<aura:component                 implements="force:lightningQuickActionWithoutHeader,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" 
				access="global" >
	
    <!-- Include Static Resources - if any -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

</aura:component>

Controller:
doInit: function( cmp, event, helper )
{
  // Obtain Parameters for URL
  var OpportunityId = cmp.get("v.recordId");
  var CustomerId = [??]; // Used to be {!Account.CustomerID__c}
  var API_Session_ID = [??]; // Used to be {!API.Session_ID}
  var API_Partner_Server_URL = [??]; // Used to be {!API_Partner_Server_URL_70}
  var User_Company_Id = [??]; // Used to be {!User.Company_Id__c}

  // Navigate to URL
  var urlEvent = $A.get("e.force:navigateToURL");
  urlEvent.setParams({
      "url": 'https://www.[website].com/action?" + [Parameters=Values List above]
   });

  // Confirm prior to navigation
  if ( confirm ("You are about to initiate a transaction on [website], please ensure you examine all necessary fields as per documentation" ))
  {
    urlEvent.fire();
  }
  
}

How do I obtain the parameters in order to achieve this? 

 
  • December 04, 2018
  • Like
  • 0
Hi everyone,

I have a VF page that calls a SimpleDialog that requests for payment after a purchase has been made.
When I test the page on it's own, I get the SimpleDialog message.

However, the VF page that calls the SimpleDialog is to be accessed by the customer through an iFRAME. I found that when the VF page is called through an iFRAME, the SimpleDialog pop up does not show up at all.

Is there a reason why SimpleDialog will not work if the VF page calling it is in an iFRAME?
We are trying to make a customer portal (without logging in) for customers to be able to add User Licenses for our product.
Without logging in, the user profile for the running user is "Guest License User".

We have created a Salesforce Site page that exposes a VisualForce page that allows users to add new licenses.
I am able to create an Opportunity from the externally exposed site, but when I try to add Opportunity Line Items (Opportunity Products), I run into site errors.

Salesforce "Guest License User" permissions only allow read and create permissions for most objects (including Opportunities, which is the object I am interested in).

Two Questions

1) Are the permissions available to the Opportunity Line Item for the "Guest License User"  the same as the permissions for the Opportunity? Or in other words, do the parent object's permissions cascade down to the child (Opportunity -> Opportunity Line Item)

2) Are "Guest License Users" unable to add Opportunity Line Items? I assume that adding an Opportunity Line Item to an Opportunity would "update" the Opportunity with Quantities and Amounts. If "Guest License User"s have no access to edit the Opportunity, are they inherently blocked from creating an Opportunity Line Item associated to an Opportunity?
  • January 05, 2016
  • Like
  • 0
We've only recently discovered this in our testing, but we seem to be getting random 503 errors while doing testing of our .NET code against Salesforce Sandbox.
It always seems to happen during a query call.

When tests are re-run, it seems to throw that error in different places in the test, there seems to be no consistency for when I receive these 503 errors.

Is there anyway to tell whether I am hitting any of the API call limits (25 concurrent calls)?

I tried to do debug monitoring in Salesforce, but unfortunately, they only record 20 logs (the tests we do are a lot more), so we've been unsuccessful in capturing the issue in those logs.

Help anyone?
I'm running into a lot of issues uploading changesets to my other sandboxes or production
I get an error similar to this

The following outbound change set upload failed due to a system error:

Change set: 2014-04-15 (04tS00000001Nls)
Organization: staging (Developer Pro Sandbox) (xxxxxxxxxxxxxxxxxxxxxxxxxxxx)
User: xxxxxx xxxxxxx (xxxxxxxxxxxxxxxxxxxxxxxxxx)
Error Number: 1876945623-22397 (152101301)

I realize that some sandboxes and production instances are on Spring 14 and some are still on Winter 14.
I have checked the areas that I'm trying to deploy to, they are both on Winter 14 and my production instance is still on Winter 14.

The items I am deploying consist of:

Custom fields
Page Layouts
One workflow rule
One field update

I have attempted to upload the change set without the workflow rule and field update, and it still fails.

Does anyone have any insight into this? Do you need more information about my changeset?
  • April 16, 2014
  • Like
  • 0

Is it possible to do any reflective calls on custom classes?

 

I have something like

 

public class CustomTaskObject { public Boolean isSelected {get;set;} public String Id {get;set;} public String Subject {get;set;} public String AccountName {get;set;} public WhatName {get;set;} public WhatStatus {get;set} public Double Timezone {get;set} ... }

 

Basically I populate a list of this CustomTaskObject, and do a very special sort done by Timezone (10 hours ahead of the current user's Timezone, desc), and then by "WhatStatus" priority (which is all done in code as there is no way to do this in SOQL) and throw it into a VisualForce pageBlockTable.

 

Users want to have the functionality to sort by other columns, such as AccountName, or WhatStatus, and I would like to have a way to make it so that I can call

 

object.getField('WhatStatus')

 

to simplify the sorting routine. Otherwise I would have to write a sort procedure to handle each field that is available for sorting.

 

Is reflection possible?

 

I have seen in other threads where people are dealing with sObjects which do have reflection, but I'm guessing that this is not possible with custom classes?

 

Thanks!

  • March 10, 2010
  • Like
  • 0

Hi everyone,

 

Does anyone know how to create slightly more complex headers using VisualForce and dataTables and columns?.

I'm trying to create a table that looks something like this:

Table Caption
Header Grouping 1Header Grouping 2
Header 1-aHeader 1-bHeader 1-cHeader 2-aHeader 2-bHeader 2-c
datadatadatadatadatadata
datadatadatadatadatadata
datadatadatadatadatadata

 

 

Sorry it seems like in the preview that it cannot generate any lines on the table. I tried to increase the spacing so that people can see the general idea that I want.

  • November 11, 2009
  • Like
  • 0

I've been working on a pretty large project in which there were a lot of changes done in Salesforce, such as, new custom objects and fields, validation rules, apex classes and triggers, buttons and custom links, page layours, etc.

Some of these changes were made directly into my Sandbox account, such as new custom objects/fields/validation rules/buttons/custom links/page layouts, etc, while all apex related stuff was done in Eclipse.

When I first started the project, I started with an empty package, so now only my apex code exists in it. I want to know if there is any documentation on how to add other components to the package? I'm using version 3.3.2, so I don't have the GUI that I've read about in some of the other threads to manage my package, and so far I've been manipulating the package.xml to add the other components by creating different types such as CustomField and CustomObject and adding the appropriate members required for our production instance. Can someone point to me where I can get information on how to add other components such as page layouts, validation rules, buttons, custom links, etc?

  • March 03, 2009
  • Like
  • 0

Hi everyone,

 

I have a button on a custom object that runs the following javascript

 

{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")} {!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")} try { document.getElementById("errorDiv_ep").style.display = "none"; document.getElementById("errorDiv_ep").style.textAlign = "center"; var id = sforce.apex.execute( "InvoiceWebService","CreateInvoiceFromProductUsagePlan",{ProductUsagePlanId:"{!ASP_Product_Usage_Plan__c.Id}" } ); window.location = "/" + id; } catch (e) { document.getElementById("errorDiv_ep").style.display = ""; document.getElementById("errorDiv_ep").innerHTML = "<table style='text-Align:left'><tr><td><font color=red>" + e.faultstring.replace(/\n/g,"<br />").replace( /:/g, ":<br />" ) + "</font></td></tr></table>"; }

 

 

Essentially what it is doing is calling an APEX class/method, and checking to see if the call is going to return an error via try/catch.

In my try/catch statement, I take the error returned and display it in the errorDiv_ep element that is standard on each Salesforce page.

 

I know this isn't the most elegant solution for displaying errors on screen, but I'm wondering if there is a better method (without the use of VisualForce). Is it also possible to return confirmation messages rather than error messages as well?

  • February 13, 2009
  • Like
  • 0
Hi, I'm trying to create a webservice but everytime I try to save it, I'm running into this error (error line highlighted in red below):
 
Save error: Method does not exist or incorrect signature: hasMaintenanceOpportunityProducts(LIST: SOBJECT: OpportunityLineItem)
 
I'll paste my class
 
Code:
global class InvoiceWebService 
{

 webService static Id generateQuote( Id OpportunityId )
 {
  List< OpportunityLineItem > oli = new List< OpportunityLineItem >();
  oli = getOpportunityLineItems( OpportunityId );
  
  Opportunity o = [select id, accountid, type, stageName from Opportunity where id = :OpportunityId];
  
  Account a = [select id, type, customer_id__c, maintenance_expiration_date__c, asp_expiration_date__c from Account where id = :o.AccountId];
  
  if ( o.type == 'Standard' )
  {
   if ( hasMaintenanceOpportunityProducts( oli ) == false )
   {
    // Do something  
   }
  }
  
 }
 
 //////////////////////////////////////////////////////////////
 // Private helper functions for the webservice
 //////////////////////////////////////////////////////////////
 
 private List< OpportunityLineItem > getOpportunityLineItems( Id OpportunityId )
 {
// Reduced the SQL command to allow it to be viewable in this thread. return [select FIELDS from OpportunityLineItem o where o.OpportunityId = :OpportunityId ]; } private Boolean hasMaintenanceOpportunityProducts( List< OpportunityLineItem > oliItems ) { Boolean hasMaintenance = false; for ( OpportunityLineItem oliTemp : oliItems ) { if ( oliTemp.PricebookEntry.Product2.Family == 'Maintenance' ) hasMaintenance = true; } return hasMaintenance; } }

 I've highlighted the method that the webservice is unable to call correctly. I've read the Considerations for using the WebService keyword document, (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_web_services_methods_considerations.htm), but I think I don't quite understand it all that well. Can someone tell me what I'm doing wrong? I have a suspicion that if I fix this part, I will get other similar errors to my other functions.


Message Edited by Whyser on 12-09-2008 09:27 AM

Message Edited by Whyser on 12-09-2008 09:28 AM
  • December 09, 2008
  • Like
  • 0
I've created a very very simple webservice using eclipse just to test to see how this works (exists only on the test environment sandbox right now)
 
Code:
global class testWebServiceClass 
{
 webService static Id generateEmptyQuoteTest( Id OpportunityId )
 {
  Quote__c q = new Quote__c ( Opportunity__c = OpportunityId, Date_Sent__c = DateTime.now() );
  insert q;
  return q.id;
  
 }
}

 
Now I've tried invoking this using s-control in the opportunity detail page button
Code:
{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")} 

var id = sforce.apex.execute( "testWebServiceClass","generateEmptyQuoteTest",{OpportunityId:"{!Opportunity.Id}"}); 

window.location.reload();

 and this works perfectly.
 
However, I'm also trying to see if I can invoke the webservice from a C# application (the project consumed the enterprise.wsdl generated from test.salesforce.com and the wsdl for the APEX class above, calling the web reference testWebService)
Code:
    protected void Button1_Click(object sender, EventArgs e)
    {
        testWebService.testWebServiceClassService test = new testWebService.testWebServiceClassService();
        test.SessionHeaderValue = new testWebService.SessionHeader();
        test.SessionHeaderValue.sessionId = sfdc.SessionHeaderValue.sessionId;
        test.Url = sfdc.Url;
        String testResult = test.generateEmptyQuoteTest("006S0000002K6i0");
        Response.Write(testResult);
    }

 where the sfdc object already has a valid login session header.
 
The part I bolded always runs into an exception:
"No operation available for request
{http://soap.sforce.com/schemas/class/testWebServiceClass}generateEmptyQuoteTest"
 
So I was wondering if anyone can tell me where I'm going wrong? I tried reading through the documentation but I guess I either missed something or I don't understand this stuff to well... please help!!

 
  • December 03, 2008
  • Like
  • 0
I have an Apex trigger that writes "Lead Status History" to a custom object I've made called "Lead_Status_History__c". It fires whenever the lead status changes on a lead. The problem I am having is that the trigger is firing twice on a specific Lead Status.
 
I believe the reason why it is firing twice on this specific lead status is because I have a workflow rule set up on the lead. When the lead status is changed to that specific status, it performs a field update on a date field on the lead, and I believe that this field update is causing my trigger to fire again.
 
To rehash the order of execution when it comes to triggers, I'll highlight the steps that are relevant to me:
 

1. The original record loads from the database or initializes for an insert operation
2. The new values load from the incoming request and overwrite the old values in the record buffer. The old values are saved in the old context variable for update triggers.
3. Before triggers run.
...
5. The record is saved to the database, but the record is not committed.
6. After triggers run.
...
8. Workflow rules execute. If field updates are specified, the record updates again, and before and after triggers for the update fire.
...
10. All data manipulation operations are committed to the database.


I believe step 8 is causing my trigger to fire again. Is there anyway to prevent triggers from doing a repeat action if step 8 causes your trigger to fire again?

Here is my apex trigger code:

Code:
trigger LeadStatusHistoryTrigger on Lead (before update) 
{
 // Declare a list of Lead_Status_History__c to be insertedin Salesforce
 List<Lead_Status_History__c> LeadStatusHistoryObjects = new List<Lead_Status_History__c>();
 
 // If the trigger is an update trigger insert all the new status changes
 if ( Trigger.isUpdate )
 {
  for ( Lead l_new: Trigger.new )
  {
    // Check to see if the status of the old and new lead values are the same.
    // If they are different then we create a new entry in the lead_status_history custom object
    if ( l_new.Status != Trigger.oldMap.get( l_new.Id ).Status )
    {
     LeadStatusHistoryObjects.add( new Lead_Status_History__c ( Lead__c = l_new.Id, Lead_Status_New__c = l_new.Status, Lead_Status_Old__c = Trigger.oldMap.get( l_new.Id ).Status ) ); 
    }
  }
  
  // After all the new Lead Status History items have been added, now insert them into Salesforce
  try
  {
   insert LeadStatusHistoryObjects;
  }
  catch (DmlException de)
  {
   for ( integer i = 0; i < de.getNumDml(); i++ )
   {
    System.debug('LeadStatusHistoryTrigger Error Inserting Lead Status History Objects: ' + de.getDmlMessage(i));
   } 
  }
  
 }
}


 

  • November 17, 2008
  • Like
  • 0
Before I begin, I wanted people to know that I've read the APEX documentation regarding Triggers and Merge Statements in the APEX Language Reference Guide located here:
 
 
and after reading it, I'm still a little confused.
 
Right now I have a custom object Lead_Status_History__c object that does some history tracking on the lead status every time the lead status changes. I've done it this way so that we can do reporting on the old and new values since Salesforce's reporting for lead history is limited (cannot set filters against old values and new values). The Lead_Status_History__c object has a lookup relationship to the Lead object (since you cannot make a master-detail relationship with leads, this was the only way).
 
In order to add/delete records to the Lead_Status_History__c object, I've written an APEX trigger that will deal with two events:
  • when the lead is updated (if the lead status has changed, then add a new entry to Lead_Status_History__c, I do not care about recording the initial insert)
  • when the lead is deleted (all associated Lead_Status_History__c objects related to the Lead are to be deleted)

The only other situation I do not know how to handle is when a Lead is being merged.

Code:
 
// trigger on lead (after delete) section
if ( Trigger.isDelete )
{
 // Trigger.old returns an array/list of old values (only available during deleting) 
 // Need to delete all instances of Lead Status History pertaining to this lead
// If this is a merge statement, how do you determine which leads are being merged? List<Lead_Status_History__c> LeadStatusHistoryDelete = [Select Id From Lead_Status_History__c Where Lead__c in :Trigger.oldMap.keySet()]; // Go throught each Lead_Status_History__c for( Lead_Status_History__c LeadStatusHistoryObject: LeadStatusHistoryDelete ) {
// Compare to each Lead Object? for ( Lead LeadObject: Trigger.old ) {
// How to determine which leads are being merged??
// Determine which leads are being merged then update the Lead_Status_History__c object with the Trigger.old.MasterRecordLeadId // Unsure about the condition statement or how to write it???
if ( LeadStatusHistoryObject.Lead__c == LeadObject.Id && LeadObject.Id != LeadObject.MasterRecordId )
{
    // Update the Lead_Status_History__c record to point to the new master Lead





}
else
{
// Delete the lead
} } } }

Does anyone have any APEX experience handling merges with triggers?

Please help!
 

  • November 13, 2008
  • Like
  • 0
Hi everyone,
 
I just had a question about the signature location when you send replies from Salesforce.
 
When you do a reply in Microsoft Outlook, your signature appears ABOVE the reply message.
 
However, in Salesforce, when you do a reply to an email message, your signature appears at the BOTTOM of the reply message.
 
My question is if there is any way to change in Salesforce where the location of your email signature shows in an email when you are replying to a message? Ideally to mimick the way that Outlook places the signature when doing a reply?
 
Thanks
  • August 19, 2008
  • Like
  • 0
i'm running into an issue using Visualforce trying to reference a static resource imageon my Salesforce Production instance from my Salesforce Sandbox instance. 

The Static Resource has it's cache control set to Public.

I'm aware that referencing external images require that the Remote site settings are set on my Salesforce Sandbox instance 

Remote Site Name: test
Remote Site URL: https://images.metropuzzle.com

Remote Site Name: Salesforce_Production
Remote Site URL: https://[mydomain].my.salesforce.com/

And with the following code
<apex:image value="https://images.metropuzzle.com/tmp/rgb-HP1361-3D2-1000px-300dpi_medium.jpeg" />

<apex:image value="https://[mydomain].my.salesforce.com/resource/XXXXXXXXX/Logo" />



I get the following results:
User-added image

What am I doing wrong?
I have a scenario in which a department wants to leverage email-to-case functionality to trigger the creation of a custom object.

The plan is simply
Send Email -> Email forward to Email-To-Case Servicing Address -> Email-To-Case creates a Case -> Case triggers a Flow that will create custom object.

During the course of the Flow, after the custom object is created, I wanted the Flow to DELETE the trigger case that was created from Email-to-Case.

However, whenever I add a Delete Record element to the Flow after the Custom Object is created, the Flow runs into an error: ENTITY_DELETED.

How would I go about deleting the triggering Case that instantiated the Flow automatically?
  • October 06, 2022
  • Like
  • 0
I'm wondering what queue method I should use.
I want to use a trigger to enqueue an external httpRequest:
When a contact is created,  if it has a value in a custom field , add to the queue. 
The process servicing the queue will post that custom field to an external server and get the additional data associated with that customer field value. Then it will update the contact.
I am open to other ways to accomplish this.
I'm late to the game when it comes to securing sties/communities and I'm trying to make the appropriate changes before Salesforce enforces the guest rules.

I'm updating my test methods to simulate having our Site run as the Guest User for the Site ("Portal Site Guest User"), but I set up things like Account creation etc prior to running the tests under the "Portal Site Guest User", but for some reason if I try retrieving records created prior to the System.RunAs... it cannot pull up any records created earlier.

I use the @isTest(SeeAllData=true) so that I can retrieve the Portal Guest User.

Sample code:
 
@IsTest(SeeAllData=true)
static testMethod void PortalTest()
{
    Account a = new Account( Name = 'test', BillingCountry = 'United States', Type = 'Prospect', CurrencyISOCode = 'USD' );

    insert a;

    User PortalGuest = [SELECT Id FROM User WHERE Name = 'Portal Site Guest User'][0];

    System.RunAs( PortalGuest )
    {
        List< Account> accList = [SELECT Id FROM Account WHERE Id = :a.Id];
        System.assert( accList.size() == 1, 'Unable to retrieve created record; accList.size() = ' + accList.size() );
    }
}

 

The System.Assert flags and indicates that the accList.size() = 0.

I have set up Account Sharing Rules for "Portal Site Guest User" to include Account Type = 'Prospect'.

Not sure if I'm missing anything else to be able to access the record from the Guest User. Help?

  • March 05, 2020
  • Like
  • 0
Hi,
Have a quick question on how to pass the list of returned records from method 1 to method 2.


public List<Lead> getCurrentMonthInfo() {
List<Lead> ll=Database.query('SELECT Id,Name,Division_Name__c,Title,counting__c '+ 'FROM Lead');  leadcount = ll.size(); 
return II;
}
Public boolean method 2( //Here I want the record list from Method getCurrentMonthInfo) {
}

Thanks,
 
Hi everyone, I'm relatively new to Lightning so please be gentle.

I'm in the process of trying to replace javascript buttons with Lightning buttons, and I've come across and Opportunity button that navigates to an external URL that passes along a variety of parameters:

I wanted to create a Lightning button that navigates to this URL with a confirmation dialog prior to navigation, so I created a Lightning Component to try to achieve this.

At the time of this post, I did not create any apex controllers for this.

Component:
 
<aura:component                 implements="force:lightningQuickActionWithoutHeader,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" 
				access="global" >
	
    <!-- Include Static Resources - if any -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

</aura:component>

Controller:
doInit: function( cmp, event, helper )
{
  // Obtain Parameters for URL
  var OpportunityId = cmp.get("v.recordId");
  var CustomerId = [??]; // Used to be {!Account.CustomerID__c}
  var API_Session_ID = [??]; // Used to be {!API.Session_ID}
  var API_Partner_Server_URL = [??]; // Used to be {!API_Partner_Server_URL_70}
  var User_Company_Id = [??]; // Used to be {!User.Company_Id__c}

  // Navigate to URL
  var urlEvent = $A.get("e.force:navigateToURL");
  urlEvent.setParams({
      "url": 'https://www.[website].com/action?" + [Parameters=Values List above]
   });

  // Confirm prior to navigation
  if ( confirm ("You are about to initiate a transaction on [website], please ensure you examine all necessary fields as per documentation" ))
  {
    urlEvent.fire();
  }
  
}

How do I obtain the parameters in order to achieve this? 

 
  • December 04, 2018
  • Like
  • 0
We are trying to make a customer portal (without logging in) for customers to be able to add User Licenses for our product.
Without logging in, the user profile for the running user is "Guest License User".

We have created a Salesforce Site page that exposes a VisualForce page that allows users to add new licenses.
I am able to create an Opportunity from the externally exposed site, but when I try to add Opportunity Line Items (Opportunity Products), I run into site errors.

Salesforce "Guest License User" permissions only allow read and create permissions for most objects (including Opportunities, which is the object I am interested in).

Two Questions

1) Are the permissions available to the Opportunity Line Item for the "Guest License User"  the same as the permissions for the Opportunity? Or in other words, do the parent object's permissions cascade down to the child (Opportunity -> Opportunity Line Item)

2) Are "Guest License Users" unable to add Opportunity Line Items? I assume that adding an Opportunity Line Item to an Opportunity would "update" the Opportunity with Quantities and Amounts. If "Guest License User"s have no access to edit the Opportunity, are they inherently blocked from creating an Opportunity Line Item associated to an Opportunity?
  • January 05, 2016
  • Like
  • 0
Hi,
I need to query the Contract lookup field from Opportunity to check if contract exists. But I can't able to see the contract field to query.

Any help
We've only recently discovered this in our testing, but we seem to be getting random 503 errors while doing testing of our .NET code against Salesforce Sandbox.
It always seems to happen during a query call.

When tests are re-run, it seems to throw that error in different places in the test, there seems to be no consistency for when I receive these 503 errors.

Is there anyway to tell whether I am hitting any of the API call limits (25 concurrent calls)?

I tried to do debug monitoring in Salesforce, but unfortunately, they only record 20 logs (the tests we do are a lot more), so we've been unsuccessful in capturing the issue in those logs.

Help anyone?

This may not be the appropriate place to ask this question but I don't know if there is a discussion board about the force.com IDE. The problem I'm having is that the force.com IDE I just downloaded and installed is missing the Run Tests option. The docs I find about running tests all say to right click on a test class and then go to Force.com > Run Tests. Unfortunately the Run Tests option is missing.

 

Does have any suggestions for fixing this problem?

 

Thank you

Hi all,

Major problem.  We have overridden the opportunity new, view and edit controls and visualforced all opportunity view and edit pages.  In the visualforce I have added the [change] link next to the Record Type on the view page.

 

When I click the change link next to the record type and choose a type from the drop down then click continue, it takes me back to the view page (which I would expect) but the record type has not changed:

 


 

Also on another page I'm just using the detail tag (thereby not writing the [change] link manually) and it still doesnt work.  Seems to me the problem is caused because the Edit  function is overwritten with a visualforce page.  The record type change page is managed by a jsp page but it would seem the owner isnt actually changed here and somehow it is passed somewhere else once the Continue button is clicked but because we have overridden view and edit, whatever process that would normally handle the record type change is now no longer being called.

 

Seems strange that salesforce would give me the option to override these pages when it clearly leads to a problem of this kind, can anyone offer a suggsetion?

 

Thanks

Steven

Hi everyone,

 

Does anyone know how to create slightly more complex headers using VisualForce and dataTables and columns?.

I'm trying to create a table that looks something like this:

Table Caption
Header Grouping 1Header Grouping 2
Header 1-aHeader 1-bHeader 1-cHeader 2-aHeader 2-bHeader 2-c
datadatadatadatadatadata
datadatadatadatadatadata
datadatadatadatadatadata

 

 

Sorry it seems like in the preview that it cannot generate any lines on the table. I tried to increase the spacing so that people can see the general idea that I want.

  • November 11, 2009
  • Like
  • 0

Hello All,

 

I'm receiving a compile error -

 

(Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST:SOBJECT:Lead at line 21 column 29)

 

for the following trigger code which I found in the salesforce wiki.  I'm unsure what is wrong with the "Initial term", can anyone help with this?

 

 

 

/* * Simple round robbin lead assignment, * trigger assumes the following custom fields on the User object * User. * Receiving_Leads__c -- are they open for new leads at this time * Open_Leads_Owned__c -- how many leads do they have right now * * if no matching new owner is found the default for the org is the new owner */ trigger triggerLeadRoundRobin on Lead ( before insert , after insert, after update , after delete) { if (Trigger.isBefore && Trigger.isInsert) { // find the user who can accept leads and which has the fewest at the moment Double least = 99999; // start with large number, find which user has least for ( User u : [select id,lastname,Open_Leads_Owned__c from User where isActive = true and Receiving_Leads__c = true]) { if ( u.Open_Leads_Owned__c == null || u.Open_Leads_Owned__c < least) { Trigger.new.ownerid = u.id; // this user will own the new lead least = u.Open_Leads_Owned__c; // changes owner before record is inserted } } } /* remaining code will keep the (summary field) Open_Leads_Owned__c * uptodate on each user record adjusts the value on insert, delete and transfer */ if (Trigger.isAfter) { if (Trigger.isInsert) { System.assert(Trigger.old == null,' old data row cannot exist at insert?'); System.assert(Trigger.new != null,' expected new object row in isInsert'); leadOwnerRelation.updateOpenLeadCount( Trigger.new.ownerid ); // call to a package } else if (Trigger.isUpdate ) { // as in change owner // here we have to recalc both the old owner and new owner System.assert(Trigger.old != null,' old data row must exist at update'); System.assert(Trigger.new != null,' what, no new in Trigger data in update'); if (Trigger.old.ownerid != Trigger.new.ownerid ) { // update includes a transfer owner leadOwnerRelation.updateOpenLeadCount( Trigger.old.ownerid ); leadOwnerRelation.updateOpenLeadCount( Trigger.new.ownerid ); } } else if (Trigger.isDelete) { System.assert(Trigger.old != null,' old data row must exist at delete time'); System.assert(Trigger.new == null,' cant have new object in isDelete'); leadOwnerRelation.updateOpenLeadCount( Trigger.old.ownerid ); } } } // end of trigger

 

Hi,

 

I will have to write the Apex class for associating master object with the chile object. How I can achieve this scenario.

 

Please help me........

 

Thanks in advance.

 

 :smileymad: :smileymad:

Message Edited by venkatesh on 03-06-2009 06:43 AM

Hi,

 

I'm trying to develop a very simple trigger that essentially creates a contact and a few contact share records when a User record is created.  

 

In my dev environment the trigger and all of the unit tests work flawlessly, when I transfer to production the trigger doesn't even fire and as a result my unit tests fail. 

When I run the tests I get no indication that the Trigger even attempted to run, let alone some error to tell me why it might be failing.  Also, System.Debug within the Trigger doesn't show in my test output.

 

The trigger itself is below.  I can post the support class code if needed but it doesn't seem to be getting that far so I don't know if it will help.

 

Any help is greatly appreciated.

 

Thanks

Jon

 

 

 

trigger User_Create_ContactSharing_Trigger on User (after insert)

{

 

// User Create ContactShareing Trigger

 

 

 

 

System.Debug('Inside Insert Trigger');

 

//get the user data and pass to the function in our support class

User[] theUsers = [select id,name,firstname,lastname,companyname, email, phone, defaultcurrencyisocode from User where id in :trigger.new];

 

 

//loop through all new users

 for(User newUser :theUsers)

{

 

User_Contact_Trigger_Class.User_Create_Trigger(newUser);

 

}

 

 

}

im getting the following error when i try to login
 
Unable to generate a temporary class (result=1).
error CS2001: Source file 'C:\WINDOWS\TEMP\oqt-a62h.0.cs' could not be found.
 
the error is on the following line of code within 

Public Class EnterpriseLoginBean

    Public Sub initByUsername()

        salesForceService = New SforceService()
 
 
It appears that my workflow rule which should be triggered when a lead record is updated and the lead status = closed - converted, only is triggered if I click edit and manually update the status.  My rule is not triggered when I click lead conversion even though the status is updated to closed - converted.  Is there anyway to trigger a workflow rule when a lead is converted?