• Rajesh Shah
  • SMARTIE
  • 645 Points
  • Member since 2008

  • Chatter
    Feed
  • 24
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 43
    Questions
  • 249
    Replies

I'm trying to create a trigger that will fire when an opportunity is updated with a checkbox "create_hybrid__c" checked.  The trigger should create a new account record and then update a field on the opportunity with the new account.

 

I can get the trigger to create the new account, but any criteria that references the opportunity is ignored.  I've highlighted those lines in red below.  Also, I specifically assign a record type in the trigger, but the account is created with a completely different record type.  I also tried to assign a parent account and that criteria was ignored.

 

Is there any way to modify the trigger below so that all the fields I've specified are populated correctly?  With this trigger, an account is created, the name, agency_id__c, cmr_numer__c, and assign_rpm_client__c are populated correctly, the record type is not correct, and the other fields I specified are just left blank.

 

trigger CreateHybridAcct on Opportunity (before update) {

 

List<Account> a = new List<Account>();

 

for (Opportunity p : Trigger.new){
    if (p.create_hybrid__c == True) {
   
    a.add (new Account(
            name = 'testtrigger',
            agency_id__c = '300',
            cmr_number__c = '997',
            client_name__c = p.account.name,
            hybrid_account__c = p.account.id,
            owner = p.owner,
            recordtypeid = '01270000000UHZcAAO',
            parentid = '0017000000PgOvrAAF',
            assign_rpm_client__c = TRUE
            ));
           
    insert a;
   
    //p.hybrid_account__c = h.id;
    p.create_hybrid__c = false;     
            
    }

}
}

Hello everyone i have a strange problem.

 

i have created one visual force page which stores the current session id in my  custom object's key field.

for retrieving the session id, i have created apex class which contains the webservice static method. which returns the session id of current session.

 

url of my current page is like this = https://c.cs4.visual.force.com/apex/Test

 

name of apex class is "mysession" and name of the webservice static method getSessionId and i am getting session id by usiing

 

String SessionID = mysession.getSessionId();

 

and i am getting SessionID = 00DP000000065Qa!AQEAQJoFPAmHIV4KrqzWQMhTeEcTVjFyxiv3S_YREhq6KU1yo5We5HM_tOZ4iUZlZfP04HmtPkohcNLG0AAzbDNAmzTbSCVg

i am storing this session =id in my custom object as key for the further retrieval of the record in my second page.

 

i am showing some data of  that object in my  Test page.

 

i have made one pageblock table. in which one colum contains hyperlinks. when  i click on that hyperlink it directly redirects me to object record in new tab of my browser. 

 

but then my url is getting changed from visual.force.com to salesforce.com. in that page i have added custom button "check" in my custom objects's page layout.

by clicking on that button i am retrieving the session id from my common apex class .

i have written the code of that button as onclick javascript event.

 

now url of page which is opened in new tab is like this:https://cs4.salesforce.com/a1DP0000001xhujMAA

 

this url refers to the record of my custom object's record.

 

now in that javascript  i am using

var sessionID = sforce.apex.execute("mysession","getSessionId",{}); for getting a sessionid from common apex class

 

and i am getting sessionID  like: 00DP000000065Qa!AQEAQBflbKcSP8DmYD0X2gpaBpiFlohTNL0jE9wcgoKnF44a05N.lUCJNryVF2eajb0sy9YRXHx2C07KzZrhrw0SciklDsct

 

now see both the session ids are different.

but why? that i dont know.

 

my quesion is "how can i have both the sessionids with same value ? ";

 

what can i do for this kind of problem?

 

i want both the sessionids with same value because i want to perform some action on the record of my custom object.

because i have stored that sessionid as key filed in my custom object.

 

any kind of help will be  greatly appriciated.

Thanks in advance.

Learn And Contribute.

 

 

 

Hi, 

I have a commandLink on click of which I want to ask the user for confirmation first i.e. whether he is sure to take the action. Once the user says Yes and the action is completed, I want a alert saying that the action was completed successfully. In order to achieve this, I used the onclick and oncomplete attributes of CommandLink. My issue is that if I use both the attributes, my commandLink action never gets fired. If I use only one of the them, everything works fine except I have only one of the popups. 


Is there an issue when both the onclick and oncomplete attribute are used together? Following is a sample code:

 

<apex:commandLink value="Test" action="{!myAction}" onclick="return window.confirm('Are you sure?');" oncomplete="alert('Event Completed');" />

 

 

 

We are getting the following error when viewing a custom VF page. We have NO validation on the page or the object.
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Subject: data value too large: Call Logged with Overlin Zamora RE: Pittsburg High School Reconstruction/Modernization (max length=80)". 
Here is my Apex code for that page 
SObject[] ClosedTasks = [SELECT (SELECT Id, WhatId, WhoId, LastModifiedDate, Subject, Who.Name, ActivityDate, Status, Priority, Owner.Name, Description, IsTask 
FROM ActivityHistories ORDER BY ActivityDate DESC, LastModifiedDate DESC LIMIT 500) 
FROM Opportunity WHERE Id = :o.Id];

myClosedTasks = (List<ActivityHistory>)ClosedTasks.get(0).getSObjects('ActivityHistories');

 

And here is the VF page.

 

 

<apex:page standardController="Opportunity" extensions="trac_Activity_History">

	<apex:form >
	<apex:pageBlock >
	<apex:pageBlockSection collapsible="false" title="Activity History" columns="1">
	
		<apex:pageBlockTable value="{!myClosedTasks}" var="t">
		
                    <apex:column headerValue="Action" width="75px" rendered="{!if(t.IsTask,'true','false')}">                    
                       <a href="{!URLFOR($Action.Task.Edit, t.Id,[retURL=URLFOR('/apex/ActivityHistory?Id='+ t.WhatId)])}" target="_top">Edit</a>
                    </apex:column>
                    <apex:column headerValue="Action" width="75px" rendered="{!if(t.IsTask,'false','true')}">                    
                       <a href="{!URLFOR($Action.Event.Edit, t.Id,[retURL=URLFOR('/apex/ActivityHistory?Id='+ t.WhatId)])}" target="_top">Edit</a>
                    </apex:column>
                    <apex:column value="{!t.IsTask}"/>
                    <apex:column headerValue="Name">
                        <apex:outputLink target="_top" value="/{!t.WhoId}">{!t.Who.Name}</apex:outputLink>
                    </apex:column>
                    <apex:column value="{!t.ActivityDate}"/>
                    <apex:column headervalue="Assigned To">
                        <apex:outputLink target="_top" value="/{!t.OwnerId}">{!t.Owner.Name}</apex:outputLink>
                    </apex:column>
                    <apex:column value="{!t.Status}"/>
                    <apex:column headerValue="Subject" value="{!t.Subject}" />
                    <apex:column headerValue="Comments">
                    	<apex:outputText >{!t.Description}</apex:outputText>
                    </apex:column>                    
		
		</apex:pageBlockTable>
	
	</apex:pageBlockSection>
	</apex:pageBlock>
	</apex:form>
	
</apex:page>

 

Why would this error occur? Seems odd.

 

 

 

Hi,

having a little trouble getting test coverage on a batch class, odly the test passes like everything was executed, but the execute method isn't covered. Been scratching my head on this one for a while.

 

The class itself is fairly simple, and according to the test, its doing what its suposed to be. Running it in executeanon works as expected as well.

 

Class:

 

 line source
 1  global class updateContactBatch implements Database.Batchable<sObject>
 2  {
 3  
 4   String Query;
 5   List<Contact> uC = new List<Contact>();
 6   List<Master_Tracker__c> uM = new List<Master_Tracker__c>();
 7  
 8   global Database.QueryLocator start(Database.BatchableContext BC)
 9   {
 10   return Database.getQueryLocator(query);
 11   }
 12  
 13   global void execute(Database.BatchableContext BC, List<sObject> scope)
 14   {
 15   for(sObject s : scope)
 16   {
 17   Master_Tracker__c m = (Master_Tracker__c)s;
 18   Contact c = new Contact(Id = m.Contact__c, Send_ExactTarget_Email__c = m.Contact_Exact_Target_Send__c);
 19   m.ContactUpdate__c = false;
 20   uM.add(m);
 21   uC.add(c);
 22   }
 23   update uC;
 24   update uM;
 25   }
 26  
 27   global void finish(Database.BatchableContext BC)
 28   {
 29   System.debug('Finish');
 30   }
 31  
 32   public static testMethod void testBatch()
 33   {
 34  
 35  
 36   List<Contact> cTest = [Select Id from Contact limit 10];
 37   List<Account> aTest = [Select Id from Account limit 1];
 38   List<Master_Tracker__c> mU = new List<Master_Tracker__c>();
 39   for(integer i = 0; i<10; i++)
 40   {
 41   Master_Tracker__c m = new Master_Tracker__c(School_Studies__c = 'testing', Contact__c = cTest[i].Id, BID__c = 'test' + i, Account_Name__c = aTest[0].Id, Offer_Id__c = 'test2' + i, Initiated_Date__c = Date.today());
 42   mU.add(m);
 43   }
 44   insert mU;
 45   Test.StartTest();
 46   updateContactBatch upCon = new updateContactBatch();
 47   List<Master_Tracker__c> testing = [SELECT m.Id, m.Contact__c, m.Contact_Exact_Target_Send__c FROM Master_Tracker__c m WHERE m.ContactUpdate__c = true];
 48   System.debug('the number of returned records are ' + testing.size());
 49   upCon.query = 'SELECT m.Id, m.Contact__c, m.Contact_Exact_Target_Send__c FROM Master_Tracker__c m WHERE m.ContactUpdate__c = true';
 50   Id batchProcessId = Database.executeBatch(upCon);
 51  
 52   Test.StopTest();
 53  
 54   AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id = :batchProcessId];
 55   System.debug('\n\nFinal results are: '+a);
 56   System.AssertEquals('Completed', a.status);
 57   System.AssertEquals(0, a.NumberOfErrors);
 58  
 59   List<Master_Tracker__c> m2 = [SELECT Id FROM Master_Tracker__c WHERE School_Studies__c = 'testing' and ContactUpdate__c = false];
 60   System.AssertEquals(m2.Size(), 10);
 61   }
 62  
 63  }

 

Here are the results of the Async job:

 

Final results are: AsyncApexJob:{Status=Completed, NumberOfErrors=0, CreatedById=005A0000000S87QIAS, Id=707T0000000EXg3IAG, TotalJobItems=1, JobItemsProcessed=1}

 

The job was submitted and completed, which should mean the code is covered, or at the least, part of it. Any help or places to look would be much apreciated.

 

I am trying to create a trigger that updates a field in the detail of a master detail relationship.

 

For example...

 

I have a custom object called Risk and I have a junction object called Risk Relationship.

 

Risk Relationship is connected to Risk by a Master Detail relationship and a lookup relationship as well.

 

Risk Relationship is the detail in both relationships.

 

Is it possible to create a trigger so that whenever a Risk is edited, a trigger is fired to create a field update in the Risk Relationship custom object?

 

Is that possible?

Hi All,

 

I am displaying History Related lists in Visualforce using the below code:

 

 

<apex:dataTable value="{!Object.histories}" var="history" rowClasses="odd,even" cellspacing="15" width="100%">
            <apex:column >
                <apex:facet name="header"></apex:facet>
                <apex:facet name="footer"></apex:facet>
                <apex:outputText value="{0,date,MM/dd/yyyy HH:mm }">
                <apex:param value="{!history.createddate}" />
                </apex:outputText>
            </apex:column>
            <apex:column >
                <apex:facet name="header">Field</apex:facet>
                <apex:facet name="footer"></apex:facet>
                <b> <apex:outputText value="{!history.field}"/></b>
                </apex:column>
            <apex:column >
                <apex:facet name="header">Editied By</apex:facet>
                <apex:facet name="footer"></apex:facet>
                <apex:outputText value="{!history.createdby.name}"/>
            </apex:column>
            <apex:column >
                <apex:facet name="header">Old Value</apex:facet>
                <apex:facet name="footer"></apex:facet>
                <apex:outputText value="{!history.oldvalue}"/>
            </apex:column>
            <apex:column >
                <apex:facet name="header">New Value</apex:facet>
                <apex:facet name="footer"></apex:facet>
                <apex:outputText value="{!history.newvalue}"/>
            </apex:column>
        </apex:datatable>

 

 

The history table is appearing in the ascending order(ie, "Created" is coming first, followed by the other field trackings).

 

But I need to display descendingly (by Created Date).

 

Any Suggestions?

 

Thanks

Bhuvana

Has anyone figured out how to get around the JSONObject "Too many script statements" error?

 

Also, now with the REST API being GA in Spring '11, when are we getting native JSON processing support?


Thanks,

Jon

Hi All,

 

I am updating the same object using "after update" and it's throwing an error which to me seems impossible as I am using trigger.new and not trigger.old

 

Error:Apex trigger AccountTrigger caused an unexpected exception, contact your administrator: AccountTrigger: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.AccountTrigger: line 7, column 3

 

So I decided to perform a simple test in a clean dev org using the following:

 

 

trigger AccountTrigger on Account (after update) {
	
	List<Account> acc=new List<Account>();

	for (Account a: Trigger.new){

		a.Description = 'Test';
		acc.add(a);

 	}

	update acc;


}

 

 

This should work or am I being stupid?

 

Thx

I am not sure what the subject should be, But here is what i want to do..

 

i am generating data for my flot graph  from my controller.

I have 2 <apex:selectList> in the VF page which captures project name and milestone. I need to pass these values into my controller method and that method returns a string value which would be used to build the graph. This graph needs to be generated on click of a button.

 

I have a html button on click of which the graph is generated.

How do i send the values of the selectlist into controller method?

Can i call the controller method from onclick of button and then run the rest of the javascript code to generate the graph?

 

Thanks

Prady

 

 

Hi All,

 

I am using the below code to display History related lists in visualforce.

<apex:dataTable value="{!Object.histories}" var="history" rowClasses="odd,even" cellspacing="15" width="100%">
<apex:column >
<apex:facet name="header"></apex:facet>
<apex:facet name="footer"></apex:facet>
<apex:outputText value="{0,date,MM/dd/yyyy HH:mm }">
<apex:param value="{!history.createddate}" />
</apex:outputText>
</apex:column>
<apex:column >
<apex:facet name="header">Field</apex:facet>
<apex:facet name="footer"></apex:facet>
<b> <apex:outputText value="{!history.field}"/></b>
</apex:column>
<apex:column >
<apex:facet name="header">Editied By</apex:facet>
<apex:facet name="footer"></apex:facet>
<apex:outputText value="{!history.createdby.name}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Old Value</apex:facet>
<apex:facet name="footer"></apex:facet>
<apex:outputText value="{!history.oldvalue}"/>
</apex:column>
<apex:column >
<apex:facet name="header">New Value</apex:facet>
<apex:facet name="footer"></apex:facet>
<apex:outputText value="{!history.newvalue}"/>
</apex:column>
</apex:datatable>

But in "Field" column, its displaying API name of the field. Is there a way to display field label instead of API Name?

 

Or can u suggest any other way to display History related lists with standard controller(without Apex).

 

Thanks

Sureka

 

 

Hi, I need help in developing a custom formula field that calculates the Age from a given date, in terms of years and months, like this:

 

MyDate: 18/05/1990  (dd/mm/yyyy)

 

Calculated Age: 19 year(s), 11 month(s)

 

I have tried several formulas, but I only could get the year and I got problems with the months calculation.

 

Could someone help with this?

 

Regards,

 

Wilmer

How do you navigate to a specific top-level (standard object or custom object) tab from Apex? Not to a specific instance of an SObject, but to the top-level tab/list.

 

Thanks!


Dave

 

I recently tried to package an app with custom settings. Unfortunately I couldn't write test methods because I wanted to create custom settings instances to test the various areas of my code. The error message I got is well known to me: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa).

 

Since inserting a Custom Settings object is a setup operation I can not create a custom settings and then proceed to create my test data. I tried creating my custom settings inside an @future method and this didn't work either (I did wrap my @future call with Test.startTest() and Test.stopTest() to ensure my @future method completed (i.e. to force synchornous execution). But I still got the same error message.

 

Ultimately what I did was write my code in such a way that the Class which relied on the custom settings had a local variable for the custom settings which I could set. In normal operation my code will query the custom settings using .getInstance() however my testMethods will all override this normal behavior and "force" set the custom settings.

 

My class which uses custom settings is below as is my class which tests my code. I hope you find this useful, and if you spot anything wrong with this please let me know. Thanks,

Caleb

 

------------ Class --------------

 public without sharing class CrossObjectUtil {
 private Map<Id,gii__AccountAdd__c> childrenToUpdateParent;
 private List<Account> parentsToUpdate;
 private Boolean isTest = false;

//This is the key!
 private CrossObjectSettings__c crossObjSettingsInstance = null;
 
 public CrossObjectUtil() {
  childrenToUpdateParent = new Map<Id,gii__AccountAdd__c>();
  parentsToUpdate = new List<Account>();
  setCrossObjectSettings(null);
 }

//Used by the test methods!

 public void setCrossObjectSettings(CrossObjectSettings__c cos) {
  if(cos == null) {
   CrossObjectSettings__c crossObjSettingsInstance = null;
   Map<String,CrossObjectSettings__c> crossObjSettingsInstanceMap = CrossObjectSettings__c.getAll();
   
   for(CrossObjectSettings__c cosInstance : crossObjSettingsInstanceMap.values()) {
    if(cosInstance.Child_Object_Name__c == 'gii__AccountAdd__c'&&
       cosInstance.Parent_Object_Name__c == 'Account') {
        crossObjSettingsInstance = cosInstance;
       }     
   }
  } else {
   crossObjSettingsInstance = cos;
  }
 }
 
 public void addChildToUpdateParent(Id parentId, gii__AccountAdd__c child) {
  childrenToUpdateParent.put(parentId,child);
 }

 public void updateParents() {
  if (childrenToUpdateParent.size() > 0) {
   updateParents(childrenToUpdateParent,false);
  }
 
  update parentsToUpdate;
 }
 
 private void updateParents(Map<Id,gii__AccountAdd__c> children,Boolean isDelete) {
  System.debug('updateParents: isDelete = ' + isDelete);
  for(Id parentId : children.keySet()) {
    SObject parent = new Account(Id=parentId);
    SObject child = children.get(parentId);
        
    if(crossObjSettingsInstance == null) {
     setCrossObjectSettings(null);
     if(crossObjSettingsInstance == null) {
      return;
     }
    }
    
    List<String> fieldMappings = crossObjSettingsInstance.Child_to_Parent_Field_Mapping__c.split(';',0);
    
    if(fieldMappings.size() == 0) return;
    
    for(String mapping : fieldMappings) {
     List<String> fields = mapping.split('=',0);
     if(fields.size() == 2) {
      if(!isDelete) {
       parent.put(fields[1],child.get(fields[0]));
      } else {
       parent.put(fields[1],null);
      }
     }
    }
    parentsToUpdate.add((Account)parent);
   } 
 }
}

 

-----------Test Method -------------

    static testMethod void test_CrossObjectUtil_Self() {
     Account a = insertAccount();
     gii__Warehouse__c w = insertWharehouse();
     gii__AccountAdd__c acctAdd = getAccountAdd(a,w);
    
      CrossObjectUtil coUtil = new CrossObjectUtil();

//Set the custom settings - the object is never saved!
      coUtil.setCrossObjectSettings(createCustomSettings());
        coUtil.addChildToUpdateParent(a.Id,acctAdd);
        coUtil.updateParents();
        Account assertAccount = [SELECT Name, Description FROM Account WHERE Id =:a.Id LIMIT 1];
        System.assertEquals(w.Id,assertAccount.Name);
        System.assertEquals(acctAdd.Name,assertAccount.Description);
    }
      
 //Notice that I do NOT insert the object! it's all in memory!
    static CrossObjectSettings__c createCustomSettings() {
     CrossObjectSettings__c crossObjSettingsInstance = new CrossObjectSettings__c(Name = 'Test Account Add to Account');
     crossObjSettingsInstance.Child_Object_Name__c = 'gii__AccountAdd__c';
     crossObjSettingsInstance.Parent_Object_Name__c = 'Account';
     crossObjSettingsInstance.Child_to_Parent_Field_Mapping__c = 'Name=Description;gii__DefaultWarehouse__c=Name';
     return crossObjSettingsInstance;
    }

When developing a Visualforce page for overiding view page for any object, one problem that creeps up is to display the History details of a record. The standard related list Component doesn't works for History.

 

With the help of some code from Community ( I now can't find the link to it :( ), I wrote my own code  then to display the history of an object. It mimics the standard list as far as possible.  

 

Heres the code. It is for the Case object but it can be used for any other object.

 1.Component Code

 

<apex:component controller="CaseHistoriesComponentController">
<!-- Attribute Definition -->
<apex:attribute name="CaseId" description="Salesforce Id of the Case whose Case History needs to be rendered" type="Id" required="true" assignTo="{!caseId}" />

<!-- Case History Related List -->
<apex:pageBlock title="Case History">
<apex:pageBlockTable value="{!histories}" var="History" >
<apex:column headerValue="Date" value="{!History.thedate}"/>
<apex:column headerValue="User"> <apex:outputLink value="/{!History.userId}"> {!History.who} </apex:outputLink></apex:column>
<apex:column headerValue="Action"><apex:outputText escape="false" value="{!History.action}"/></apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:component>

 

 

 

 

2. Apex Code

 

public class CaseHistoriesComponentController {

public Id caseId {get; set;}
public cHistories[] histories;

// Variables
public Static final Map<String, Schema.SObjectField> CaseFieldmap = Schema.SObjectType.Case.fields.getMap();
public Static final List<Schema.PicklistEntry> fieldPicklistValues = CaseHistory.Field.getDescribe().getPicklistValues();

public List<cHistories> getHistories()
{
list<cHistories> histories = new list<cHistories>();
String prevDate = '';
for(CaseHistory cHistory : [Select CreatedDate, CreatedBy.Name, CreatedBy.Id, Field, NewValue, OldValue from CaseHistory where CaseId = :caseId order by CreatedDate desc])
{
if((cHistory.newValue == null && cHistory.oldValue == null)
|| (cHistory.newValue != null && !(string.valueOf(cHistory.newValue).startsWith('005') || string.valueOf(cHistory.newValue).startsWith('00G')))
|| (cHistory.oldValue != null && !(string.valueOf(cHistory.oldValue).startsWith('005') || string.valueOf(cHistory.oldValue).startsWith('00G'))))
{
cHistories tempHistory = new cHistories();
// Set the Date and who performed the action
if(String.valueOf(cHistory.CreatedDate) != prevDate)
{
tempHistory.theDate = String.valueOf(cHistory.CreatedDate);
tempHistory.who = cHistory.CreatedBy.Name;
tempHistory.userId = cHistory.CreatedBy.Id;
}
else
{
tempHistory.theDate = '';
tempHistory.who = '';
tempHistory.userId = cHistory.CreatedBy.Id;
}
prevDate = String.valueOf(cHistory.CreatedDate);

// Get the field label
String fieldLabel = CaseHistoriesComponentController.returnFieldLabel(String.valueOf(cHistory.Field));

// Set the Action value
if (String.valueOf(cHistory.Field) == 'created') { // on Creation
tempHistory.action = 'Created.';
}
else if(cHistory.OldValue != null && cHistory.NewValue == null){ // when deleting a value from a field
// Format the Date and if there's an error, catch it and re
try {
tempHistory.action = 'Deleted ' + Date.valueOf(cHistory.OldValue).format() + ' in <b>' + fieldLabel + '</b>.';
} catch (Exception e){
tempHistory.action = 'Deleted ' + String.valueOf(cHistory.OldValue) + ' in <b>' + fieldLabel + '</b>.';
}
}
else{ // all other scenarios
String fromText = '';
if (cHistory.OldValue != null) {
try {
fromText = ' from ' + Date.valueOf(cHistory.OldValue).format();
} catch (Exception e) {
fromText = ' from ' + String.valueOf(cHistory.OldValue);
}
}

String toText = '';
if (cHistory.OldValue != null) {
try {
toText = Date.valueOf(cHistory.NewValue).format();
} catch (Exception e) {
toText = String.valueOf(cHistory.NewValue);
}
}
if(toText != '')
tempHistory.action = 'Changed <b>' + fieldLabel + '</b>' + fromText + ' to <b>' + toText + '</b>.';
else
tempHistory.action = 'Changed <b>' + fieldLabel;
}

// Add to the list
histories.add(tempHistory);
}
}

return histories;
}

// Function to return Field Label of a Case field given a Field API name
public Static String returnFieldLabel(String fieldName)
{
if(CaseHistoriesComponentController.CaseFieldmap.containsKey(fieldName))
return CaseHistoriesComponentController.CaseFieldmap.get(fieldName).getDescribe().getLabel();
else
{
for(Schema.PicklistEntry pickList : fieldPicklistValues)
{
if(pickList.getValue() == fieldName)
{
if(pickList.getLabel() != null)
return pickList.getLabel();
else
return pickList.getValue();
}
}
}
return '';
}
// Inner Class to store the detail of the case histories
public class cHistories {

public String theDate {get; set;}
public String who {get; set;}
public Id userId {get; set;}
public String action {get; set;}
}
}

  Let me know your views on the code or if you have any questions

 

This seems easy enough, but it has me stumped.

 

Use Case: Partners create leads in the partner portal. When the lead is ready to convert, our reps change themselves to the owner and convert it. I want to automatically add (since they forget all the time) the partner user to the sales team.

 

Problem: When I convert the lead (i have the trigger running after insert) I get an error saying that the record is locked.

 

It looks to me like Salesforce inserts the opportunity record, but locks it so its uneditable through the conversion. My trigger also depends on a custom field being mapped over, so that's why I run the trigger after insert so that the field will be mapped over.

 

Any thoughts anyone on how to get around this?

 

Here's my code:

 

 trigger addPartnerToSalesTeam on Opportunity (after insert) {
    
    /**
    * Need to get the opportunity and user
    */
    private Opportunity[] newOpty = new Opportunity[1];
    newOpty = Trigger.new;    

    //get userId of lead creator
    String leadCreatorId = newOpty[0].Lead_Creator_Id__c;

    //get lead Creator profile Id
    User leadCreator = [select profileId from user where id =:leadCreatorId];
    
    newOpty[0].description = leadCreator.ProfileId;//testing
    
    //run trigger if the owner of the converted lead was a partner user
    if(leadCreator.ProfileId == '00e20000000uCnj') {
        newOpty[0].description = newOpty[0].description + ' It works!!!' + ' ' + leadCreatorId; //for testing
        addtoSalesTeam.addUser(newOpty[0], leadCreatorId);

    }//end if

        
}//end addPartnerToSalesTeam trigger

 ________________________________________________________________

 public class addToSalesTeam {
    
    /**
    * To run this method, the trigger (or whatever calls it) must pass two variables:
    *
    * @Opportunity opty = the opportunity being shared
    * @User theUser = the user to be shared with
    *
    */
    public static void addUser (Opportunity opty, String userId) {
        
        OpportunityTeamMember optyMemb = new OpportunityTeamMember();
        
        //put acctId into optyMemb object
        optyMemb.OpportunityId = opty.Id;
        
        //put userId into optyMemb object
        optyMemb.UserId = userId;
        
        //Insert sharing record into database
        Database.Saveresult sr = Database.insert(optyMemb);

    }//end addPartner method

}//end AddToSalesTeam

Hi guys,

I'm experiencing some unexpected behavior when trying to use the apex:repeat function to render tabs....

Basically it seems that tabs cannot be created on demand?  My controller is definitely returning data... as the second page block in my sample will show... repeat works - just the tabs are not rendered..

I'm sure any of you guys can see where I was going with this - and I guess I can achieve a similar result by dropping down to boring old html - just trying to use the standard components (as per best practice)

Any assistance greatly appreciated - as the purist coder me is seriously disturbed at the moment...

here is my 'simplified' and easily testable page & controller

Code: VF PAGE
<apex:page controller="clsRecordType">
    <apex:pageBlock >
        <apex:tabPanel id="theTabPanel">
            <apex:tab label="Account Types"/>
            <apex:repeat value="{!RecordTypes}" var="types">
                <apex:tab label="{!types.Name}"/>     
            </apex:repeat>
        </apex:tabPanel>
    </apex:pageBlock>

    <apex:pageBlock >
        <apex:repeat value="{!RecordTypes}" var="types">
            {!types.Name}<br/>       
        </apex:repeat>
    </apex:pageBlock>
</apex:page>

and the controller

Code:
public class clsRecordType {

    list<RecordType> lrecordtypes;

    public list<RecordType> getRecordTypes() {
        if(lrecordtypes==null) lrecordtypes = [Select Name, Id, Description From RecordType  where SobjectType = 'Account' and IsActive=True];
        return lrecordtypes;
        }
   }

 
 

Hello all...

I'm having trouble with the API for OpportunityTeamMember: There's no way to set the Opportunity Access Level via the API, as there is when using the website.

The OpportunityShare object has exactly the field I need (OpportunityAccessLevel), but that object doesn't include the TeamMemberRole attribute, which I also need.

Finally, UserTeamMember has both, but isn't associated directly with a Opportunity, my last requirement in all this.

Any and all thoughts are appreciated!

Thanks,

Tim