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

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

I have a custom object (Letter_Of_Agreement) that has an Account record as it's master.

 

I was hoping to be able to leverage the existing related list mechanism to display the Account's contacts on a visualforce page (the page is using the LOA controller). 

 

 

Is it possible to reference the parent relationship of an object in a related list in some way?   i.e. <apex:relatedList list="Account__r.Contacts"  />

 

No matter the variation I use, I get an error "List attribute parent name 'account/account__r/etc' is an invalid field name for entity LOA"

 

 

Should I just recreate the related list functionality & look with a custom query and some visualforce?

Message Edited by icemft1976 on 03-03-2010 07:17 AM

Hey all,

 

I'm having an issue with apex action support and required fields.

 

I've got two feilds:

 

Secondary_phone_number__c, and Secondary_phone_number_type__c.

 

Secondary_phone_number_type__c isrequired when Secondary_phone_number__c is not null.

 

So I made a little action region base don this tutorial -

http://wiki.developerforce.com/index.php/Visualforce_DynamicEditPage

- but it only partially works.

 

If I enter a value in Secondary_phone_number__c, then Secondary_phone_number_type__c is rendered AND required, which is correct. But if I change my mind, and delete the value in Secondary_phone_number__c, it re-renders, but still requires Secondary_phone_number_type__c even though it should not...

 

Here is my applicable code, can anyone help out?

 

 

<apex:actionRegion > <apex:panelGrid columns="3" id="thePanelGrid"> <apex:outputPanel> <apex:inputField value="{!Member__c.Secondary_phone_number__c}" id="theInputField"> <apex:actionSupport event="onchange" rerender="thePanelGrid" status="status"/> </apex:inputField> </apex:outputPanel> <apex:inputField value="{!Member__c.Secondary_phone_number_type__c}" required="{!Member__c.Secondary_phone_number__c != null}" rendered="{!Member__c.Secondary_phone_number__c != null}" id="secPhoneType"> <apex:actionSupport event="onchange" rerender="thePanelGrid"/> </apex:inputField> </apex:panelGrid> <apex:actionStatus startText="applying value..." id="status"/> </apex:actionRegion>

 

 

Thanks!

 

 

  • February 10, 2010
  • Like
  • 0
I have a page where I have two pageBlockSections that I want to toggle on and off... Here's the page:

 

 

<apex:page standardController="CustomObject__c" extensions="ControllerExt">

<apex:pageMessages id="pageMessages" />

<apex:form id="terminalForm">
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockSectionItem >
<apex:outputLabel for="type">Type</apex:outputLabel>
<apex:selectList id="type" value="{!type}" size="1">
<apex:selectOptions value="{!typeOptions}" />
<apex:actionSupport event="onchange"
action="{!pageRefreshAction}"
rerender="TypeSection_CC,TypeSection_CH,pageMessages"
</apex:selectList>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>

<apex:outputPanel id="TypeSection_CC" rendered="{!(type == 'option1'||type == 'option2')}">
<apex:pageBlockSection>
<!-- Stuff -->
</apex:pageBlockSection>
</apex:outputPanel>

<apex:outputPanel id="TypeSection_CH" rendered="{!(type == 'option3')}">
<apex:pageBlockSection>
<!-- More Stuff -->
</apex:pageBlockSection>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>

 

As you can see, the sections render depending on the value of "type". The default value of "type" is "option1". So "TypeSection_CC" is displayed when the page loads.

 

The "pageRefreshAction" method just adds a message to the page that displays the value of "type". I've tried making this method void as well, and it makes no difference.

 

 

public PageReference pageRefreshAction() { ApexPages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.INFO, 'Type: '+type)); return null; }

 

 

When I choose "option3" from the "type" selectList the pageMessages block is refreshed and shows the value of "type" as "option3", but TypeSection_CC is still displayed and TypeSection_CH is not displayed.

 

Any help?? I don't know why this is causing problems...

 

Message Edited by ryanhca on 02-09-2010 11:55 AM

I've tested multiple times and found this persitent behaviour with getContent() or getContentAsPDF() methods of PageReference class.

 

Tried this:

I've a VF page which accepts a QueryString parameter "stmtid", and readsfrom an Object on page load like this:

MyObject__c[] objs = [Select Id, Name From MyObject__c Where ID =: ApexPages.currentPage().getParameters().get('stmtid')];

 

I called this VF page from a Custom Button, which works perfectly fine and generates the PDF on load, since the page is RenderAs="PDF".

 

BUT when I use this code:

 

PageReference p = Page.MyVFPDF; p.getParameters().put('stmtid', a.ID); Attachment attachment = new Attachment(); attachment.Body = p.getContentAsPDF(); // OR p.getContent() ... ... ... insert attachment;

 

 

 

Here, I getEmpty PDF file, since the Query in MyVFPDF page's extention class' contructor is returning Null value, i.e. No Record, but same ID (stmtid) value can be queried against the database and I can see the results in Eclipse Object browser ...

 

So, can anyone guide me here why I can't read the Values when I call the page in APEX calls and tries to read the Content to generate a PDF, but can use same page & stmtid variable value on a Custom Button & generate a PDF file ?

 

  • February 09, 2010
  • Like
  • 0

I'm writing a trigger and need to count records that match a few criteria.

 

The current query is:

 

 

Integer i = [select count() from Account where Account_Status__c = 'Open' AND Producer_Code__c = :pcode ];

 I need to add another criteria that will match records with "Account_Established__c" within the current month?

 

Any quick and easy way to do this?

 

Thanks in advance.

 

 

 

Hi


I am new to visualforce so am probably doing things by trial and error and looking at examples (and so not getting the whole picture).

 

But I have controller extension for a custom object (call it FSL) and part of what the controller extension is trying to do is to generate a case off the save of this FSL custom object (PageReference save() function) and then have in the Case Description field the value of the full url of this custom object's entry.

 

Specifically, if this custom object entryhas id of xxxyyz and I am in my sandbox instance, then I want to be able to have in Case Description something like 'For more detail on this object, please refer to '+CustomObject_Link;  and the CustomerObject_Link would return say https://tapp0.salesforce.com/xxxyyz.

 

Right now, I  have the following code:

 

public PageReference Save() {

PageReference CustomObject_Link = new PageReference('/' + FSL.id);

.

.

cases.Description='You can see more detail for the FSL entry related to this request by clicking on this link: '+CustomObject_Link;

 

 

And when the case is generated, the Case Description would just contain:

 

 You can see more detail for the FSL entry related to this request by clicking on this link:/xxxyyz.

 

 

I can hardcode the CustomObject_link in sandbox so that it has:

public PageReference Save() {

PageReference CustomObject_Link = 'https://tapp0.salesforce.com'+new PageReference('/' + FSL.id);

 

And this will allow Case Description to contain:

 You can see more detail for the FSL entry related to this request by clicking on this link:https://tapp0.salesforce.com/xxxyyz.

 

Problem is when I bring this to production, we have a different instance (i.e. it would be https://na2.salesforce.com).

 

So how does one extract the instance information (i.e. that it's na2 instead of tapp0) in visualforce so I can do something like:

 

  PageReference CustomObject_Link = 'https://'+CurrentInstance+'.salesforce.com'+new PageReference('/' + FSL.id);

 

Or how do I just issue a PageReference properly so that it would return the full url (https://<salesforce instance url>/xxyyz) and not just /xxxyyz?

 

 

 

 

 

  • February 02, 2010
  • Like
  • 0

 this is first trigger

trigger chAccGenerate on Organization__c (after insert) {
      if (Trigger.isInsert){
      List<Chart_of_accounts__c> accounts = new Chart_of_accounts__c[0];
      List<SMain__c> smain = new SMain__c[0];
        for (Organization__c o : Trigger.new) {        
            if(o.Industry__c == 'Telecom')
             {accounts.add(new Chart_of_accounts__c (name = 'Sales of product income',Type__c = 'Income',Organization__c = o.ID));
            accounts.add(new Chart_of_accounts__c (name = 'Service/fee income',Type__c = 'Income',Organization__c = o.ID));
            insert accounts;
            }
            
}
}
}

 

 

 

trigger test on Chart_of_accounts__c (after insert) { if (Trigger.isInsert){ List<SMain__c> smain = new SMain__c[0]; for (Chart_of_accounts__c c : Trigger.new) { if(c.Type__c == 'Income') {smain.add(new SMain__c (Chart_of_accounts__c = c.ID)); insert smain; } } } }

 

 

 after create Organization__c record force say:

 

 Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CloudBudget.chAccGenerate caused an unexpected exception, contact your administrator: CloudBudget.chAccGenerate: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CloudBudget.test: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id a0AA0000000EdM1MAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.CloudBudget.test: line 7, column 13: []: Trigger.CloudBudget.chAccGenerate: line 9, column 13

 

 

???

 

 

  • January 06, 2010
  • Like
  • 0

Hello.  I'm building some Apex code - writing a query where I grab a parent and certain child records.  The Parent is Conference and the child is Attendee.  So I would expect the inner query to be SELECT Id FROM Attendees__r...  This wasn't working so i checked it in the schema browser and I see the following:

 

Select c.Name, c.Id, (Select Id From Sessions__r), (Select Id, Name From R00N50000001QtE7EAK) From Conference__c c

 

I checked the schema browser and the relationship name is indeed R00N50000001QtE7EAK.  How/Why is this happening?  Is there a way to change it?

 

Thanks

Chris

 

 

 

easy one, i think, but i can't find it in the forums.  i have a vf page that displays some checkboxes and fields - all are fields on the underlying object.  i added some functionality where i put a checkbox in an actionRegion - so when the checkbox is toggled, stuff happens.  everything works perfectly, but my field label is no longer displayed.  i added it manually, but the style and spacing are lost.  what am i doing wrong?

 

i saw one forum post to put the info in pageblocksectionitems, which i did, but it didn't help.  code snippet is below...

 

Thanks for your help.

chris

 

<apex:actionRegion >
  <apex:pageBlockSectionItem >
    <apex:outputLabel value="{!$ObjectType.SFDC_520_Quote__c.fields.Estimated_SalesTax_Override_Flag__c.label}"
                                        for="SalesTaxOverrideCheckboxField"/>
                       
    <apex:inputField value="{!SFDC_520_Quote__c.Estimated_SalesTax_Override_Flag__c}"
                            rendered="{!SFDC_520_Quote__c.Opportunity__r.Site_Address_State__c == 'NY'}"
                            id="SalesTaxOverrideCheckboxField">   
      <apex:actionSupport event="onchange"
                                        rerender="orderWorksheetDetailPanel" />
   </apex:inputField>

  </apex:pageBlockSectionItem>
</apex:actionRegion>
 

Hi,

 

I have custom field "Speciality(picklist)" and "SubSpeciality(multiselect picklist)" in my Account object. Speciality is the controlling field for SubSpeciality. Subspeciality is changed based on the selection of Speciality.

 

It is working fine in standard page layout. But I want to use it in my VF page to create new Account record. I have used inputfield and it display the details of both speciality and subspeciality. but subspeciality is not changed on selection of speciality.

 

How can I change the subspeciality on selection of speciality field. Following are sample code of my page.

Please help..... 

 

 

          <apex:inputfield value="{!Account.Speciality__pc}"></apex:inputfield>
           <apex:inputfield value="{!Account.Subspecialty__pc}" />

 

Thanks in Advance.

 

Kamlesh Chauhan

Hi,

 

I overrode my CaseComments related list on the Case page layout due to comments customization needs:

 

VForce Page

 

<apex:page standardController="Case" extensions="CaseCommentRelatedListExt">

 

<apex:pageBlock >

<apex:pageBlockTable value="{!Case.CaseComments}" var="c">

<apex:column headerValue="CC">

       <apex:form >

                <apex:inputField value="{!c.IsPublished}"/>

        </apex:form>

</apex:column>

<apex:column headerValue="Date" value="{!c.createddate}"/>

<apex:column headerValue="Created By" value="{!c.CreatedById}"/>

<apex:column headerValue="Comment" value="{!c.CommentBody}"/>

</apex:pageBlockTable>

</apex:pageBlock>

</apex:page> 

 

Even though this is great, I lost some of the standard functionality of CaseComments such as the edit, delete buttons

 

Is there a way I can call this functionalities from vforce without writing my own Case Comment edit page?

 

Thank you very much

 

 

  • October 15, 2009
  • Like
  • 0

Hi,

 

Is it do-able to replace the standard case comment related list and replace it with a custom visual force page?

 

And if it is possible how difficult it is?

 

Thank you.

  • October 12, 2009
  • Like
  • 0

Hello

 

I am trying to build a table of data in a page.

 

I have used the tutorial I find in the Visualforce guide, and it works just fine.

 

-------------

<apex:page standardController="Account">
   <apex:pageBlock title="Hello {!$User.FirstName}!">
      You are viewing the {!account.name} account.
   </apex:pageBlock>
   <apex:pageBlock title="Contacts">
      <apex:pageBlockTable value="{!account.Contacts}" var="contact">
         <apex:column value="{!contact.Name}"/>
         <apex:column value="{!contact.MailingCity}"/>
         <apex:column value="{!contact.Phone}"/>
      </apex:pageBlockTable>
   </apex:pageBlock>
</apex:page>

 Now, I am trying to adjust this to match what I am trying to do.

 

I have two custom objects:

 

Program Participation (which contains a master lookup fiels to Contacts, who participated in this program)

Review (this object has a lookup field to program participation, and basically allows to enter different reviews on the program)

 

What I am trying to do is, from within the Program Participation, to display all the reviews . This is the code I have

 

<apex:page standardController="Program_Participation__c">

    <apex:pageBlock title="Hello {!$User.FirstName}!">

    You are viewing the {!Program_Participation__c.name} Program Participation record

 

          <apex:pageBlockTable value="{!Program_Participation__c.Reviews}" var="review">         <apex:column value="{!review.Name}"/>

      </apex:pageBlockTable>    </apex:pageBlock> 

   </apex:page>

 

 When I save I get this error message

 

  

Error: Invalid field Reviews for SObject Program_Participation__c

 

Does anybody have an idea why this is happening?

 

Thanks

Giorgio

I got a question from a customer today and just wanted to verify the answer with the community.

 

If I send an HTTP Callout to a web service that a customer has exposed, how do I make sure that it is compressed?  If I simply add an  HTTP header like: Content-Encoding: gzip  will that do it?

 

 

Hello Community,

 

I have a VF page, with a list of objects.

 

I am using DataTable to bring the list of objects on VF Page, and am using a component to display a single object. The component has its own logic of building the view to display that object.

 

Now, in that component, I have a small button, that is supposed to do something in the background, and update the display of an object field on the component itself. And, I am using apex:CommandLink and rerender to do that.

 

But, the issue is, that when a component is rendered repeatedly in a VF page, the IDs inside the component are also duplicated and repeated as-they-are; resulting in duplicate IDs in the VF page.

 

For example, if I have a <apex:outputText id="DisplayName" value="{!DisplayName}"> inside the component; and if this component is repeated in the VF page, all these outputText elements would have the same ID.., not even a single change....., and if I am trying to re-render this outputText, the system doesn't do anything at all.

 

Re-render is not working at all, in this case...

 

To summarize again, if I am using a component repeatedly in a VF page, and doing something inside the component and re-rendering inside the component.. it doesn't work at all !!

 

Any solutions ? I dont want to go the manual way of writing javascript and ajax methods.

 

 

  • July 08, 2009
  • Like
  • 0

Hi All,

 

I'm trying to call an Apex function (in a controller extension class) using a Javascript "onclick" event and a VF ActionFunction. The scenario is this....

 

The button that triggers the "onclick" event is located in a VF page of form:

 

 

<apex:page controller="MyMasterPageController">

<apex:sectionHeader title="ATitle">
<apex:pageBlock >
<apex:composition template="MyChildPageComposition"/>

<apex:form >
<apex:commandButton value="Click Me" onclick="MyJavascriptFunc()"/>
</apex:form>

</apex:pageBlock>
</apex:sectionHeader>

</apex:page>

 

which is known as the "master" page.

 

 

The javascript function is located in the composition "MyChildPageComposition" of form:

 

 

<apex:page controller="MyMasterPageController" extensions="ControllerExtForChildPage">
<apex:form >

<apex:actionFunction action="{!myApexFunc}" name="MyJavascriptFunc"/>

<apex:pageBlock>
<apex:pageBlockSection title="ASectionTitle">

<!-- Input fields/bulk of VF page etc goes here -->

</apex:pageBlockSection>
</apex:pageBlock>

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

 

which is known as the "child" page and displayed within the "master" page using the <apex:composition> functionality.

 

 

The Apex function "myApexFunc" is found in the class "ControllerExtForChildPageComposition" and is of form:

 

 

public PageReference myApexFunc() {

// do something here
system.debug('Print some debug here');

return null;
}

 

 

 

Now, my issue is that if I create the VF pages for real as basic as those examples above, "myApexFunc" is successfully called (the debug is printed, and any other code in it runs) when the "Click Me" button in the master page is clicked.

 

However, when I have attempted to incorprate the basic apex and VF code above into existing master/child pages and their associated controllers and extensions, "myApexFunc" is never successfully called. In fact, if the child page is subsituted for a child page of this form:

 

 

 

<apex:page controller="MyMasterPageController" extensions="ControllerExtForChildPage">
<apex:form >

<apex:actionFunction action="{!myApexFunc}" name="AnotherJavascriptFunc"/>

<script>

function MyJavascriptFunc() {
alert('Running Javascript');
AnotherJavascriptFunc();
alert('Finishing javascript');
}

</script>

<apex:pageBlock>
<apex:pageBlockSection title="ASectionTitle">

<!-- Input fields/bulk of VF page etc goes here -->

</apex:pageBlockSection>
</apex:pageBlock>

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

 

which is incorprated into an existing child page,both alerts are run (proving that the link between the "onclick" event in the master page and "MyJavascriptFunc" in the child page composition is there, but "myApexFunc" is still not called! Can anyone shed any light on this? Is there any VF or Apex code which is incompatible with using Javascript and action functions? As I said before, when it's in its basic forms above, everything works, just not when other VF and apex code are added.

 

Many thanks,

 

Marco

 

 

 

 

 

 

 

 

I want to add some parameter for the function in actionfunction.

example:
visualforce code

<apex:actionFunction action="{!insertSelDMDocId}"  status="selDocIdCb" name="insertSelDMDocId"/>

fuction abc(){

 insertSelDMDocId();//i want to add a parameter like insertSelDMDocId(id)

}

apex code:

// I want to get id here like insertSelDMDocId(id) , but it some error occurred.
public void insertSelDMDocId() {

   myid = id

 }

i have no idea about this issue.

If anyone can help me?

Thank you very much!!

 

Hi All,

 

I have a visualforce page which has some input fields displayed in it.

These fields are not present in the database. I want to get the red mark on this fields that Salesforce has for required field.

 

I have seen that the red mark appears when we use standard controller and display standard field with requiredtrue in the field attribute. But in my case the fields are not a part of the database

 

Does visualforce has any inbuilt attribute to display the red mark or should I get it as an image myself?

 

 

Thanks & Regards,

Heena 

  • February 26, 2009
  • Like
  • 0
I hope someone can help me.  I have a VF page that includes 4 tabbed sections.  One of them is a custom search tab.  When the user types their criteria (an account name) into the inputtext box, and clicks my search button, everything works great.  If the user types in their criteria, then presses "Enter",  the page refreshes and takes the user back to the first tab (my search tab is the fourth tab).
How can I get pressing enter to be the same as clicking the button?

Thanks in advance!!

Jim
  • August 27, 2008
  • Like
  • 1
I made a trigger that updates somes values after update. But some fields are not the same type.

Is there any functionnality ( like toString)  to covnert My picklist values (String) to a double ( Like parseFloat in Javascript).


Thank you
  • February 05, 2008
  • Like
  • 0

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');" />

 

 

Hi,

 

I have a Visualforce page through which I am trying to access a SDK. It is done using ActiveX control. The VB + JS script that I have runs fine when it is a normal HTML page residing on my desktop. However the same code when incorporated in Visualforce does not work. Does running ActiveX control require uploading any kind of files to Static Resource? My code need not be a Visualforce. If there is any other way I could integrate ActiveX with Salesforce, even that would be fine. 


Thanks in Advance.

 

Based on the holidays mentioned in the Company Profile, I need to find out if a given date falls on an Holiday or not? Currently I am doing this using a complex logic where based on all the permutations and combinations like Yearly, Monthly, Daily, etc I try to see if it is a holiday or not. I just wanted to know if there is a simpler way to do this that I don't know about.

 

I have a force.com site with lets say XYZ as the home page. In one of the subsequent pages I am displaying images uploaded in the attachment object of the related record. To display the image, I am forming the url as '/servlet/servlet.FileDownload?file=' + attachmentId;' This works fine when I use the apex image tag to display the images on the site.

However due to another problem, I had to use html image tag. But when I use the html tag, the images don't get displayed. In order to display them, I have to change the url as  '/XYZ/servlet/servlet.FileDownload?file=' + attachmentId;'. This works fine in sites but gives error when viewing the site page as a normal VF page when logged in. 

Can anyone explain why is difference between apex image and html image? And what are the possible solutions I have to display the images on both sites and VF page?

As of now, I am trying to solve the other problem I am facing using apex image. If that works out, I will use Apex Image tag.

Something very interesting I found today and thought to share it.

We have a custom button on detail page of a object with the OnClick JavaScript behaviour. The JavaScript checks certain field values and based on that, it redirects the User to a Visualforce page. One of the parameters we passed to visualforce page was named 'sid' i.e. we used to pass sid = Id of the record. Everything worked fine except for one case.

When we login to the org and click the button, it didn't redirected us to the VF page. Instead what it did was it toggled between the VF page and the detail page continuously till the browser got tired and threw an error. However if we went to any other Visualforce page and then came back to the detail page and again clicked the button, everything worked fine and we were redirected to the VF page. Weird. 

After a lot of debugging, I finally found the problem. It was the name of the parameter sid. I looked into the details of the page getting called using Firebug and I found that my sid parameter contained the session id instead of the Id of the record. For some reason, the first time when we try to visit the Visualforce page, salesforce replaced the sid with session id. However, after visiting another page and then calling our VF page, the sid now had the Id of the record. 

To solve, we replaced the sid parameter with something else. Lesson learnt: Do not use the standard parameter that salesforce uses unless you are trying to override it.

 


Message Edited by Rajesh Shah on 01-20-2010 04:09 PM

I have a standard Salesforce edit page where the first 2 fields are picklist and the next one is a date field. Everytime the page loads in edit mode, salesforce automatically brings the date field in focus and the calendar widget pops up. This can be very confusing to the users as the date field is required to be populated only in certain cases. I also do not have the option of moving a text field before the date field.

Is there a way to remove the focus or allow me to have some other field in focus?

Requirement: A group of X people in the system should have the right to Add team members to Accounts. The group of people may belong to 1 single profile but not necessarily

 

Problem: This is what salesforce says about the permissions a user need to have to add a Team member to a Account Group.

a. He is a System Administrator

b. He is the Owner of the Account

c. He is the Manager of the Owner

d. He has Modify all Data and Manage user permission on his profile.

 

In my case, none of the above condition is satisfactory for the group of X people. Is there any other way I can give them the permission to add Account Team Member? I also found that if a User A is added to Account Team with Read/Write permission, he can add another Team Member  but he can only provide that other member Read Access.

 Can I use this in some way?

I am having a problem in creating a report type. Before the problem, let me explain the relationship between the objects.

I have object A as child of Account and object B as child of A. So its like Account -> Object A -> Object B. I need to create a report with the details from Account, Object A and Object B. This can be done using report Type. However, it is also required to summarize the information based on the roles defined in Account Team. This kind of relationship cannot be created in Report Type. 

Is there any way, that this is possible to do using Out of the box functionality? If not, what are the alternatives?

Regards,

Rajesh

I created a Custom Setting Data Set to store the Visualforce page that needs to be called for each recordtype. In the Name, I am storing the Record Type name. The whole feature works great for my requirement except for a small hitch.

 

The Name field length is 38 charaters. So I cannot add record type names more than 38 chars and I have record types with length upto 60 characters. Also, in eclipse Schema, I can see that the length of the field is 80 chars. I checked in another org and it also gave the same error. Now because of this small hitch, I cannot use this feature. :smileysad:

 

Is it a bug from Salesforce? or will the length of the Name field always be 38?

Is there any to pass to parameters from a javascript to a actionFunction?

For eg  I have a var 'x' in javascript set to some value. On some condition I need to call a actionFunction which calls a controller. I need to pass the value of x to the controller. I can pass using param tag of actionFunction to controller but how to pass x to the actionFunctio?

Hi All,

 

I am writing an apex class which has grown too big. When saving through Eclipse or UI, it gives me that 'Script too large'.

What exactly is the size limit of an Apex Class?

 

 

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

 

Recently I was working on a requirement which required overriding the Case detail page with a visualforce page. Problem crept when the related list comonent didnt worked for Case Comments and History. So I decided to write my own code to display the related lists.

I was finally able to write my own code to display the related list. It implements all the function that standard related list of Case Comments provide. In order to make it reusable, I made it as a component so that in other pages I just need to pass the Case Id and I will get the complete list of Case Comments.

 Heres the code finally :

 1. Component Code

 

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

<!-- Component Body -->
<apex:componentBody >
<apex:form >
<apex:pageBlock title="Case Comments" >
<apex:pageBlockButtons location="top">
<apex:commandButton action="{!NewComment}" value="New"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!Comments}" var="comment">
<apex:column headerValue="Action">
<apex:outputLink value="/{!comment.cComment.Id}/e?parent_id={!caseId}&retURL=/{!caseId}">Edit</apex:outputLink>&nbsp | &nbsp
<apex:commandLink action="{!deleteComment}" value="Del">
<apex:param name="CommentId_d" value="{!comment.cComment.Id}"/>
</apex:commandLink>&nbsp | &nbsp
<apex:commandLink action="{!makePublicPrivate}" value="{!comment.PublicPrivateAction}">
<apex:param name="CommentId_p" value="{!comment.cComment.Id}" />
</apex:commandLink>
</apex:column>
<apex:column headerValue="Public" value="{!comment.cComment.IsPublished}" />
<apex:column headerValue="Comments">
<apex:outputText escape="false" value="{!comment.commentText}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:componentBody>
</apex:component>

 

 2. Apex Code

public with sharing class CaseCommentsComponentController {

public Id caseId {get; set;}
public cComments[] comments{
get{
List<cComments> comments = new List<cComments>();
for(CaseComment comment : [Select LastModifiedDate, LastModifiedBy.Id, LastModifiedBy.Name, IsPublished, CreatedDate, CreatedBy.Id, CreatedBy.Name, CommentBody From CaseComment c where ParentId = :caseId order by c.LastModifiedDate desc])
{
cComments tempcComment = new cComments();
tempcComment.cComment = comment;

// Build String to display.
tempcComment.commentText = '<b>Created By: <a href=\'/' + comment.CreatedBy.Id + '\'>' + comment.CreatedBy.Name + '</a> (' + comment.CreatedDate.format() + ') | ';
tempcComment.commentText += 'Last Modified By: <a href=\'/' + comment.LastModifiedBy.Id + '\'>' + comment.LastModifiedBy.Name + '</a> (' + comment.LastModifiedDate.format() + ')</b><br>';
tempcComment.commentText += comment.CommentBody;

if(comment.IsPublished)
tempcComment.PublicPrivateAction = 'Make Private';
else
tempcComment.PublicPrivateAction = 'Make Public';
//Add to list
comments.add(tempcComment);
}
return comments;
}

set;
}

public PageReference NewComment()
{
PageReference pr = new PageReference('/00a/e?parent_id='+ caseId + '&retURL=%2F' + caseId);
pr.setRedirect(true);
return pr;
}

public PageReference deleteComment()
{
Id commentId = ApexPages.currentPage().getParameters().get('CommentId_d');

for(cComments Comment : comments)
{
if(Comment.cComment.Id == commentId)
{
delete Comment.cComment;
break;
}
}

PageReference pg = new PageReference('/' + caseId);
pg.setRedirect(true);
return pg;
}

public PageReference makePublicPrivate()
{
Id commentId = ApexPages.currentPage().getParameters().get('CommentId_p');
for(cComments Comment : comments)
{
if(Comment.cComment.Id == commentId)
{
Comment.cComment.IsPublished = !Comment.cComment.IsPublished;
if(Comment.cComment.IsPublished)
Comment.PublicPrivateAction = 'Make Private';
else
Comment.PublicPrivateAction = 'Make Public';

update Comment.cComment;
break;
}
}
PageReference pg = new PageReference('/' + caseId);
pg.setRedirect(true);
return pg;
}

public class cComments {

public CaseComment cComment {get; set;}
public String commentText {get; set;}
public String PublicPrivateAction {get; set;}
}
}

 Hope it is helpful to you.

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

Message Edited by Rajesh Shah on 10-16-2009 08:03 PM

I am having a problem using action Support and rerendering a section.

Following is the page code.

<apex:form id="AccountForm">
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}" />
<apex:commandButton value="Cancel" action="{!cancel}" />
<apex:commandButton value="Custom Save" action="{!saveCustom}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:inputField value="{!Account.Name}" />
<apex:inputField required="true" value="{!Account.AccountNumber}" />
<apex:inputField value="{!Account.Industry}" />
<apex:inputField value="{!Account.Has_Shipping_Address__c}" >
<apex:actionSupport event="onclick" action="{!changeShippingSection}" rerender="AccountForm" status="StatusChange"/>
<apex:actionStatus startText="Updating page ..." id="StatusChange"/>
</apex:inputField>


</apex:pageBlockSection>

<apex:pageBlockSection id="ShippingAddressSection" rendered="{!shippingSection}" Title="Shipping Address" >
<apex:inputField value="{!Account.ShippingCity}" />
<apex:inputField value="{!Account.ShippingState}" />
<apex:inputField value="{!Account.ShippingCountry}" />
<apex:inputField value="{!Account.ShippingPostalCode}" />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>

 In the above code, when the Has Shipping Address field is clicked, the Shipping Address section should be visible. Following is the corresponding controller code

public void changeShippingSection()
{
shippingSection = account.Has_Shipping_Address__c;
//return null;
}

 It works perfectly fine when I AccountForm as Id in the rerender attribute. But if I put shippingAddressSection as Id in the attribute, no change happens even though function gets called.

Is this the intended behaviour or am I missing something?

 

 

 

Message Edited by Rajesh Shah on 10-08-2009 07:47 PM

Hi, I have the following query.

For the current User, I need to determine if it belongs to particular group or not. In the case, where the group is of type Roles And Subordinates, how do I determine this? I checked that for this type of group, there are no group members. So the only option I would have is to traverse through the Role Heirarchy. 

 

Let me know if there is a better way to do this.

 

I am building a Visualforce page for creating a case. Now there are fields in case which are read only for all profiles except System Adminstrator. I need the user to enter the value for this field and so I created my page with a controller and not a standard controller. Also in my controller I added the modifier as without sharing.

 

Now when I log in through another user, I still see the field as read only on the page. However from the controller I am able to insert value or update the field. I fail to understand this. It seems to me that the page is running in User mode following the user profile permissions and field level security while the controller is running in Sytem mode. Is this the intended behaviour or am I missing something?

 

How do I solve this? Has anybody faced a similar problem before? Please reply. This is very critical to the project I am doing.

How do I get a pageReference of a S-Control in an Visualforce Controller?

For eg: I want to call an S-Control after saving the record in the s-contol.

I know I can do it using /servlet/servletIntegration ...... but I don't want to do it this way. 

Message Edited by Rajesh Shah on 09-08-2009 07:12 PM

We have a Case application where there are many record types. What we have done is using s-control, we have created our own print functions which mimics the printable view function. Basically what we do is get the content of the print page, remove not required sections and display the core details for print with some custom style sheets applied. This is working fine for the existing recordtypes.

 

Recently we created a new record type, which requried details from a Child Object too. So we build a Visualforce view page for it showing the details in one go from both the Case and the child object. But when I use the print s-control for this, I only get the case details and not the child details. It is very important to show the child details in the print and I can't think of a to do it. 

 

Let me know if any of you have a solution for this. 

How can i pass  a network like "\\192.168.0.1\c\project\Salesforce\Test.txt " in a URl field defined for a Custome object thru an Apex Code.

 

I tried doing  the same but type of erros shown are:-

 

1. Save error: line breaks not allowed in string literals  


Please help me in this issue

I have a Visualforce page which displays Case details in a custom way. For rendering Case Comments, I cannot directly use Case Comments related list as it is not allowed by Salesforce. So I created a Custom Component which takes Case Id as parameter and generates the related list of Case Comments as it is rendered in a normal view. Everything works fine till now.

 

In the related list I have also added links like del, Make public/Private for the case comments. These are command links which have corresponding action functions in the custom component controller. These functions return page reference of null. When the page is rerendered after the call, I now see 2 section headers instead of 1. I have no idea why there should be 2 section headers coming up when there is a tag for only 1. btw both the section headers come one below the other.

 

Has anyone faced this problem before? Do let me kniow your ideas.

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');" />

 

 

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

 

Recently I was working on a requirement which required overriding the Case detail page with a visualforce page. Problem crept when the related list comonent didnt worked for Case Comments and History. So I decided to write my own code to display the related lists.

I was finally able to write my own code to display the related list. It implements all the function that standard related list of Case Comments provide. In order to make it reusable, I made it as a component so that in other pages I just need to pass the Case Id and I will get the complete list of Case Comments.

 Heres the code finally :

 1. Component Code

 

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

<!-- Component Body -->
<apex:componentBody >
<apex:form >
<apex:pageBlock title="Case Comments" >
<apex:pageBlockButtons location="top">
<apex:commandButton action="{!NewComment}" value="New"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!Comments}" var="comment">
<apex:column headerValue="Action">
<apex:outputLink value="/{!comment.cComment.Id}/e?parent_id={!caseId}&retURL=/{!caseId}">Edit</apex:outputLink>&nbsp | &nbsp
<apex:commandLink action="{!deleteComment}" value="Del">
<apex:param name="CommentId_d" value="{!comment.cComment.Id}"/>
</apex:commandLink>&nbsp | &nbsp
<apex:commandLink action="{!makePublicPrivate}" value="{!comment.PublicPrivateAction}">
<apex:param name="CommentId_p" value="{!comment.cComment.Id}" />
</apex:commandLink>
</apex:column>
<apex:column headerValue="Public" value="{!comment.cComment.IsPublished}" />
<apex:column headerValue="Comments">
<apex:outputText escape="false" value="{!comment.commentText}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:componentBody>
</apex:component>

 

 2. Apex Code

public with sharing class CaseCommentsComponentController {

public Id caseId {get; set;}
public cComments[] comments{
get{
List<cComments> comments = new List<cComments>();
for(CaseComment comment : [Select LastModifiedDate, LastModifiedBy.Id, LastModifiedBy.Name, IsPublished, CreatedDate, CreatedBy.Id, CreatedBy.Name, CommentBody From CaseComment c where ParentId = :caseId order by c.LastModifiedDate desc])
{
cComments tempcComment = new cComments();
tempcComment.cComment = comment;

// Build String to display.
tempcComment.commentText = '<b>Created By: <a href=\'/' + comment.CreatedBy.Id + '\'>' + comment.CreatedBy.Name + '</a> (' + comment.CreatedDate.format() + ') | ';
tempcComment.commentText += 'Last Modified By: <a href=\'/' + comment.LastModifiedBy.Id + '\'>' + comment.LastModifiedBy.Name + '</a> (' + comment.LastModifiedDate.format() + ')</b><br>';
tempcComment.commentText += comment.CommentBody;

if(comment.IsPublished)
tempcComment.PublicPrivateAction = 'Make Private';
else
tempcComment.PublicPrivateAction = 'Make Public';
//Add to list
comments.add(tempcComment);
}
return comments;
}

set;
}

public PageReference NewComment()
{
PageReference pr = new PageReference('/00a/e?parent_id='+ caseId + '&retURL=%2F' + caseId);
pr.setRedirect(true);
return pr;
}

public PageReference deleteComment()
{
Id commentId = ApexPages.currentPage().getParameters().get('CommentId_d');

for(cComments Comment : comments)
{
if(Comment.cComment.Id == commentId)
{
delete Comment.cComment;
break;
}
}

PageReference pg = new PageReference('/' + caseId);
pg.setRedirect(true);
return pg;
}

public PageReference makePublicPrivate()
{
Id commentId = ApexPages.currentPage().getParameters().get('CommentId_p');
for(cComments Comment : comments)
{
if(Comment.cComment.Id == commentId)
{
Comment.cComment.IsPublished = !Comment.cComment.IsPublished;
if(Comment.cComment.IsPublished)
Comment.PublicPrivateAction = 'Make Private';
else
Comment.PublicPrivateAction = 'Make Public';

update Comment.cComment;
break;
}
}
PageReference pg = new PageReference('/' + caseId);
pg.setRedirect(true);
return pg;
}

public class cComments {

public CaseComment cComment {get; set;}
public String commentText {get; set;}
public String PublicPrivateAction {get; set;}
}
}

 Hope it is helpful to you.

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

Message Edited by Rajesh Shah on 10-16-2009 08:03 PM

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?

  • March 01, 2011
  • Like
  • 0

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

  • February 09, 2011
  • Like
  • 0

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

 

 

  • January 18, 2011
  • Like
  • 0

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

 

 

  • January 14, 2011
  • Like
  • 0

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

 

  • January 29, 2010
  • Like
  • 0

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