• Mats Eriksson
  • NEWBIE
  • 25 Points
  • Member since 2011

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 41
    Replies
I have written a custom mail-to-case class for handling inbound mails to a custom mailaddress. These mails are meant for already existing cases. This class is working very well. However, some people have started using this address for communicating general stuff to us. Not good! At the moment, my class is always returning Success regardless if it fails or not. Any errors are being logged in a separate logging app. result.success = true; return result; That means as many mails fail they create un-necessary entries in my error log app. What is the proper way code wise to gracefully handle these mails? I ONLY want to process mails that have a case reference in the subject and/or body and preferably bounce those that don't. Failing that I'd like to forward these to another mailaddress. Lastly, if that is not possible, I'd like to quietly just drop those mail in the can so to speak. How to achieve this in a mail handler class? /Mats

I need some help with a simple (me thinks) syntax problem.

 

I have a before insert trigger on case that takes a number of custom case fields (from web2case) and creates a person account if the customer doesn't exist in the database.

 

When the person has been created I update the case with the AccountID from the previous stage. Works like a charm.

Now I turn back and requery the Account table based on the AccountId to get at the PersonContactId. (Need to do a requery as this field otherwise is empty).

 

As far as I can see in the debug logs this step is also working as intended but I probably fumble when assigning the query to a map because extracting the values from the map doesn't work.

 

    Map<Id,Account> AccountContactMap= new Map<Id,Account>();
    
    for (Account acc :[Select Id, PersonContactId from Account where Id IN :accIds]){
    	AccountContactMap.put(acc.Id, acc);
    }
    
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && !takenSSNumbers.contains(caseObj.SSNumber__c))
        Account newAcc = AccountContactMap.get(caseObj.AccountId); 
      	caseObj.ContactId = newAcc.PersonContactId;
	}

The code refuses to save on the caseObj.ContactId assignment row with the following error: Save error: Variable does not exist: newAcc.PersonContactId

 

When I inspect the debug log I can see that Id and PersonContactId are assigned:

(201026000)|VARIABLE_ASSIGNMENT|[67]|newAcc|{"PersonContactId":"003D000000q9HfIIAU","Id":"001D000000lvhoxIAA"}|0x6ce315e1

 

Both these AccountId and PersonContactId from the log points to the same Person Account, the newly created one which is what I want. So the data is there, it's just not 'popping out' the way I want....

 

I have tried both to assign the map directly with the select statement and with this latest try, through the map.put() method. No difference.

 

Also, the AccIds list contains one row in my test which it should.

 

What am I doing wrong?

 

/Mats

 

 

 

I have created a before insert trigger on case that will query Account for the existence of a social security number and if there is no match, a person account is created.

 

I then update the case with AccountID and PersonContactID (for ContactID).

 

My problem is that while I can update the case with the AccountID, the PersonContactID is null (also IsPersonAccount is false at this point). When I inspect the new account afterwards, there is a PersonContactID and IsPersonAccount is true.

 

The code compiles fine and executes fine with no errors doing all it should do except setting the ContactId.

 

It seems to me that the person account creation is a two step rocket behind the scene. First the account is created, then an internal trigger fires which creates the "shadow contact" and updates the account with the necessary information like the PersonContactID.

 

Thus my attempt to update the case happens in beteween those two steps. Am I right?

 

What can I do to work around this fact?

 

/Mats

Hi,

 

I have a validation rule on a field in the case object which fires under certain circumstances. The problem is not the formula, it works as expected but the error message is not optimal for end-users:

 

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger ChangeCaseFieldInformationOnFirstSave caused an unexpected exception, contact your administrator: ChangeCaseFieldInformationOnFirstSave: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 5002000000ISzWNAA1; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Please enter a serial numer for the device.: [Serial_Number__c]: Class.ChangeCaseFieldsOnFirstSave.ChangeCaseFields: line 42, column 3

Embedded in the red block is my own error message (in bold). Thats and ONLY that is what I would like to show! Not the other garbage aimed at programmers and not end users.

 

Why is this? Is it because I have a trigger on the case object as well? A trigger that is calling a class to do some housekeeping not related to the validation rule.

 

EDIT: When the case has been created, other validation rules work as expected. It's only the above one that behaves like this.

 

I thought a validation rule would fire before the insert...

 

Any insights?

 

/Mats

I have a trigger that acts On INSERT Case and calls a class. This class in it's simplest form has been working quite well for some months.

 

Now I have expanded the functionality of the class to include some IF and  ELSE IF statements inside a FOR loop. This does not work because seemingly the FOR loop fails to enter. The code compiles nicely with no errors.

 

ccs is the trigger.new object passed into the class.

Debug messages in the first FOR loop confirms that there is case data available. The debug messages in the next FOR loop never executes let alone the IsIC part.

 

I use this methodology in many places and it normally works well (iterating through the trigger object pulling Id's into a list and then a FOR loop with an SOQL statement)

 

public with sharing class ChangeCaseFieldsOnFirstSave {
	public static void ChangeCaseFields(Case[] ccs){

		List<Case> CasesToUpdate = new List<Case>(); 
		List <Id> lstCases= new List<Id>();
		
		for (Case t:ccs){
				lstCases.add(t.Id);
		}
		
		for(Case c:[Select c.id, c.Subject, c.CustomerName__c, c.Status, c.IsSS__c, c.IsIc__c, c.IsKF__c, c.account.IsSS__c, c.account.IsIc__c, c.account.IsKF__c from  Case c where (c.Id in :lstCases)]) {	
			system.debug('#### - Start');
			if (c.account.IsSS__c==true) {
				c.IsSS__c=true;
				CasesToUpdate.add(c);
			}

			else if (c.account.IsIc__c==true){
				system.debug('#### - IsIC');
				c.IsIc__c=true;
				c.Subject=c.CustomerName__c;
				CasesToUpdate.add(c);
			}
			else if (c.account.IsKF__c==true){
				c.IsKF__c=true;
				CasesToUpdate.add(c);
			}
		}
		 update CasesToUpdate;
	}
}

 

 Anyone that could tell me what is wrong?

 

 

/Mats

 

 

 

 

 

I have a VF Page where I use standardController="Case" extensions="ChangeCountryController".

 

The page and associated controller works like a charm in the sandbox. When writing the test class, I run into this error. As far as I understand, I'm using the proper method to initialise the standard controller with my extension but still get this annoying error.

 

I must have missed something fundamental. The complete error message is: Save error: Constructor not defined: [ChangeCountryController].<Constructor>(ApexPages.StandardController)

 

Below are stubs for my test class and extension.

 

//Test Class
@isTest
private class TestChangeCountryController {
  static testMethod void myUnitTest() {
    PageReference pageRef = Page.ChangeCountry;
    Test.setCurrentPage(pageRef);
    
    Case cse=new Case();
    cse.Serial_Number__c='666666666666666';
    cse.Status='New Case';
    insert cse;
        		
    ApexPages.StandardController sc = new ApexPages.StandardController(cse);
    ChangeCountryController controller = new ChangeCountryController (sc);  //<--- Complains here!
		}
}

//Controller extension
public with sharing class ChangeCountryController {
  public ApexPages.StandardController stdCtrl {get; set;}
   
  public ChangeCountryController(ApexPages.standardController std)
 	  {   
 	      Case cc=(Case) stdCtrl.getRecord();
 	  }
 }

 

 

 

Ideas anyone?

 

/Mats

 

I have created a VF Page that uses the case standard controller plus a custom made controller that returns a recordset that I can iterate through and render nicely on the VFP.

 

The page is to be embedded in a Case Page Layout.

 

Now, I want to grab the custom serial number from the case in question and pass it to my controller to be used in the WHERE part of my SOQL query. I figure I should be able to use the <apex:variable> mechanism and pick it up in the controller but I can't save the page because it can't find my custom serial number. Does the VFP live in it's own bubble, blissfully ignorant of the case in context? Or can I somehow traverse the page collection to get to the case page and lift the serial number from it?

 

In the page:

<apex:variable var="srchText" value="{!MySerial_Number__c}"/>

In the Controller:
strSerial = System.currentPageReference().getParameters().get('MySerial_Number__c');

The error comes when trying to save the page. Error message is Error: Unknown property 'CaseStandardController.MySerial_Number__c'

 

What to do?

 

/Mats 

 

I have problems testing my getter/setter. I'm rather new to it and am missing the nuances.

 

I have a class that looks like this:

  

public with sharing class clsCheckDuplicateSerials {
	public string CheckDuplicateSerials{get; set;}
	  String srchText;
	  	  
	  public String getSearchText() {
	    return srchText;
	  }
	  public void setSearchText(String s) {
	    srchText = s;
	  }
}

 The test method looks like this:

@isTest
private class TestDuplicateISerials {
    static testMethod void myUnitTest() {
        String sText ='ABX9043092058';
        CheckDuplicateSerials mm= new CheckDuplicateSerials();
        mm.getSearchText =sText;
        String s = mm.getSearchText ;
        systemAssert(sText,s)
    }
}

 

This doesn't work, I get "Variable does not exist: getSearchText". I have tried different methods of assignment but only the error messages change.

 

It's the test class that fails, the first one doesn't throw any errors.

 

I'm aware of the issue with execution order of the getter and setter but ignoring it for the moment, just want to be able to get the testing going.

 

Any advice?

 

/Mats

Hi,

 

I have created a trigger on case comments that update a field on the parent case. It works very nicely. But when I want to select only cases that are created by SSP Users I have run into problems.

 

I tried getUserType() in the rem:ed line below (I also check for case status there) but it doesn't act differently so I assum both internal and external SSP users are of type 'Standard''
 

 

trigger IsNewCaseComment on CaseComment (after insert) {
Map<Id,CaseComment> cMap = new Map<Id,CaseComment>();
  for (CaseComment t: Trigger.new){
  cMap.put(t.ParentId,t);
}
  List<Case> CasesToUpdate = new List<Case>();
  Set<Id> idSet = cMap.keySet();
  for(Case c:[select Id,CreatedById,Status,IsNewCaseComment__c from Case where Id in :idSet]) {
     {
	//if (C.Status !='Waiting for Documentation' &&  UserInfo.getUserType()!='Standard'){
	c.IsNewCaseComment__c=true;
	CasesToUpdate.add(c);
	//}
}
}
  update CasesToUpdate;
}

 

Any idea on how to proceed?

I have a page that is giving the user the option to add line items to a catalog order. I'm able to display the catalog items, my debug code is showing that the setter is getting the integer entered into the input field, but either no line items get added or all items are added, not just the ones that have a value entered in the field.  I'm not seeing the issue and am hoping that the community sees something I"m missing. 

 

Here is my controller: 

public with sharing class selectableProduct {

    public Material_Order__c record;
    public Integer amount{get; set;}
    public Product_vod__c prod{get;set;}
    public List<Product_vod__c> productList=new List<Product_vod__c>();
    public List<Material_Order_Line_Item__c> linesToAdd=new List<Material_Order_Line_Item__c>();

    //set current material order in focus
    public selectableProduct(ApexPages.StandardController stdController){
        record = [SELECT id, Name, Date__c, Status__c, Notes__c
                    FROM Material_Order__c 
                    WHERE id =:ApexPages.currentPage().getParameters().get('id')];

    }
    
    //get list of available products to order
    public List<Product_vod__c> getProductList(){
        productList = [SELECT id, Name, Image__c FROM Product_vod__c WHERE Product_Type_vod__c = 'Order' ORDER BY Name ASC];
        return productList;
    }
    
    public Integer getAmount(){
        return amount;
      }
   public void setAmount(Integer a){
       this.amount = a;
       }
    
    //set amounts of selected items and insert line items on material order
    public pageReference placeOrder(){
    
        pageReference orderQtys = new PageReference('/'+record.id);
 
        for(Product_vod__c ps : productList){

            Material_Order_Line_Item__c newLine = new Material_Order_Line_Item__c();
          
           if((amount != NULL) || (amount != 0)){
            newLine.Products__c = ps.id;
            newLine.Quantity__c = amount;
            newLine.Material_Order__c = record.id;

            linesToAdd.add(newLine);
            }
        }
        insert linesToAdd;
        return orderQtys;
    }
    
}

 

And here is the VF Code: 

<apex:page standardController="Material_Order__c" extensions="selectableProduct">
<apex:form >
<apex:pageBlock title="Products">
  <apex:pageBlockButtons >
    <apex:commandButton action="{!placeOrder}" value="Submit"/>
  </apex:pageBlockButtons>
<apex:pageBlockSection title="Available Line Items" columns="1">
  <apex:dataTable value="{!productList}"  var="prod" width="95%" cellpadding="5">
    <apex:column width="10%" headerValue="Amount">
      <apex:facet name="header"/>
      <apex:inputText value="{!amount}"/>
    </apex:column>
    <apex:column width="20%">
      <apex:facet name="header">Product</apex:facet>
      <apex:outputText value="{!prod.Name}"/>
    </apex:column>
    <apex:column width="70%">
      <apex:facet name="header">Image</apex:facet>
      <apex:outputField value="{!prod.Image__c}"/>
    </apex:column>
  </apex:dataTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

Thanks for your help in advance!

JoAnn

Hi Everyone,

when I try to install Eclipse Juno 4.2 with the force.com IDE I get the following error message:

 

Cannot complete the install because one or more required items could not be found.
  Software being installed: Force.com IDE 25.0.0.201206181021 (com.salesforce.ide.feature.feature.group 25.0.0.201206181021)
  Missing requirement: Force.com IDE 25.0.0.201206181021 (com.salesforce.ide.feature.feature.group 25.0.0.201206181021) requires 'org.eclipse.update.ui 0.0.0' but it could not be found

 Does anyone know how to fix this?

 

Kind regards,

 

Otto

  • July 02, 2012
  • Like
  • 0

I have integrated the web to lead form in our organisation's Joomla website, but having a few issues with the form online and hope someone can advise :) 

 

  1. I can’t change the formatting without losing the integration through to – i.e. can’t add spaces between the category title and the answer box – it’s pretty ugly at the moment. 

  2. The multi-select boxes only show one option at a time when live in the website only a single line is visible as where it should show 4/5 options as it does in the article view on the administration side

    see both above issues at http://euclidnetwork.eu/membership/join-euclid-network-here.html
     
  3. Also I need to add in some code for the spam protection – as not sure where to start - does it matter if in javascript or php?

thanks to anyone that can help!

  • March 01, 2012
  • Like
  • 0

I need some help with a simple (me thinks) syntax problem.

 

I have a before insert trigger on case that takes a number of custom case fields (from web2case) and creates a person account if the customer doesn't exist in the database.

 

When the person has been created I update the case with the AccountID from the previous stage. Works like a charm.

Now I turn back and requery the Account table based on the AccountId to get at the PersonContactId. (Need to do a requery as this field otherwise is empty).

 

As far as I can see in the debug logs this step is also working as intended but I probably fumble when assigning the query to a map because extracting the values from the map doesn't work.

 

    Map<Id,Account> AccountContactMap= new Map<Id,Account>();
    
    for (Account acc :[Select Id, PersonContactId from Account where Id IN :accIds]){
    	AccountContactMap.put(acc.Id, acc);
    }
    
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && !takenSSNumbers.contains(caseObj.SSNumber__c))
        Account newAcc = AccountContactMap.get(caseObj.AccountId); 
      	caseObj.ContactId = newAcc.PersonContactId;
	}

The code refuses to save on the caseObj.ContactId assignment row with the following error: Save error: Variable does not exist: newAcc.PersonContactId

 

When I inspect the debug log I can see that Id and PersonContactId are assigned:

(201026000)|VARIABLE_ASSIGNMENT|[67]|newAcc|{"PersonContactId":"003D000000q9HfIIAU","Id":"001D000000lvhoxIAA"}|0x6ce315e1

 

Both these AccountId and PersonContactId from the log points to the same Person Account, the newly created one which is what I want. So the data is there, it's just not 'popping out' the way I want....

 

I have tried both to assign the map directly with the select statement and with this latest try, through the map.put() method. No difference.

 

Also, the AccIds list contains one row in my test which it should.

 

What am I doing wrong?

 

/Mats

 

 

 

I have created a before insert trigger on case that will query Account for the existence of a social security number and if there is no match, a person account is created.

 

I then update the case with AccountID and PersonContactID (for ContactID).

 

My problem is that while I can update the case with the AccountID, the PersonContactID is null (also IsPersonAccount is false at this point). When I inspect the new account afterwards, there is a PersonContactID and IsPersonAccount is true.

 

The code compiles fine and executes fine with no errors doing all it should do except setting the ContactId.

 

It seems to me that the person account creation is a two step rocket behind the scene. First the account is created, then an internal trigger fires which creates the "shadow contact" and updates the account with the necessary information like the PersonContactID.

 

Thus my attempt to update the case happens in beteween those two steps. Am I right?

 

What can I do to work around this fact?

 

/Mats

How to avoide the error in the following code................actually when i am testing this webservice with xmlspy it is giving the error

 

global class InboundLinxUserRegistration {
     global class dtRegistrationInput {
       webservice ID UserId;
       webservice String First_Name;
       webservice String Last_Name;
       webservice String Email_Address;
       webservice String Status;
       webservice ID Workplace_Id;
       webservice String Workplace_Name;
       webservice String Workplace_Province;
       webservice String Workplace_City;
       webservice String Workplace_Postal_Code;
       webservice String Workplace_Address;
       webservice String Speciality;
       webservice String Record_Type;
      }
     global class dtRegistrationOutput {
       webservice date mydate;
       webservice String added;
       webservice String status;
       webservice String Message_Text;
       webservice String error;
      
      }
     
      public webservice static dtRegistrationOutput userregistration(dtRegistrationInput userregistration){
           dtRegistrationOutput retvalue=new dtRegistrationOutput();
           for(List<Account> account :[select National_Code__c,PersonEmail from Account]){
              for(Account acc : account) {
                 if((acc.National_Code__c==userregistration.UserId)||(acc.PersonEmail==userregistration.Email_Address)){
                         retvalue.status='Failure';
                         retvalue.error='Duplicate';
                    }else {    
                     account[0].National_Code__c=userregistration.UserId;
                     account[0].FirstName=userregistration.First_Name;
                     account[0].LastName=userregistration.Last_Name;
                     account[0].PersonEmail=userregistration.Email_Address;
                     account[0].Account_Status_NES__c=userregistration.Status;
                     account[0].Primary_Parent_vod__c=userregistration.Workplace_Id;
                     account[0].Primary_Province_NES__c=userregistration.Workplace_Province;
                     account[0].Primary_City_NES__c=userregistration.Workplace_City;
                     account[0].Primary_Postal_Code_NES__c=userregistration.Workplace_Postal_Code;
                     account[0].Primary_Address_1_NES__c=userregistration.Workplace_Address;
                     account[0].Specialty_1_vod__c=userregistration.Speciality;
                     account[0].RecordTypeId=userregistration.Record_Type;
                     try{
                         insert acc;
                         retvalue.added='True';
                         retvalue.Message_Text='Registration Successfull';
                        } /*catch(DMLException e) {
                             retvalue.mydate=system.today();
                             retvalue.added='false';
                             retvalue.Message_Text=e.getMessage();
                        }*/
                        catch (Exception e){
                          retvalue.mydate=system.today();
                          retvalue.added='false';
                          retvalue.Message_Text=e.getMessage();
                         }
                    
                 }
              }
             return retvalue;
           }
            
                                 
          return retvalue;
       }
  }

I have a trigger that acts On INSERT Case and calls a class. This class in it's simplest form has been working quite well for some months.

 

Now I have expanded the functionality of the class to include some IF and  ELSE IF statements inside a FOR loop. This does not work because seemingly the FOR loop fails to enter. The code compiles nicely with no errors.

 

ccs is the trigger.new object passed into the class.

Debug messages in the first FOR loop confirms that there is case data available. The debug messages in the next FOR loop never executes let alone the IsIC part.

 

I use this methodology in many places and it normally works well (iterating through the trigger object pulling Id's into a list and then a FOR loop with an SOQL statement)

 

public with sharing class ChangeCaseFieldsOnFirstSave {
	public static void ChangeCaseFields(Case[] ccs){

		List<Case> CasesToUpdate = new List<Case>(); 
		List <Id> lstCases= new List<Id>();
		
		for (Case t:ccs){
				lstCases.add(t.Id);
		}
		
		for(Case c:[Select c.id, c.Subject, c.CustomerName__c, c.Status, c.IsSS__c, c.IsIc__c, c.IsKF__c, c.account.IsSS__c, c.account.IsIc__c, c.account.IsKF__c from  Case c where (c.Id in :lstCases)]) {	
			system.debug('#### - Start');
			if (c.account.IsSS__c==true) {
				c.IsSS__c=true;
				CasesToUpdate.add(c);
			}

			else if (c.account.IsIc__c==true){
				system.debug('#### - IsIC');
				c.IsIc__c=true;
				c.Subject=c.CustomerName__c;
				CasesToUpdate.add(c);
			}
			else if (c.account.IsKF__c==true){
				c.IsKF__c=true;
				CasesToUpdate.add(c);
			}
		}
		 update CasesToUpdate;
	}
}

 

 Anyone that could tell me what is wrong?

 

 

/Mats

 

 

 

 

 

I have a VF Page where I use standardController="Case" extensions="ChangeCountryController".

 

The page and associated controller works like a charm in the sandbox. When writing the test class, I run into this error. As far as I understand, I'm using the proper method to initialise the standard controller with my extension but still get this annoying error.

 

I must have missed something fundamental. The complete error message is: Save error: Constructor not defined: [ChangeCountryController].<Constructor>(ApexPages.StandardController)

 

Below are stubs for my test class and extension.

 

//Test Class
@isTest
private class TestChangeCountryController {
  static testMethod void myUnitTest() {
    PageReference pageRef = Page.ChangeCountry;
    Test.setCurrentPage(pageRef);
    
    Case cse=new Case();
    cse.Serial_Number__c='666666666666666';
    cse.Status='New Case';
    insert cse;
        		
    ApexPages.StandardController sc = new ApexPages.StandardController(cse);
    ChangeCountryController controller = new ChangeCountryController (sc);  //<--- Complains here!
		}
}

//Controller extension
public with sharing class ChangeCountryController {
  public ApexPages.StandardController stdCtrl {get; set;}
   
  public ChangeCountryController(ApexPages.standardController std)
 	  {   
 	      Case cc=(Case) stdCtrl.getRecord();
 	  }
 }

 

 

 

Ideas anyone?

 

/Mats

 

Anyone else seeing this?

 

Occurs on "Edit" of Account that has the Edit button overridden to bring up an AccountEditVFPage.

 

Debug logs shows no error!

 

Ideas?

  • February 09, 2011
  • Like
  • 0

The trigger below runs through a set of logic looking for matching Contacts/Person Accounts based on email address and creating Accounts/Contacts and Person Accounts where they don't already exist.

 

Everything is working fine except for the bit that is highlighted.

It is supposed to create a new Person Account and then update a lookup with the new Person Account ID.

The Person Account record is being created just fine, but the lookup is not being populated like it is with the rest of the trigger.

If a second record is created with a matching email address, the lookup is populated on the second record as it should.

 

Any idea what I am doing wrong??

 

Thanks is advance for any help.

 

 

trigger enquiryTrigger on Enquiry__c (before insert) {

// Get the email address from the enquiry record
   List<Enquiry__c> enqEmail = [select email__c from Enquiry__c where ID in :Trigger.new];
 
   for(Enquiry__c e: Trigger.new){

// Get the contact with matching email address   	
      List<Contact> conID = [select Name from Contact where Email = :e.email__c limit 1];

// If matching contact is found update Enquiry record      
      if (conID.size() > 0) {
      	e.Matching_Contact__c = conID[0].Id;

      } 

//If no matching contact is found and enquiry DOES NOT contain a Company, create a Person Account

else if (e.company__c == null) {

		Account pa = new Account (RecordTypeId = '01220000000DpJM', LastName = e.Name, PersonEmail = e.Email__c, Phone = e.Phone__c);
		insert pa;
		
		// Update Enquiry with new Person Account      		
		e.Matching_Contact__c = pa.PersonContactId;
      	
       } else {

		// If Enquiry does contain a Company check for matching Account record       	
		       	List<Account> accName = [select Id from Account where Name = :e.Company__c limit 1];
		      
		      	if (accName.size() > 0) {
		
				// If matching Account record is found, create a contact on the existing Account
				      		Contact c = new Contact (LastName = e.Name, Phone = e.Phone__c, Email = e.email__c, AccountId = accName[0].Id);
					       	insert c;
				
				// Update Enquiry with new Contact	       	
					       	e.Matching_Contact__c = c.Id;
	       	
		      	} else {
		      		
				// If no matching Account is found, create an Account        		
					       	Account a = new Account (Name=e.Company__c);
					       	insert a;
					       	
				// Create a related Contact	       	
					       	Contact c = new Contact (LastName = e.Name, Phone = e.Phone__c, Email = e.email__c, AccountId = a.Id);
					       	insert c;
					       	
				// Update Enquiry record with new Contact	       	
					       	e.Matching_Contact__c = c.Id;
	       	
			}
		}
	}
}

 

 

 

Hello,

 

I'd like to create a new Person Account via API.  I have Person Account enabled.  Ideally, I want to create a Person Account in one shot, but I don't think it's possible?  I need to create an Account and 1 associated Contact and then convert the account to a Person Account type?  

 

 

void testCreateAndDestroyStudentAccount() { def first = "APIFirst" def last = "APILast" // create new, non-person Account first Account acct = new Account() acct.name = "${last}" def organizationaccount = getRecordTypes().find { it.name =='Educational Organization' } acct.recordTypeId = organizationaccount.id acct.ownerId = salesforce_owner_id acct.gender__pc = '' acct.languages__pc = '' acct.firstName = '' acct.lastName = '' acct.salutation = '' acct.level__pc = '' SaveResult[] result = salesForceService.createObjects(acct) result.each { it.errors.each { com.sforce.soap.partner.Error er -> println "ERROR: ${er.getMessage()}" } assertTrue("should have created account", it.success) println "Account ID: ${it.id}" acct.id = it.id } println "creating contact..." Contact contact = new Contact() contact.setFirstName(first) contact.setLastName(last) contact.accountId = acct.id contact.recordTypeId = '' contact.ownerId = salesforce_owner_id result = salesForceService.createObjects(contact) result.each { it.errors.each { com.sforce.soap.partner.Error er -> println "Create contact ERROR: ${er.getMessage()}" } assertTrue("should have created contact", it.success) println "CONTACT ID: ${it.id}" contact.id = it.id } def studentaccount = getRecordTypes().find { it.name =='Student Account' } acct.recordTypeId = studentaccount.id result = salesForceService.updateObjects(acct) result.each { it.errors.each { com.sforce.soap.partner.Error er -> println "Update Account ERROR: ${er.getMessage()}" } fail("should have converted to Person Account") } }

 

Code creates an Account and Contact fine, but fails at the update when attempting to convert to a Person Account (at the end) with message:

 

Cannot specify any additional fields when marrying or separating a Person-Account

 

 

 

Ideas?  Thoughts? Suggestions?

 

I appreciate any insight

 

Todd

The application requirement is to send a list of things to a subscriber, that the subscriber has not already received. (The subscriber cannot receive the same thing twice.) A list of things sent is stored in a transaction table, and a list of things that can be sent is stored in a thing table. In regular SQL, this is a simple query:

 

 

SELECT thingId FROM available_things WHERE thingId NOT IN (SELECT thingId FROM transactions WHERE subscriberId = 'XXX')

This is not possible in SOQL. Apprently, however, we can do something similar:

// An IN-bind with an Id list. Note that a list of sObjects // can also be used--the Ids of the objects are used for // the bind Contact[] cc = [select id from contact limit 2]; Task[] tt = [select id from task where whoId in :cc];

(Taken from the Apex Language Reference here.)

 

Unfortunately, it appears that lists, maps, and sets are all limited to 1000 items. (Contact[] is shorthand for List<Contact>.)

 

Since any of my subscribers may have tens of thousands of things sent to them, I cannot do this:

 

Transaction__c[] thingsSent = [select thingId from transaction__c where subscriber__c = :subscriberId]; Thing__c[] things = [select thingId from thing__c where thingId not in :thingsSent];

 

 

I can set an arbitrary upper limit on the number of thiings to send at 1000, but I cannot set any such limit on the number of things that have already been sent.

 

Can this be done in SOQL?

 

TIA,

 

John

  • May 01, 2009
  • Like
  • 0