• dmcheng
  • SMARTIE
  • 1300 Points
  • Member since 2006

  • Chatter
    Feed
  • 47
    Best Answers
  • 5
    Likes Received
  • 0
    Likes Given
  • 163
    Questions
  • 594
    Replies

Developer Community:  

 

I have a trigger on the Opportunity object that inserts opportunity line items as assets on the account which is working as expected.  A second trigger on the asset object needs to insert a list of child objects called Asset Components to each asset. If I manually insert an asset (without using the opportunity trigger), the asset trigger works as expected.  If I insert the records via the trigger, the child records are not created.  I'm not sure what I'm missing here - any thoughts? 

 

Opportunity trigger works as expected, all assets are inserted: 

trigger createAsset on Opportunity (after update) {
	
	List<Opportunity> opptys = new List<Opportunity>();
	List<OpportunityLineItem> opptyLIS = new List<OpportunityLineItem>();
	List<Asset> assets2Insert = new List<Asset>();
	List<Product_Component__c> pcs = new List<Product_Component__c>();
	List<Asset_Component__c> assetComps2Insert = new List<Asset_Component__c>();
	List<Asset> ats = new List<Asset>();	
	
	for(Opportunity o : trigger.new){
		if((o.IsWon == true)&&(o.Status__c=='Shipped')){
			opptys.add(o);
		}
	}
	
	if(!opptys.isEmpty()){
		for(Opportunity os:opptys){
		opptyLIS = [SELECT id, OpportunityId, Opportunity.Accountid, PriceBookEntryid, Quantity,
					PricebookEntry.Product2id, Opportunity.CloseDate, PricebookEntry.Product2.ProductCode
					FROM OpportunityLineItem 
					WHERE OpportunityId = :os.id];
		}
		
		for(OpportunityLineItem lis : opptyLIS){
			Integer lineQty=integer.valueOf(lis.Quantity);
			
			for(Integer i=0; i<lineQty; i++){
					Asset newAsset = new Asset();
					newAsset.Name = lis.PricebookEntry.Product2.ProductCode;
					newAsset.AccountId = lis.Opportunity.AccountId;
					newAsset.Product2Id = lis.PricebookEntry.Product2Id;
					newAsset.H_W_Exp_Date__c = lis.Opportunity.CloseDate.addyears(1);
					newAsset.S_W_Exp_Date__c = lis.Opportunity.CloseDate.addyears(2);
				assets2Insert.add(newAsset);
			}
		}
	}
	
	insert assets2Insert;
}

 

Asset trigger - works when asset is inserted manually, but not when inserted by above trigger: 

trigger createAssetComponents on Asset (after insert) {
	
	List<Product_Component__c> pcs = new List<Product_Component__c>();
	List<Asset_Component__c> assetComps2Insert = new List<Asset_Component__c>();
	List<Asset> ats = new List<Asset>();

	
	for(Asset a : trigger.new){
		ats.add(a);

	}
	if(!ats.isEmpty()){
		for(Asset asInTrigger : ats){
		pcs=[SELECT Top_Level_Product__c, Quantity__c, Component__c, 
						Component_Name__c, Name
						FROM Product_Component__c 
						WHERE Top_Level_Product__c = :asInTrigger.Product2Id]; 
				
		}
		
		for(Asset ats2 : ats){
			for(Product_Component__c p : pcs){
	
				for(integer c=0; c< p.Quantity__c; c++ ){
					Asset_Component__c assetComps = new Asset_Component__c();
					assetComps.Parent_Asset__c = ats2.id;
					assetComps.Installed__c = date.today();
					assetComps.xAsset_Component__c = p.id;	
					assetComps.Serial_Number__c = 'fill in'+c;
					assetComps2Insert.add(assetComps);	
				}    
			}
		updatedAsset.add(ats2);
	}
	insert assetComps2Insert;
	}	
}

 Thanks for your assistance!

JoAnn

I have a scheduled job that runs nightly which basically updates any team member that is active and becomes inactive due the the start and end date and visa versa.  When update these records there are a lot of triggers that get set off.  If the list of active --> Inactive or the inactive -->active is too big I will run into soql limits

 

In my code put a limit on the query to only retrieve x amount for inactive or active lists.  but really I need it to run all of them

 

any way of accomplishing this.

 

Hi all,

 

As per the requirement i need to schedule more than five batch apex, i.e., i need to call the next batch class process at the end of first/previous class. how can i achieve this. waiting for your valuable tips.

 

 

Thanks,

Bala

I've used a pretty awesome trigger template, and I've tested that the trigger behavior is working as expected (knock on wood). I took it from a peer's blog (http://blog.deadlypenguin.com/blog/2012/02/13/classifying-triggers-in-salesforce/) and it's working well.

 

The logic of the trigger automatically inserts child records (Vendor_Scorecard__c) lookup to the parent (Service_Request__c) if Service Request is in Status of 'In Review'.

 

I'm having trouble on the test class, I need to query for the existence of child VSCs and assert that they inserted properly, but i'm not sure how. I also have another issue from a pre-existing trigger (too many SOQL) but i'm not sure why it hits the limit.

 

This tests a lot of triggers...and some are poorly written so I can't set test data over 5 records or it fails (that's another problem, not for today). How would I query for the created Vendor_Scorecard__c for each of the srf's in the list?

 

static testMethod void addVendorIdTest() {   
	
	//Create test Task Order
	Task_Order__c t = new Task_Order__c(Name = 'Test Task Order');
	Insert t;	       
	
	//Create test Account
	Account a = new Account(Name = 'Test', Task_Order__c = t.Id, Lin__c = '9999');
	Insert a;
   
	//Create test Contact
	Contact c = new Contact(LastName = 'Test', AccountId = a.Id, Vendor_Id__c = '123ABC');
	Insert c; 
	
	//Create test Service Request BULK
	List <Service_Request__c> srfTestList = new List <Service_Request__c>();
	  for (integer i=0; i<5; i++) {
		Service_Request__c sr = new Service_Request__c(
			Task_Order__c = t.Id, 
			Vendor_Id__c = '123ABC', 
			Status__c = 'New'
		);
		  srfTestList.add(sr);
	  }
			
	  insert srfTestList;
	  
	  test.startTest();  
	  for(Service_Request__c srf: srfTestList) {
		srf.Status__c = 'In Review';
		update srf;  	
	  }
	  test.stopTest();
				
	List <Service_Request__c> insertedSRFs = [Select Vendor_Name__c, Id FROM Service_Request__c WHERE Id IN: srfTestList];
	
	String testVendor = [SELECT Vendor_Name__c FROM Service_Request__c WHERE Id = :srfTestList LIMIT 1].Vendor_Name__c;
	
	for (Service_Request__c s: insertedSRFs){
	  System.assertEquals(c.Id, testVendor);
	}
	
}

 

This is the method (classified trigger) that creates the Vendor_Scorecard__c objects for each srf in srfList. Ignore the excessive comments, that's for me...

 

public void doAwesomeness() {
	
	if (isUpdate) {
		
	  set<Id> objIds = new Set<Id>();
	  
	  for (Service_Request__c srf: newObjs) {
		if (
			oldMap.get(srf.ID) != null &&
			oldMap.get(srf.ID).Status__c != srf.Status__c &&
			srf.Status__c == 'In Review'
		) {
		  //Set for unique IDs for records that pass conditionals above 
			objIds.add(srf.Id);
		}
	  }
	  
	  //Maybe don't need where Status statement, since it's done above?
	  //List is to house records that have passed conditions above		  
	  List <Service_Request__c> srfList =
		[SELECT Status__c, Id, Vendor_Name__c
		 FROM Service_Request__c
		 WHERE Status__c = 'In Review'
		 AND Id IN: objIds];
	  
	  //List for update of VSCs added, for each of the srf in the list above
	  List<Vendor_Scorecard__c> vscList = new List<Vendor_Scorecard__c>();

	  //for records in list, iterate through and use values from those records to create new child VSCs
	  for (Service_Request__c srf: srfList){
		Vendor_Scorecard__c vsc = new Vendor_Scorecard__c (
			Service_Request__c = srf.Id, 
			Vendor__c = srf.Vendor_Name__c,
			RecordTypeId = '012800000007dww');
		vscList.add(vsc);
	  }
	  if (!vscList.isEmpty()) {
		try {
		  insert vscList;
		} catch (DmlException e) {}
	  }
	//End Routing Boolean, return necessary?     
	} else {
	  return;
	}
}

 

 

 

 

 

  • June 01, 2012
  • Like
  • 0

I have been trying to automatically populate the "Related To" field on the task view with the Account Name using a custom link. Currently it is a drop down and then you have to search for the account name. The account name appears on the contact view (where I created the task from).

I am using this formula but am receiving an error, any help would be appreciated.

 

 

https://emea.salesforce.com/00T/e?retURL=%2F00320000001jWar&who_id=00320000001jWar&what_id={!Account_ID}

 

 

Unable to Access Page
The value of the "what_id" parameter contains a character that is not allowed or the value exceeds the maximum allowed length. Remove the character from the parameter value or reduce the value length and resubmit. If the error still persists, report it to our Customer Support team. Provide the URL of the page you were requesting as well as any other related information.
Back

 

Hello,

 

I am trying to check within a visualforce component if an attribute is of a particular type. If it is I then wish to cast the attrbiute to a different class type.  The type is a String which is used for comparison.  I thought a Case statement could be used for this but I'm getting errors and wondering now if it cannot be used

 

First of all I tried the following

 

{!
Case(detailItem.type, 'NUMB',(ItemNumb)detailItem, 'TEXT',(ItemText)detailItem, detailItem)
}

 

but this gives syntax errors.  Missing ')'

 

From this I cannot determine where I am missing the ')'

 

To see if it was a result of where I try to cast the class I reoved the cast and tried the following (just for debugging)

 

{!
Case(detailItem.type, 'NUMB',detailItem, 'TEXT'detailItem, detailItem)
}

 

but this gives an error as follows

 

Description Resource Path Location Type
Save error: Incorrect parameter for function 'Case()'. Expected Object, received Text 

 

My expression is therefore a string but the return type is an object.  Is this not allowed?  If so woukd an if statement allow this?

 

On trying the following I received a Missing ')' error also.

 

{!if(detailItem.type=='NUMB',(ItemNumb)detailItem,detailyItem)}   

 

Any suggestions on whether a cast like this can be done in an if/case statement, and where I am missing  ')' if so are welcome.

 

Thanks in advance.

the scenario looks like this...when i create a lead record ,a contact record is inserted based on the lead field values(some mapping is there like name.address..etc).the problem is i want a get contact id of the record which is inserted when lead is created..how do i get that...there is a lookup field on 3rd  object where i want the contact id.  please help....

 

trigger test1 on Lead (after insert)
{
    
     Set<ID> ls = new Set<ID> ();
     for(Lead l:Trigger.new)
    {
        ls.add(l.id);  
    }
    
    List<Lead> lis=[Select Id,Name, Status,Email,Company,fax,from Lead where id in:ls];
       List<Contact> con=[Select Id,Name ,Email_2__c,fax from Contact ];
       List<Contact> lstContact = new List<Contact>();

          
       
   
       for(Lead ld:lis)
       {
           for(Contact cn:con)
           {
              
                   
                   Contact objC= new Contact();    
                objC.FirstName=ld.FirstName;
                objC.LastName=ld.LastName;
                lstContact.add(objC);
 
           }    
               customobj.lookupfield=...?????(here i want the contact id)
       }
           
           if(lstContact.size() > 0 )
        insert lstContact;
      
                   
}

I've been trying to use a custom field to display the owner of an account in a custom Opportunity field Account_Owner__c. I'm new to Apex, but found a similar trigger I'm trying to adapt to my purpose. I'm currently receiving the following error:

 

Compile Error: Invalid foreign key relationship: Account.ownerid at line 19 column 81

 

Any guidance here is much appreciated.

 

 

trigger trgAccOwner on Opportunity (before insert,before update) 
{
    Set<Id> accid=new  Set<Id>();
    Set<Id> accownerid=new  Set<Id>();
    for(Opportunity  tl:Trigger.new)
    {
        accid.add(tl.account.Id);
    }
    map<id,account> mpacc=new map<id,account>([select id,name,ownerid from account where id in :accid]);
    for(account acc:mpacc.values())
    {
        accownerid.add(acc.ownerid);
    }
    map<id,user> mpuser=new map<id,user>([select id,name from user where id in :accownerid]);
    if(mpuser.size()>0)
    {
        for(integer i=0;i<Trigger.new.size();i++)
        {
            Trigger.new[i].Account_Owner__c=mpuser.get(mpacc.get(Trigger.new[i].account.ownerid.name));
        }
    }
}

 

 

 

Thanks much!

 

I need some help wrapping my head around testing this trigger - I seem to have prepared and inserted my dataset correct, but I'm not sure why it's giving me an error of "Expected:Null".

 

My Trigger (working in sandbox, manually inserting records)

 

trigger AddCountyId on Contact (before insert, before update) {
	
    Set<String> CountyIds = new Set<String>();
    
    for(Contact c : Trigger.new) {       
       CountyIds.add(c.fdicCountyID__c);       
    }       
    
    Map<String, Id> countyMap = new Map<String,Id>();

	//Add both sets of IDS to above Map
	for(County__c cty : [SELECT cty.Id, cty.fdicCountyID__c
		FROM County__c cty
		WHERE cty.fdicCountyID__c != null AND cty.fdicCountyID__c IN :CountyIds]) {
    		countyMap.put(cty.fdicCountyID__c, cty.Id);
		}    
  
  	//Update Primary County on the Contact with County ID
    for(Contact updateC : Trigger.new) {
	    try {    
	          if(updateC.fdicCountyID__c != null) {
	  			  //Update Primary County with County Id from Map
	              updateC.Primary_County__c = countyMap.get(updateC.fdicCountyID__c);
	          }
	    }  
	    catch (Exception e) {
	   	}
	}

}

 

Stripped down test method in my test class

 

	static testMethod void verifyCountyId() {
		
		//Create Test County
  		County__c cty = new County__c(Name='Test County', Latitude__c = 1, Longitude__c = 1, fdicCountyId__c ='abcd1234');
  		insert cty;
		
		//Create Test Vendor
		Account vAcct = new Account(Name = 'Test Vendor Account');
		insert vAcct;
		Contact v = new Contact(LastName = 'Vendor Demo', last_engaged_date__c = Date.today(), AccountId = vAcct.Id, fdicCountyId__c = 'abcd1234');
		insert v;
		
		System.assertEquals (v.Primary_County_ID__c, cty.Id);
	}

 I get a System.AssertException: Assertion Failed: Expected:null Actual: a0hJ000000FymvMac 

 

Does anyone have any insight as to what i'm doing wrong?

  • February 27, 2012
  • Like
  • 0

Hi,

 

I have a custom visualforce that uses a standard controller and I need to add a “Save & New” button. What is the action name for the method?

 

Thank you

 

  • February 17, 2012
  • Like
  • 0

Hi,

 

I am invoking my batch class from a scheduler. In the scheduler i am calling the same batch class twice with different query and parameters one by one like below:-

 

A_Batch batch1 = new A_Batch('B1', query1);
Database.executeBatch(batch1, 200);
            
A_Batch batch2 = new A_Batch('B2', query2);
Database.executeBatch(batch2, 200);

 

Can i assume that my batch2 be called only after batch1 is processed or queue'd?

 

Thanks.

I'm trying to run a scheduled class and I need help with building the list of records that I need to update.  Below is my class, which will be referenced by a scheduled class: 

 

I'm getting an error : Save error: Initial term of field expression must be a concrete SObject: LIST<Guest_Card__c>

 

global class GuestCardsCheck {


/*
Purpose: - On a nightly basis, any Guest Cards that meet certain conditions will be
automatically changed to "Inactive" status. A scheduled class will call this
class method to perform this check.

*/

public static String checkGCQuery = 'select Id from Guest_Card__c where Inactive_Reason__c = "Independent Lead Source" AND ((Move_In_Date__c != Null AND LastModifiedDate >= Today.addDays(-30)) OR(Move_In_Date__c = Null AND LastModifiedDate >= Today.addDays(-60)))';

public static void checkGuestCards ()
{

//collect a list of records that need to be inactivated

List <Guest_Card__c> InactiveGCs = Database.query(checkGCQuery);

InactiveGCs.Status__c = 'Inactive';

update InactiveGCs;


}

 

 

ListMetadataQuery query = new ListMetadataQuery();

 query.type = "ApexClass";

 double asOfVersion = 23.0;

 // Assume that the SOAP binding has already been established.

 FileProperties[] lmr = metadataService.listMetadata( new ListMetadataQuery[] { query }, asOfVersion);

if (lmr != null)
{
  foreach(FileProperties n in lmr)
{
  string filename = n.fileName;
}
}


 I m using this code to get list of Apex classes.

I want list of folders for //***query.type = "EmailTemplate";***// component type.

Is it possible using listMetadata() method or any other way to achieve this?

please reply asap.

thanks in advance.
  • February 13, 2012
  • Like
  • 0

Hello everyone, I'm pretty new to developing and my org has just run accross a problem. We need to track history on product changes within the Opporunitiy. I know this is not supported nativly. My thought is that we can run a trigger and populate a list of changes. However I'm not sure where to start on this. Any references or advice would be helpful. Thanks in advance!

Really confused here - batch jobs are allowed 1 callout execute(), and I made 1, and then got this error.

 

I set the batch size to 1 as well.

 

In fact, I basically copy & pasted a different batch job where I'm doing something very similar, with the only change here being I'm using the standard  "implements Database.Batchable<sObjects> " instead of a custom iterable.  Any thoughts?

 

global with sharing class g2wGetRegistrantDetailsBatch implements Database.Batchable<sObject> {

   public String sObjectQuery ='Select Id, CampaignId FROM CampaignMember' ;
   
   global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(sObjectQuery);
   }

    global void execute(Database.BatchableContext BC, List<sObject> scope){
        //Process this 1 campaignMember.  The batch size is always 1 due to 1 callout / batch job limit
        CampaignMember cm=(CampaignMember)scope[0];
        Campaign campaign=[SELECT Id FROM Campaign WHERE id=:cm.campaignId LIMIT 1];
        String requestURL='<my API request URL>';
        
        try{
            //Get registrant details
            system.debug('The request URL is'+requestURL);
            HttpResponse response=g2wUtils.getResponse(requestURL);//send out the request to the other server
        }catch(DMLException e){
           
        }//try
        
    }//execute

    global void finish(Database.BatchableContext BC){
   
    }//finish

    
}//g2wGetRegistrantDetailsBatch

 Called by:

    public static void scheduleQueuedBatchJobs(){
       g2wGetRegistrantDetailsBatch job=new g2wGetRegistrantDetailsBatch();
       String query='Select Id, CampaignId FROM CampaignMember';
       job.sObjectQuery=query;
       Id getRegistrantDetailsBatchJobId = Database.executeBatch(job, 1);//need the batch size at 1 due to callout limit of 1 per batch
    }//scheduleQueuedBatchJobs

 

Hi,

I have 3 custom objects and their feilds are :-

 

1> Object :-Salesreturn  ///////Feild:- Internal UIN

2>object:- UIN MASTERS///// Feild:- Extenal_uin_master,Registered_At_Depot_masters

3> object:- UIN PRODUCTS/////Feild:- a>Internal_UIN_products(this internal uin can be of Mechanic or retailer or reborer i.e max 3) ,,b> Registered_At_Depot_products(checkbox),,,c> Status:-submitted,in process,Start

 

Now, 

When we enter any Internal Uin in salesreturn object then it checks in UIN Products that this internal exists in UIN Product and if it exists and its status is not equal to submitted then Registered_at_Depot_products should get unchecked.

Also,this internal_uin_products is related to any Extenal_uin_master(which is there in UIN MASTERS object) and Hence,Registered_At_Depot_masters at uin masters should also get unchecked.

And a mail should go to a user say raj@abc.com

Good day all,

We are looking for sample APEX that would, upon Case creation or changing the existing Account on a case to perform the following:

 

Perform a lookup to the related Account and find the Entitlement Associated to the Account with a 'Type' field value of "Support Contract"

There can be from zero to many Entitlements associated to an Account, but there would only be one Entitlement with a the 'Type' field set to "Support Contract", so the results would return one record. 

We need this entitlement to be automatically associated to the Case.  There are no Milestones to worry about. 

Essentially, when a Case is created or the Case Account field is modified.  Then we can create lookup fields to display (Status, Contract Start and End Date) on the case.

 

Does anyone have any sample APEX I can look at that might point me in the right direction.

 

Currently 99% of cases are created through the "email to case" functionality, not manually.

 

Thank you in advance for your assistance.

I can't figure out why this isn't triggering when i have it run against a case that has comments.

 

usually i'd expect it to throw an error. but the lack of error shows that it isn't even entering the for loop

 

for (Case escalatedcase:Trigger.new){
    
    
   // escalatedcase.addError(escalatedcase.CaseComments);
    
    
                                        for(CaseComment oldcomment :  escalatedcase.CaseComments) {
                                      CaseComment newcomment = oldcomment.clone(false, true);
                                      //newcomment.ParentId = CaseAdd.Id;
                                      
                                      ccomments.add(newcomment);
                                       escalatedcase.addError('Please choose a Tier 2 Escalation Level to direct escalation.'); //in your face!
                                    }
}

 

I'm trying to find a way you can get the number of future calls an org has processed in a 24hr period. In the docs there are Limits.getFutureCalls() and Limits.getLimitFutureCalls() but these seem to be the number of future calls in the future call stack and the limit of the stack rather than the number that have taken place in the 24hr period...

  • January 23, 2012
  • Like
  • 0

Hi,

 

Can someone please help me understand how to avoid the below error in the batch:

 

Aggregate query has too many rows for direct assignment, use FOR loop

 

The batch uses the below query:

 

SELECT Id, Type, Potential_Revenue__c, (SELECT Id, Total_Perm_Value__c, CreatedDate, Contract_Type__c, Status, Account_End_Date__c  from Agreements where status != \'Activated\') From Account';

 

And the error comes in at the below line of code:

 

global void execute(Database.BatchableContext BC, List<sObject> scope)
{
for(sobject s : scope)
{
Account a = (Account) s;
custIndicator = 0;
if(a.Agreements != null && a.Agreements.size() > 0) <--------- Error comes here.
{

 

thanks a lot!!

Has anyone been successful in overriding the FlowPageBlockBtns CSS for a Visual Workflow VF page?
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_flows_customize_runtime_ui.htm

I want to center the buttons and have tried to override the Salesforce CSS several ways but none of them work, the buttons still end up with text-align:right.  See code and resulting screenshot where the overrides haven't taken effect.
 
<apex:page showHeader="false" sidebar="false" standardStylesheets="false">
	<style>
		.FlowPageBlockBtns, 
		.pbHeader .pbButton td,
		.pbHeader .td {
			text-align: left !important;
		}

		body {
			font-size: 1.2em;
		}
	</style>

	<div>
		<div style="text-align: center;">
			Quote Request Form
		</div>
	</div>
	<flow:interview name="Quote_Request_Form" />
</apex:page>
User-added image
 
How can I align the Next and Finish buttons on a Visual Flow?  I've tried setting the CSS but it doesn't work.
<style>
        .FlowPageBlockBtns .FlowNextBtn,
        .FlowPageBlockBtns .FlowPreviousBtn,
        .FlowPageBlockBtns .FlowFinishBtn,
        .center {
            text-align: center;
        }
        body {
            font-size: 1.2em;
        }
    </style>

 
Can high-volume portal users view all custom object records if sharing is Public Read Only?

If a custom object's org-wide sharing is set to Public Read Only, does a high-volume portal (HVP) user have access to custom records created by other HVP users?  NOTE: Each portal user has its own account.

The documentation implies that HVP users in different accounts cannot access each others' custom records, regardless of the sharing settings.  Can anyone confirm that?

The custom object in question does not have any lookups to account or contact, it stands alone.
I need to mimic an HTML POST form submission and redirect to the same page (non-Visualforce).  Is this possible using PageReference?  the form submission has to be a POST and I don't see any methods on PageReference for setting the  request body.
In a Visualforce controller, if I need to do an HTTP POST to an external website and then redirect to that same URL, how do I do it?

Here's the situation: currently the client has a plain HTML form (standard HTML form and input tags) that submits search criteria fields directly to a 3rd party search web site. This appears in a new window and displays a list of results.

They want a custom button on the Salesforce account detail page to submit account fields as search criteria to the external website. It should still open a new window to show the results

Question is: once I send the HTTPRequest in the controller, how do I redirect to the external website? Do I set up a PageReference to the HttpResponse, or just to the original URL?
I am trying to set up a Named Credential so that I can make callouts from a Visualforce controller to an external web app using Oauth 2.x.  The web application is called Procore.  I'm not sure how to configure the Authentication Provider and Connected App (if the latter is needed).

1. For the Authentication Provider, should I choose Salesforce or Open ID Connect as the provider type?

2a.  If I choose Salesforce, what is the URL suffix supposed to be?  

2b.  Also, this page says I need to set up a Connected App first.  Is this really necessary since I'm just doing a callout to an external app?  What should the Callback URL be for this connected app - a Salesforce URL or a Procore URL? https://help.salesforce.com/HTViewHelpDoc?id=sso_provider_sfdc.htm&language=en_US#sso_provider_sfdc

3.  If I choose Open ID Connect, what is the URL suffix supposed to be?  And since this requires the key and secret from Procore, what is the Redirect URI that I supply to Procore to get the key and secret?

Is the Email field in the User object hidden from customer community users? My client has customer community and has written an application for the community. There is an Apex class "with sharing" that selects various fields from the User object. When a community user accesses this method, all field values are returned except for the Email field, which returns a null value.

When a standard license user performs the same function, the email value is returned.

Portal User Visibility and Community User Visibility is enabled. There is a sharing rule on the User object and all the community users are in the group.
I'm testing Lightning Connect with a Microsoft Azure SQL db.  I'm getting an error when validating the external data source in Salesforce.  Here's the config:
external data source config

When I click Validate and Sync, I get this error:
The external system is unreachable. Make sure that the URL is correct in the external data source settings, and that the server's SSL certificate is valid for its domain name. Attempted to reach this URL: https://[myservername].database.windows.net:1433/$metadata

I have tried Anonymous authentication but I get the same error.

I've set up Azure firewall rules for the Salesforce IP addresses.
  • September 23, 2015
  • Like
  • 0
hello.  I need to change a Visualforce email template written by someone else.  They included a URLFOR in the template.  Apparently it used to work, but now when I try to view the template in Setup, there is an error 

"Error occurred trying to load the template for preview: Invalid parameter for function URLFOR. Please try editing your markup to correct the problem"

I can edit and save the template, but I still see the error.

I created a basic template for testing and the same error occurs.  Has anyone else run into this?

Here is the basic email template I created:
 
<messaging:emailTemplate subject="test" recipientType="User" relatedToType="Case">
    <messaging:plainTextEmailBody>
    </messaging:plainTextEmailBody>
    <messaging:htmlEmailBody >
        {!URLFOR($Action.Case.View, '111111111111111')}
    </messaging:htmlEmailBody>
</messaging:emailTemplate>


I'm having trouble with email template merge fields that are not being populated when the email is sent by Apex.

I have an Apex method that uses setTemplateId, setWhatId, and SetTargetObjectId. The template is an HTML template, not Visualforce. setTargetObjectId is set to a contact. setWhatId is a custom object that has no relationships with the contact object.

In the email template, I want to merge {!Contact.Name}. When the Apex method runs, it sends the email and links the activity to the contact, but the contact name is always blank in the email body.

Is this because the merge fields must be in the WhatId custom object? Or because the contact is linked to a portal user?
I have a client who wants the ability to clone a task that has multiple contacts. They would make slight changes to the cloned task (Assigned To, etc) but the multiple contacts would remain the same.

I'm getting a DUPLICATE_VALUE error when I tried to insert the cloned TaskRelation records and I can't figure out why. Do I need to create the task relation records in a different way?

Here's what I'm doing:

I retrieve the TaskRelation records for the original task, use the clone() list method, then insert the cloned Task, then replace the TaskId with the cloned task Id, and attempt to insert the cloned taskRelation records.

The error detail is:

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []

Here are the code snippets:
 
originalRelations = [SELECT RelationId, TaskId, IsWhat FROM TaskRelation 
        WHERE TaskId = :originalTask.Id AND IsWhat = false];
// Don't preserve Id, deep clone.
cloneTask = originalTask.clone(false, true);
cloneRelations = originalRelations.deepClone(false);
...
...
insert cloneTask;
for (TaskRelation relation : cloneRelations) {
    relation.TaskId = cloneTask.Id;
}
insert cloneRelations;

 
I have a Customer Community Plus site with portal users using Customer Portal licenses.  I want the portal users to  run User object reports so they can see last login, etc.  Portal users are still getting "Insufficient Privileges" when trying to run these reports, even though I think I've done all the necessary settings.

Here's what I've done:

In Sharing Settings, enabled External Sharing Model.

In Sharing Settings, on the User object, set the Default External Access to Private.*

In Sharing Settings - User Sharing Rules, set up a Read Only sharing rule for All Customer Portal Users.

On the report folder, share the folder to All Customer Portal Users as Viewer.

On the report itself, I'm using the Username, First Name, Last Name, Created Date and Last Login.  I'm filtering on Account.Name.  The portal user profile has Read permission to the Account object.

*This doesn't seem right, but that is what this article says:
https://help.salesforce.com/apex/HTViewSolution?urlname=Why-do-Portal-Reports-receive-an-Insufficient-error-or-are-missing-columns&language=en_US
Can anyone clarify the following about Social Persona and Social Post objects?

1. In a developer instance, do I need to open a case to enable visibility of Social Persona and Social Post objects in the Setup UI? I have Social Accounts/Contacts enabled but the Persona and Post do not appear in the Setup menu.

2. Are SocialPersona and SocialPost accessible to the API? When I'm in the Developer Workbench or Dev Console, those objects are not available for SOQL queries. However I can create triggers on Persona and Post via the Setup UI in the sandbox, and the Social Customer Service Implementation Guide refers to an Apex class that you can customize and which references SocialPersona and SocialPost.
I'm unable to create a project for a particular instance when using Eclipse Kepler, but I can create projects for other instances.

I'm getting an Eclipse error "Unable to create project.  Reason outOfMemory error: Java heap space".

I've made the following settings in my Eclipse.ini file but I'm still getting the error.  
-Xms256m
-Xmx1024m
-XX:PermSize=128m
-XX:MaxPermSize=512m

I'm using 32-bit Kepler on Windows 7 SP1.  Again, I am able to create projects for other sandbox instances, but not this particular instance.
Hello.  I need to refresh viewstate on a page to show the latest query results but it's not working. 

I have an inputText on the page for the user to enter a filter value.  When that happens, I re-query records and I rerender the pageBlockTable that displays the records.

I'm using onChange on the inputText and an actionFunction with Javascript.

When I enter a value in the input field, the page is rerendered.  However, the viewstate is not changing so the pageBlockTable still shows the original set of records.

Here are the code snippets.

VF page:
<apex:page>
	<script>
		CCx.thispage = {};
		CCx.thispage.filterByName = function(evt) {
			var name = evt.value;

			// log a google analytics event

			// submit via actionfunction
			doFilterByName(name);
		};
	</script>

	<apex:form id="form">
		<div class="ccx-list-header">
			<div class="ccx-advocate-buttons" id="bulkListActions">
				<apex:inputText value="{!searchName}" onChange="CCx.thispage.filterByName(this); return false;" 
						html-placeholder="Search for advocate" />
			</div>
		</div>
		<apex:actionFunction name="doFilterByName" action="{!filterByName}" 
				rerender="bulkListActions, advocateListTable" />


			<apex:pageBlock id="pageblock">
				<apex:pageBlockSection columns="1" collapsible="false" id="section">
					<apex:pageBlockTable id="advocateListTable" value="{!advocates}" var="advocateListItem">
					</apex:pageBlockTable>
				</apex:pageBlockSection>
			</apex:pageBlock>

Controller:
public class MyController {
	public String currentDeskId;
	public String searchName { get; set; }
	public List<CCx_AdvocateServices.onboardingAdvocateDecorator> advocates { get; set; }

	public void filterByName() {
		system.debug('*** searchName: ' + searchName);
		if (string.isBlank(searchName)) return;
		advocates = CCx_AdvocateSelector.selectAdvocateDecoratorForDeskAndName(currentDeskId, searchName);
		system.debug('*** advocates: ' + advocates);
		searchName = null;
	}
	
	// Constructor
	// etc
}


Hello.  I have a VF page showing a list of records in a pageblocktable.  I have an inputText field on the page where the user can enter a value to filter the list.  When the user enters the value, I'll re-query the data and rerender the pageblocktable.

I'm trying to use actionRegion and actionSupport for this, but it's not working.  The filterByName method never gets called.

Can anyone tell me what I'm doing wrong?  Does it have to do with onChange, or with the form submission process?  There are no other input fields on the page.

Here's a snippet of the VF page:
<apex:form >
	<div class="ccx-list-header">
		<div class="ccx-advocate-buttons" id="bulkListActions">
			<apex:actionRegion immediate="true">
				<apex:inputText value="{!searchName}" html-placeholder="Search for advocate">
					<apex:actionSupport action="{!searchAdvocate}" reRender="advocateListTable" event="onchange" />
				</apex:inputText>
			</apex:actionRegion>
		</div>
	</div>
</apex:form>

Here's a snippet from the controller:
public class MyController {
        public String currentDeskId;
	public String searchName { get; set; }
        public List<CCx_AdvocateServices.onboardingAdvocateDecorator> advocates { get; set; }

	public void filterByName() {
		system.debug('*** searchName: ' + searchName);
		if (string.isBlank(searchName)) return;
		advocates = CCx_AdvocateSelector.selectAdvocateDecoratorForDeskAndName(currentDeskId, searchName);
		system.debug('*** advocates: ' + advocates);
		searchName = null;
	}
	
	// Constructor
	// etc
}


I am having trouble with apex:outputField and a long textarea field.  Salesforce appears to be inserting extra spaces on lines after BR tags.

Here is the text exactly as it appears within the long textarea field:

The following questions and requirements are needed to continue your on-boarding. Once you have finished, you will have access to our system for client and resource management.

1. Fill in some demographic information
2. Sign the advocate handbook

If you have any questions, please contact your Program Manager.

Welcome to the team!

Note all lines are flush against the left margin.


Here is resulting HTML after apex:outputField:

<span>
The following questions and requirements are needed to continue your on-boarding. Once you have finished, you will have access to our system for client and resource management.
<br>
<br>
 1. Fill in some demographic information
<br>
 2. Sign the advocate handbook
<br>
<br>
 If you have any questions, please contact your Program Manager.
<br>
<br>
 Welcome to the team!
</span>


Note that all the text lines after BR tags are indented by a space.  This causes problems because we are also using Markdown to do some extra formatting.

Anyone know how I can eliminate those extra spaces?  I've already tried outputText but that does not suit our needs.

Thanks
David
If I use field level security to hide a field for a custom profile, a user in the profile can still global search for text in that field and the record will appear in the results, even though the field is hidden. Is that supposed to happen?

Furthermore, I have an external website making SOSL searches through the SOAP API using this custom profile, and this is also finding the record. (The SOSL search uses ALL FIELDS.) But the API documentation explicitly states that API calls respect field level security.

Is there a way to guarantee that UI search and API SOSL/SOQL search respect field level security?

Thanks
David
Hello.  I have a client who wants external users to submit data via a Sites VF page and update Opportunity records.

Of course the Sites profile doesn't have permissions to update standard objects.  Furthermore, the client does not want to purchase portal licenses for these external users.

I am considering two workarounds and am wondering if they are possible:

1.  Write some Apex webservices and call them from the Sites page Visualforce controller.
-- Looking at the webservice documentation, this doesn't seem possible, but I thought I check to make sure.

2.  Have the Sites page create a custom object record instead, and then write a trigger to update the opp record using the custom object.
-- Will the trigger be running in the system context and be able to update the opp?

Thanks
David

Hello.  In unit tests, is there a specific way of creating completed tasks so that they appear immediately in the ActivityHistory read-only object?   See code snippet below.  When I run the unit test, the activity history is empty.  However, when I create completed tasks manually in the UI, the ActivityHistory is populated.

Account acct = new Account(Name = 'Apex Test');
insert acct;

Task tsk1 = new Task(WhatId = acct.Id, Subject = 'Email: apex test', ActivityDate = date.today(), Status = 'Completed');
Task tsk2 = new Task(WhatId = acct.Id, Subject = 'Call: apex test', ActivityDate = date.today(), Status = 'Completed');
Task tsk3 = new Task(WhatId = acct.Id, Subject = 'Email: apex test', ActivityDate = date.today().addYears(-2), Status = 'Completed');
Task[] tskList = new List<Task>{ tsk1, tsk2, tsk3 };
insert tskList;

Account result = [select Id (SELECT ActivityDate, Subject FROM ActivityHistories) from Account where Id = :acct.Id];
Can anyone clarify the following about Social Persona and Social Post objects?

1. In a developer instance, do I need to open a case to enable visibility of Social Persona and Social Post objects in the Setup UI? I have Social Accounts/Contacts enabled but the Persona and Post do not appear in the Setup menu.

2. Are SocialPersona and SocialPost accessible to the API? When I'm in the Developer Workbench or Dev Console, those objects are not available for SOQL queries. However I can create triggers on Persona and Post via the Setup UI in the sandbox, and the Social Customer Service Implementation Guide refers to an Apex class that you can customize and which references SocialPersona and SocialPost.

The WebServiceCallout.invoke method is not documented in any Salesforce publications.  I asked tech support and they don't have any docs either in their internal knowledge base.  They said it is part of the wsdlToApex tool and not documented.  They pointed me to an external forum site where someone has posted some details.  (Sad that I have to go to non-salesforce forum site to get this.)

 

If anyone else is looking for this info, here is the link:

http://stackoverflow.com/questions/4392616/what-are-the-parameters-for-the-salesforce-webservicecallout-invoke-method

 

And here are the details from the post.  I have not verified any of the text or code, use at your own risk.

 

Object servicePort - A class with the following variables:
  String enpoint_x: containing the service endpoint (not sure if necessary)
  Map<String,String> inputHttpHeaders_x: custom httpHeaders
  Map<String,String> outputHttpHeaders_x: I think this is the httpHeaders that were returned
  String clientCertName_x: Used in configuring an SSL cert?
  String clientCert_x: Used in configuring an SSL cert?
  String clientCertPassword: Used in configuring an SSL cert?
  Integer timeout_x: How long (in milliseconds?) to wait for the response
  String[] ns_map_type_info: The first String is the namespace of the service schema, the second is the name of the object that contains the Apex classes defining the schema objects
Object request_x - The Apex object that will form the XML schema object
Map<String, Object> response_map_x - Object is the object that the result is to be unserialized into. String is the name of Object variable.
String[] {
  endpoint - The service endpoint
  soapAction - If the service call requires a soapAction, put it here. Otherwise leave blank.
  methodSchema - Schema for the request object
  method - Name of the request method
  responseSchema Schema for the response
  responseClass The Apex class that the response will be unserialized into
}

 

In addition, Soap headers can be inserted by creating an object in the servicePort class as well as a String with the same variable name+"_hns" that specifies the namespace for that object:

public SoapSecurity Security;
private String Security_hns = "Security=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";

 

The apex XML Schema objects should contain variables for each child element (or attribute). Arrays whose variable names match certain patterns define how the object variables are used in the xml.

 

Given the following example XML: 

<foo a="b"><bar>baz</bar></foo>

 

The Apex classes would be something like this:

public class MyService {
   public class bar {
      public String bar;
      private String[] bar_type_info = new String[] {'bar','http://www.w3.org/2001/XMLSchema','string','0','1','true'};
      private String[] apex_schema_type_info = new String[] {'http://schema.myservice.com', 'false', 'false'};
      private String[] field_order_type_info = new String[] {'bar'};
   }

   public class foo {
      public MyService.bar bar;
      public String a;
      private String[] bar_type_info = new String[] {'bar','http://schema.myservice.com','bar','0','1','true'};
      private String[] a_att_info = new String[] {'a'};
      private String apex_schema_type_info = new String[] {'http://schema.myservice.com','false','false'};
      private String[] field_order_type_info = new String[] {'bar'};
   }
}

 Please 

 

 

 

Here's a (brief) breakdown of these objects:

If the variable represents another XML element or a text node, then there needs to be a matching _type_info String[] e.g. bar_type_info. The elements of this array are: 1. XML element name 2. Schema 3. XML type 4. minOccurs 5. maxOccurs (set to '-1' for unbounded) 6. isNillable

If the variable represents an attribute, then there must be a matching _att_info String[] e.g. a_type_info. Thise simply contains the XML name of the attribute.

Note that if an class variable name is a reserved word, then _x is appended to it e.g. bar_x. This would affect the other variables names: bar_x_type_info. The Apex Developer's Guide explains their rules for names, but if you are manually creating it, I think you can give it whatever name you want--the arrays determine the XML element name...

I have not found a way to represent a simple XML type that also contains an attribute: e.g.

<foo bar="baz">bar</foo> 

The apex_schema_type_info array specifies information about the XML element represented by the class: 1. Schema 2. 'true' if elementFormDefault="qualified" 3. 'true' if attributeFormDefault="qualified"

I'm still rather fuzzy on what 2 and 3 actually do, but it seems to affect how child elements (and attributes) inherit the parent namespace (whether it's implied or must be specified in the resulting XML).

field_order_type_info simply specifies the order of the child elements.

 

This is an informational posting since I couldn't find it documented anywhere:

 

If a report is in a folder, the OwnerID of the report corresponds to the ID of the folder object, so you can query a report folder's contents like this:

 

 

folder[] ff = [select id from folder where developername = 'Community_Inventory_Tool_Reports'];
id fid = (ff.isEmpty()) ? null : ff[0].id;
report[] rpts = [select id, name, description from report where ownerid = : fid and ownerid != null order by name];
return (rpts.isEmpty() == null) ? null : rpts; 

 

 

 

 

I finally got Validation/Triggers enabled for Lead Conversion, but now I can't figure out how to code a trigger for it.  I've tried

Code:
trigger test on Lead (after convert) {
}

but I get an Invalid Token error.  There are no hints in the documentation.

thanks
David
Can high-volume portal users view all custom object records if sharing is Public Read Only?

If a custom object's org-wide sharing is set to Public Read Only, does a high-volume portal (HVP) user have access to custom records created by other HVP users?  NOTE: Each portal user has its own account.

The documentation implies that HVP users in different accounts cannot access each others' custom records, regardless of the sharing settings.  Can anyone confirm that?

The custom object in question does not have any lookups to account or contact, it stands alone.
I need to mimic an HTML POST form submission and redirect to the same page (non-Visualforce).  Is this possible using PageReference?  the form submission has to be a POST and I don't see any methods on PageReference for setting the  request body.
In a Visualforce controller, if I need to do an HTTP POST to an external website and then redirect to that same URL, how do I do it?

Here's the situation: currently the client has a plain HTML form (standard HTML form and input tags) that submits search criteria fields directly to a 3rd party search web site. This appears in a new window and displays a list of results.

They want a custom button on the Salesforce account detail page to submit account fields as search criteria to the external website. It should still open a new window to show the results

Question is: once I send the HTTPRequest in the controller, how do I redirect to the external website? Do I set up a PageReference to the HttpResponse, or just to the original URL?

Is the Email field in the User object hidden from customer community users? My client has customer community and has written an application for the community. There is an Apex class "with sharing" that selects various fields from the User object. When a community user accesses this method, all field values are returned except for the Email field, which returns a null value.

When a standard license user performs the same function, the email value is returned.

Portal User Visibility and Community User Visibility is enabled. There is a sharing rule on the User object and all the community users are in the group.
I'm testing Lightning Connect with a Microsoft Azure SQL db.  I'm getting an error when validating the external data source in Salesforce.  Here's the config:
external data source config

When I click Validate and Sync, I get this error:
The external system is unreachable. Make sure that the URL is correct in the external data source settings, and that the server's SSL certificate is valid for its domain name. Attempted to reach this URL: https://[myservername].database.windows.net:1433/$metadata

I have tried Anonymous authentication but I get the same error.

I've set up Azure firewall rules for the Salesforce IP addresses.
  • September 23, 2015
  • Like
  • 0
I have a client who wants the ability to clone a task that has multiple contacts. They would make slight changes to the cloned task (Assigned To, etc) but the multiple contacts would remain the same.

I'm getting a DUPLICATE_VALUE error when I tried to insert the cloned TaskRelation records and I can't figure out why. Do I need to create the task relation records in a different way?

Here's what I'm doing:

I retrieve the TaskRelation records for the original task, use the clone() list method, then insert the cloned Task, then replace the TaskId with the cloned task Id, and attempt to insert the cloned taskRelation records.

The error detail is:

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []

Here are the code snippets:
 
originalRelations = [SELECT RelationId, TaskId, IsWhat FROM TaskRelation 
        WHERE TaskId = :originalTask.Id AND IsWhat = false];
// Don't preserve Id, deep clone.
cloneTask = originalTask.clone(false, true);
cloneRelations = originalRelations.deepClone(false);
...
...
insert cloneTask;
for (TaskRelation relation : cloneRelations) {
    relation.TaskId = cloneTask.Id;
}
insert cloneRelations;

 
I'm unable to create a project for a particular instance when using Eclipse Kepler, but I can create projects for other instances.

I'm getting an Eclipse error "Unable to create project.  Reason outOfMemory error: Java heap space".

I've made the following settings in my Eclipse.ini file but I'm still getting the error.  
-Xms256m
-Xmx1024m
-XX:PermSize=128m
-XX:MaxPermSize=512m

I'm using 32-bit Kepler on Windows 7 SP1.  Again, I am able to create projects for other sandbox instances, but not this particular instance.
Hello.  I need to refresh viewstate on a page to show the latest query results but it's not working. 

I have an inputText on the page for the user to enter a filter value.  When that happens, I re-query records and I rerender the pageBlockTable that displays the records.

I'm using onChange on the inputText and an actionFunction with Javascript.

When I enter a value in the input field, the page is rerendered.  However, the viewstate is not changing so the pageBlockTable still shows the original set of records.

Here are the code snippets.

VF page:
<apex:page>
	<script>
		CCx.thispage = {};
		CCx.thispage.filterByName = function(evt) {
			var name = evt.value;

			// log a google analytics event

			// submit via actionfunction
			doFilterByName(name);
		};
	</script>

	<apex:form id="form">
		<div class="ccx-list-header">
			<div class="ccx-advocate-buttons" id="bulkListActions">
				<apex:inputText value="{!searchName}" onChange="CCx.thispage.filterByName(this); return false;" 
						html-placeholder="Search for advocate" />
			</div>
		</div>
		<apex:actionFunction name="doFilterByName" action="{!filterByName}" 
				rerender="bulkListActions, advocateListTable" />


			<apex:pageBlock id="pageblock">
				<apex:pageBlockSection columns="1" collapsible="false" id="section">
					<apex:pageBlockTable id="advocateListTable" value="{!advocates}" var="advocateListItem">
					</apex:pageBlockTable>
				</apex:pageBlockSection>
			</apex:pageBlock>

Controller:
public class MyController {
	public String currentDeskId;
	public String searchName { get; set; }
	public List<CCx_AdvocateServices.onboardingAdvocateDecorator> advocates { get; set; }

	public void filterByName() {
		system.debug('*** searchName: ' + searchName);
		if (string.isBlank(searchName)) return;
		advocates = CCx_AdvocateSelector.selectAdvocateDecoratorForDeskAndName(currentDeskId, searchName);
		system.debug('*** advocates: ' + advocates);
		searchName = null;
	}
	
	// Constructor
	// etc
}


Hello.  I have a VF page showing a list of records in a pageblocktable.  I have an inputText field on the page where the user can enter a value to filter the list.  When the user enters the value, I'll re-query the data and rerender the pageblocktable.

I'm trying to use actionRegion and actionSupport for this, but it's not working.  The filterByName method never gets called.

Can anyone tell me what I'm doing wrong?  Does it have to do with onChange, or with the form submission process?  There are no other input fields on the page.

Here's a snippet of the VF page:
<apex:form >
	<div class="ccx-list-header">
		<div class="ccx-advocate-buttons" id="bulkListActions">
			<apex:actionRegion immediate="true">
				<apex:inputText value="{!searchName}" html-placeholder="Search for advocate">
					<apex:actionSupport action="{!searchAdvocate}" reRender="advocateListTable" event="onchange" />
				</apex:inputText>
			</apex:actionRegion>
		</div>
	</div>
</apex:form>

Here's a snippet from the controller:
public class MyController {
        public String currentDeskId;
	public String searchName { get; set; }
        public List<CCx_AdvocateServices.onboardingAdvocateDecorator> advocates { get; set; }

	public void filterByName() {
		system.debug('*** searchName: ' + searchName);
		if (string.isBlank(searchName)) return;
		advocates = CCx_AdvocateSelector.selectAdvocateDecoratorForDeskAndName(currentDeskId, searchName);
		system.debug('*** advocates: ' + advocates);
		searchName = null;
	}
	
	// Constructor
	// etc
}


I am having trouble with apex:outputField and a long textarea field.  Salesforce appears to be inserting extra spaces on lines after BR tags.

Here is the text exactly as it appears within the long textarea field:

The following questions and requirements are needed to continue your on-boarding. Once you have finished, you will have access to our system for client and resource management.

1. Fill in some demographic information
2. Sign the advocate handbook

If you have any questions, please contact your Program Manager.

Welcome to the team!

Note all lines are flush against the left margin.


Here is resulting HTML after apex:outputField:

<span>
The following questions and requirements are needed to continue your on-boarding. Once you have finished, you will have access to our system for client and resource management.
<br>
<br>
 1. Fill in some demographic information
<br>
 2. Sign the advocate handbook
<br>
<br>
 If you have any questions, please contact your Program Manager.
<br>
<br>
 Welcome to the team!
</span>


Note that all the text lines after BR tags are indented by a space.  This causes problems because we are also using Markdown to do some extra formatting.

Anyone know how I can eliminate those extra spaces?  I've already tried outputText but that does not suit our needs.

Thanks
David
If I use field level security to hide a field for a custom profile, a user in the profile can still global search for text in that field and the record will appear in the results, even though the field is hidden. Is that supposed to happen?

Furthermore, I have an external website making SOSL searches through the SOAP API using this custom profile, and this is also finding the record. (The SOSL search uses ALL FIELDS.) But the API documentation explicitly states that API calls respect field level security.

Is there a way to guarantee that UI search and API SOSL/SOQL search respect field level security?

Thanks
David
Hello.  I have a client who wants external users to submit data via a Sites VF page and update Opportunity records.

Of course the Sites profile doesn't have permissions to update standard objects.  Furthermore, the client does not want to purchase portal licenses for these external users.

I am considering two workarounds and am wondering if they are possible:

1.  Write some Apex webservices and call them from the Sites page Visualforce controller.
-- Looking at the webservice documentation, this doesn't seem possible, but I thought I check to make sure.

2.  Have the Sites page create a custom object record instead, and then write a trigger to update the opp record using the custom object.
-- Will the trigger be running in the system context and be able to update the opp?

Thanks
David

Hello.  In unit tests, is there a specific way of creating completed tasks so that they appear immediately in the ActivityHistory read-only object?   See code snippet below.  When I run the unit test, the activity history is empty.  However, when I create completed tasks manually in the UI, the ActivityHistory is populated.

Account acct = new Account(Name = 'Apex Test');
insert acct;

Task tsk1 = new Task(WhatId = acct.Id, Subject = 'Email: apex test', ActivityDate = date.today(), Status = 'Completed');
Task tsk2 = new Task(WhatId = acct.Id, Subject = 'Call: apex test', ActivityDate = date.today(), Status = 'Completed');
Task tsk3 = new Task(WhatId = acct.Id, Subject = 'Email: apex test', ActivityDate = date.today().addYears(-2), Status = 'Completed');
Task[] tskList = new List<Task>{ tsk1, tsk2, tsk3 };
insert tskList;

Account result = [select Id (SELECT ActivityDate, Subject FROM ActivityHistories) from Account where Id = :acct.Id];
Hello.  I want to put a custom button on a standard detail page layout to execute Apex code, and I'm wondering if using VF page action attribute is a best practice.
 
Here are the details.  When the user clicks the custom button on the detail page, I need to check a couple field values in the record.  If they are valid, I want to insert 8 child records, popup a window saying insert is complete, then return to the original record detail page.  If the field values are not valid, then I want to popup a window saying the child records were not inserted, then return to the original record detail page.
 
So, there's no real user interaction here, just record creation where appropriate and some popup messages.
 
In the past, I have used a VF page with the action attribute to call a method in the VF controller. The constructor is empty and the VF page also has no content.  This worked fine, but I have read some old posts that say using action attribute this way is not best practice.
 
Is this still true?  If so, what's a better approach for this -- webservice methods, or using action function in the VF page?
 
Thanks
David

Hello,

 

I'm writing a small app, that will bulk merge contacts, using partner WSDL.

Here is code that i'm using:

 

private SObject createSObject(String ID,String type)
    {   
        SObject result = new SObject();
        result.setType(type);
        result.setId(ID);
        return result;
    }
    

private void merge(String MasterID,String type, String ChildID)
    {
        connection = Auth.getConnection();
        MergeRequest mReq = new MergeRequest();
        mReq.setMasterRecord(createSObject(MasterID, type));
        mReq.setRecordToMergeIds(new String[] { ChildID });
        MergeRequest[] mergeBatch = new MergeRequest[1];
        mergeBatch[0] = mReq;
        MergeResult[] mRes = connection.merge(mergeBatch)
    }

When i'm trying to merge two contacts, and child has a donation, i get an error:

"Contacts tied to Donations cannot be deleted."

Isn't it suppose to remap donations also? 

 

Thanks

  • November 21, 2011
  • Like
  • 0