• wesnolte
  • SMARTIE
  • 1596 Points
  • Member since 2009

  • Chatter
    Feed
  • 60
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 388
    Replies

I want to write code that does stuff based on the choices in a picklist. I know all the choices in a picklist and of course I could hardcode it, but I want to be able to edit the picklist choices without breaking my code.

 

Example:

 

Let's say I have a custom object that has a picklist value named "Mood" with the options of "Happy", "Sad" and "Fine". Next I have a visualforce page with a table with totals for each mood.

 

I could easily write code in the VF controller that pulls all my records, and iterates through each with a if statement that checks the mood and totals them.

 

The problem there is if I ever add another mood to the picklist, I would then have to edit my vf page and the controller apex to reflect the additional moods.

 

It would be a lot nicer to be able, in apex, to get a list of the picklist options and then iterate through those and run the tallying code.

 

 

This is not my specific usecase, but it illustrates it nicely. Could someone out there help me out? 

Oh, and FYI, I through this code in there:

 

 

schema.describefieldresult f = schema.sobjecttype.my_custom_object__c.fields.my_custom_field__c;

 

but I get an error page saying, System.Exception: Too many fields describes: 11 

 

 

Hi,

 

I'm totally newbie on Sales force, and I'm trying something that should be easy.

From a Case, I want to manage a new type of object, named SMS

I created the object and now I want to customize the page, with APEX

 

So, I created a class

 

global class NetsizeClass { private SMS__c currentSms; public SMS__c getSms() { return currentSms; } public NetsizeClass(ApexPages.StandardController controller) { if (currentSms == null) currentSms = new SMS__c(); string sms_id = System.currentPageReference().getParameters().get('id'); if (sms_id == null || sms_id == '') { // New SMS currentSms.message__c = 'New SMS '; } else currentSms= [select message__c, status__c, case__c, contact__c from SMS__c where id = :sms_id]; } public void SendSMS() { if (currentSms.id == null || currentSms.id == '')
// New SMS
else
// Existing SMS

upsert currentSms;
... } }

 

and a Page, that overload the 'New' button in my SMS object

 

<apex:page standardController="SMS__c" extensions="NetsizeClass"> <apex:sectionHeader title="New SMS" subtitle=""/> <apex:form> <apex:pageBlock title="SMS information"> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}"/> <apex:commandButton value="Send SMS" action="{!SendSMS}"/> </apex:pageBlockButtons> <TABLE> <TR> <TD><B>Message</B></TD> <TD><apex:inputField value="{!sms.Message__c}" id="smsMsg"/></TD> </TR> <TR> <TD><B>Contact</B></TD> <TD><apex:inputField value="{!sms.Contact__c}" id="smsContact"/></TD> </TR> <TR> <TD><B>Case</B></TD> <TD><apex:inputField value="{!sms.Case__c}" id="smsCase"/></TD> </TR> <TR> <TD><B>Case 2</B></TD> <TD><apex:inputField value="{!SMS__c.Case__c}" id="smsCase2"/></TD> </TR> </TABLE> <br/> </apex:pageBlock> </apex:form> </apex:page>

 

It works fine, when I am on a Case, I see the button 'New SMS' (I customized the layout), that open my custom APEX page.

But I just don't know how to retreive the parent Case information (I'm using the 2 fields Case for my tests):

- the field smsCase is empty, and it's normal as it is linked to {!sms.Case__c} and sms is created in the constructor. But I read in some forums that it's the only way to retreive later the updated values (I want to customize the Edit and View page)

- the field smsCase2 is filled with the id of my Case, but I don't know how to retreive this data from my page.

 

I also would like to retreive automatically the contact linked in the parent Case, to link it to the SMS. But I think it should be easy to do when I'll have the ID of my Case.

 

I'm sure that I'm missing something but I searched in so much forums that I'm starting to mix-up everything.

Any help will be welcome :)

 

Thanks

Hervé

 

 

  • August 11, 2009
  • Like
  • 0

Hello,

 I am using the below code to redirect to the standard salesforce pages as:

 

    public PageReference Save()

    { 

String newPageUrl = 'https://ap1.salesforce.com/701/o';

   PageReference newPage = new PageReference(newPageUrl);

   newPage.setRedirect(true);

   return newPage; 

    } 

 This piece of code helps in navigating the page to campaign default page.Here the url-"https://ap1.salesforce.com/701/o" is the campaigns default page url for my account.

 

Instead of passing the complete url is there any way to redirect to sandard campaign page in pageReference method. 

 

Thanks,

shaan 

  • August 11, 2009
  • Like
  • 0

I have Product object in salesforce and there are some products like 'MQX', 'ARC 600' etc

 

I am trying to get records through LIKE query like:

 

results = Database.query('select Id,Name,Product_Group__c from Product2 where Name Like :filterby OR Name Like \'%'+filterby+'%\'  order by ' + sortFullExp);

 

When I set filterby variable to "MQX" its not returning records :smileysad:... When I tried tro get records for "ARC"also givinig me NULL but when I ask for "600" then its returning fine also when I requested " MQX"  mean with one space as prefix also getting result but not getting exact match but getting like "Prodcut of MQX" etc......please have a look on following code

 

private void BindData(Integer newPageIndex)
    {
        try
        {
                string sortFullExp = sortExpression  + ' ' + sortDirection;
                searchText=sortFullExp;
                if(filterby == null || filterby == '')
                {                    
                      //searchText='Coming';
                }
                else if(filterby != '')    
                {
                       
                        results = Database.query('select Id,Name,Product_Group__c from Product2 where Name Like :filterby OR Name Like \'%'+filterby+'%\'  order by ' + sortFullExp);
                      
                      
                    
                }                         
    
            pageResults = new List<Product2>();
            Transient Integer counter = 0;
            Transient Integer min = 0;
            Transient Integer max = 0;
            if (newPageIndex > pageNumber)
            {
                min = pageNumber * pageSize;
                max = newPageIndex * pageSize;
            }
            else
            {
                max = newPageIndex * pageSize;
                min = max - pageSize;
                //min = (min <>
            }
            for(Product2 a : results)
            {    
                counter++;
                if (counter > min && counter <= max)
                    pageResults.add(a);
            }
            pageNumber = newPageIndex;
            if (pageResults == null || pageResults.size() <= 0)
            {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Data not available for this view.'));
               results=null;
               pageResults=null;
            }
        }
        catch(Exception ex)
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,ex.getMessage()));
        }
    }

 

I have 7000 products in my object. Please help me in this. I want to get actual records for LIKE query.. Please reply ASAP Thanks in advance.

I need help with the controller side of this custom button.  I have created a custom vf page that is similar to the view all button on Activity History.  I am trying to create a Back or Cancel button and I am not sure what the syntax should look like.  The vf page comes from a button on the Case related list on the Account page. So I am trying to go from a custom case page to a standard account page.

 

This is my custom controller.  I am not sure what to do in my account query so that when the Cancel method calls it the account page is returned.  Any help or suggestions would be greatly appreciated. thanks!

public class ViewAllIncidents {

public Account acct{
get{
if(acct == null){
acct = [SELECT a.id, a.name
FROM Account a
WHERE id =: apexpages.currentpage().getParameters().get('id')];
}
return acct;
}
set;
}

public ViewAllIncidents() {

this.theIncidents = [SELECT c.Account.Name, c.CaseNumber, c.Status, c.due_date__c, c.subject, c.Contact.Email, c.description
FROM Case c
WHERE c.AccountId = :ApexPages.currentPage().getParameters().get('acctId')];

}
public List<Case> theIncidents { get; set; }

public PageReference cancel() {
//cancel method to return to the account detail page
return new ApexPages.StandardController(acct).view();
}
}

 

 

 

  • August 06, 2009
  • Like
  • 0

Hello again!!

 

I have a VF Page where I show columns, something like this;

 

             <apex:column headervalue="Pool">{!item.Pool__c}</apex:column>
             <apex:column headervalue="Garage">{!item.Garage__c}</apex:column>
             <apex:column headervalue="Good Neighborhood">{!item.Neighborhood__c}</apex:column>

 

But It shows true or false. I want to see V if It's true, or X if It's false....

 

 

Any idea???

 

Thanks!!!!

Hello eveyone!!

 

I have done a custom link in Lead;

/apex/DataLeads

 

 

DataLeads is a .Page where I want to show the name and the phone of the lead, but I don't know how can I get the Id of the Lead.

 

I mean, In the Lead Jonh, I do click in the link and a pop-up (has to) show his name and phone

 

Any idea?!?

 

Thanks in advance!!

I've spent a good amount of time looking around trying to find whatever piece of semi-magical syntax I need to be able to get a PageReference to a tab of a standard controller.

 

On the forums I've found the reccomendation to just link to it's URL directly: https://salesforce_instance/001/o.

While that's the quick and easy way, it doesn't work with packages or code deployments, which the code I'm patching will someday be involved with.

 

So in short, I need a portable way of finding a pagereference to a standard controller, say the normal accounts tab. Anybody know an easy way?

Hi,

I have created a visualforce page and a have also create a controller class for it.
I have created a command button for 'Cancel' in the Visualforce page. The action refers to a pagereference method in the controller class.
The pagereference method performs the function of redirecting to a different page of my choice. Redirect is set to true.
I encounter a problem with this in one scenario.
There is an input field in the visualforce page which is a lookup to different object. If I type something in the text space instead of selecting from the list and then click on Cancel, it does not work it stays in the same page and throws an error. Once I delete the text the Cancel button works.
What is happening? How do I get the Cancel to work all times.

Thanks
Krishnadas
Steadfast Global
www.steadfastglobal.com

Hi, I'm completely new to developing in Apex and Visualforce, so please bear with my elementary question.

 

I have a simple repeat block in my Visualforce page:

 

<apex:repeat value="{!stagesStrLst}" var="eachstage" id="theRepeat">
      {!curStageNum} {!eachstage} {!stageStr}

      <br/>
</apex:repeat>

 

'stagesStrLst' is a String list obtained from a SOQL query in my Apex code (8 elements in the list).

'stageStr' is a String variable with the following get method:

get
{
   String blockStr;
   blockStr = '<div class="workarea"> ';
   blockStr += '<h3>' + curStage + '</h3>';
   blockStr += ' </div>';
           
   System.debug(curStageNum);

   curStageNum++;

   System.debug(curStageNum);

   return blockStr;   
}

 

'curStage' simply returns the element of 'stagesStrLst' of index 'curStageNum', which is set to 0 in the controller's constructor. Every time stageStr's get method is called, it should increment curStageNum.

 In other words, what I think it should output on my Visualforce page is

0 a a

1 b b

2 c c

3 d d

4 e e

5 f f

6 g g

7 h h

 

where a, b... are the string elements in the list.

 

However, I instead get

0 a a

0 b a

0 c a

0 d a

0 e a

0 f a

0 g a

0 h a

It's looping through stagesStrLst just fine, but it seems curStageNum is never being incremented properly. In fact, the system log shows that the debug statements I inserted only output once (though the second debug statement reveals that curStageNum did indeed get incremented to 1, but that's never shown in the Visualforce page).

 

I'm pretty confused about this behavior and was wondering if someone could please explain why my Visualforce page never shows my integer variable being incremented? This was just a small test project to try get myself to understand what I can and can't do with Visualforce/Apex before I tackle a bigger, more functional project.

 

Thank you.

  • July 30, 2009
  • Like
  • 0

Hi,

 

Can someone help, I keep getting the error:

System.DmlException: Insert failed. First exception on row 0 with id 00oS0000000AOgYIAW; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

But I am pretty sure that there is no Id specified in my insert call.

Here is my code:

 

 

public PageReference save() { List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>(); List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>(); for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){ for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){ if(revenueSchedule.get('Id') == null) revenueSchedulesToInsert.add(revenueSchedule); else revenueSchedulesToUpdate.add(revenueSchedule); } if(revenueSchedulesToUpdate.size() > 0) update revenueSchedulesToUpdate; if(revenueSchedulesToInsert.size() > 0) insert revenueSchedulesToInsert; } return Page.revenueScheduleView2; }

 

 

 

Hi,

 

In my lead object I have two field. email and emailoptout. I want to update all related lead and contact records when I update any lead and contact emailloptout field value. I tried to do so but it goes in infinite loop. Is there any way or through api we can check that record is already udpated or not?

 

Please guide.

Hi,

 

I am getting limit exceeded reeor while trying to access the site created by me. What could be the probable reason for this?

 

Thanks.

  • July 26, 2009
  • Like
  • 0

Hi,

 

I'm creating a Visualforce page for Sys Admins on which I would like be able to display a drop down of all Sites in the org if possible. From what I can tell, the Sites info is stored in the metadata but, unfortunately, it doesn't seem like there is a way to access this particular metadata from Apex.

 

Any ideas?

 

Thanks a lot,

Mike 

Hi,

 

I have created a UserDetail custom object. I tried to insert data into the object using binding.create() and passed the sObject. I got an error message stating "Only concrete SObject lists can be created ". How can acheive this task.

 

Thanks in Advance

  • July 23, 2009
  • Like
  • 0

Hello everyone & thanks again for a great forum. Your help and advice is always very appreciated!

 

I have written some code with a test method, but it is only showing up with 25% coverage. This is my first crack at writing tests, so I am not sure what I am missing. If someone could please help me understand what I am missing I would be really appreciative. 

 

Thanks!

Shannon

 

 

public class String_functions{
Opportunity opp;

public String_functions(ApexPages.StandardController controller) {
opp = (Opportunity)controller.getRecord();
opp = [select id, StageName, CloseDate, name,Special__c, Adders_Optional_Scope_of_Supply__c, Tender_Name_or_Reason_for_Quotation__c, Commissioning_Start_up_Training__c from opportunity where id = :opp.id];
}

public string getReasonText()
{
string paragraph = opp.Tender_Name_or_Reason_for_Quotation__c.replaceAll('\n','<br/>');
return paragraph;
}

public string getSpecialText()
{
string paragraph = opp.Special__c.replaceAll('\n','<br/>');
return paragraph;
}

public string getTrainingText()
{
string paragraph = opp.Commissioning_Start_up_Training__c.replaceAll('\n','<br/>');
return paragraph;
}

public string getAddersText()
{
string paragraph = opp.Adders_Optional_Scope_of_Supply__c.replaceAll('\n','<br/>');
return paragraph;
}


//******************
//Test Method
//******************
public static testMethod void TestString_functions() {

// Insert test Opportunity
Opportunity testOppty = new opportunity (
Name = 'Test Opportunity',
Amount = 5000,
StageName = 'Closed Won',
CloseDate = System.today(),
Tender_Name_or_Reason_for_Quotation__c = 'test\ntest2\ntest3\ntest4',
Commissioning_Start_up_Training__c = 'test\ntest2\ntest3\ntest4',
Special__c = 'test\ntest2\ntest3\ntest4',
Adders_Optional_Scope_of_Supply__c ='test\ntest2\ntest3\ntest4');
insert testOppty;

// Instantiate VisualForce Page
PageReference pg = Page.Quote;
Test.setCurrentPage(pg);
ApexPages.currentPage().getParameters().put('id', testOppty.id);

// Instantiate String_function controller
ApexPages.StandardController s = new ApexPages.standardController(new Opportunity());
String_functions qe = new String_functions(s);

// Test: getReason_Text
string paragraphTest1= qe.getReasonText();
System.assertEquals (paragraphTest1, 'test<br/>test2<br/>test3<br/>test4');

// Test: getSpecial_Text
string paragraphTest3= qe.getSpecialText();
System.assertEquals (paragraphTest3, 'test<br/>test2<br/>test3<br/>test4');

// Test: getTraining_Text
string paragraphTest2= qe.getTrainingText();
System.assertEquals (paragraphTest2, 'test<br/>test2<br/>test3<br/>test4');

// Test: getAdders_Text
string paragraphTest4= qe.getAddersText();
System.assertEquals (paragraphTest4, 'test<br/>test2<br/>test3<br/>test4');
}
}

//The End

 

The results of the test are below:

 

 

*** Beginning Test 1: String_functions.public static testMethod void TestString_functions() 20090720142314.487:Class.String_functions.TestString_functions: line 49, column 4: Insert: SOBJECT:Opportunity *** Beginning Workflow Evaluation User: Shannon Langan Start Time: 20090720142314.871 Starting All Rules Evaluation Starting evaluation of rule type Assignment Starting evaluation of rule type Response Starting evaluation of rule type Workflow [Opportunity: Test Opportunity 006S0000002eI82] Rule Name: Shipping Address Trigger type: ON_ALL_CHANGES Evaluating Workflow Entry Criteria: [Opportunity : Shipping Address equals null] Value found: null Criteria evaluates to true [Opportunity: Test Opportunity 006S0000002eI82] Rule Name: Order Approved Notification to MGMT Trigger type: ON_CREATE_OR_TRIGGERING_UPDATE Evaluating Workflow Entry Criteria: [Opportunity : Amount less than CAD 100000] AND [Opportunity : Order Status equals SOA Approved (Mgmt & Finance)] Value found: 5000 Value found: 1 Criteria evaluates to false [Opportunity: Test Opportunity 006S0000002eI82] Rule Name: Payment Terms Overide Default Values Trigger type: ON_CREATE_OR_TRIGGERING_UPDATE Evaluating Workflow Entry Criteria: [Opportunity : Payment Terms Override equals NULL] Value found: null Criteria evaluates to false [Opportunity: Test Opportunity 006S0000002eI82] Rule Name: Payment Term Change - ReApprove Trigger type: ON_CREATE_OR_TRIGGERING_UPDATE Evaluating Workflow Entry Criteria: Formula: IF(AND(Payment_Terms_Override__c<> NULL, NOT(ISPICKVAL(Order_Status__c,"Not Submitted"))),true,false) Value(s) Found: Order_Status__c=Not Submitted, Payment_Terms_Override__c=null Criteria evaluates to false Spooling All Immediate Actions [Opportunity: Test Opportunity 006S0000002eI82] Field Update Field: Opportunity: Shipping Address Value: , , , , Ending All Rules Evaluation Bulk Execute all Immediate Actions Starting evaluation of rule type Escalation End Time: 20090720142314.921 *** Ending Workflow Evaluation20090720142314.487:Class.String_functions.TestString_functions: line 49, column 4: DML Operation executed in 381 ms 20090720142314.487:Class.String_functions.: line 6, column 11: SOQL query with 0 rows finished in 6 ms System.QueryException: List has no rows for assignment to SObject Class.String_functions.: line 6, column 11 Class.String_functions.TestString_functions: line 58, column 26 Cumulative resource usage: Resource usage for namespace: (default) Number of SOQL queries: 1 out of 100 Number of query rows: 0 out of 500 Number of SOSL queries: 0 out of 20 Number of DML statements: 1 out of 100 Number of DML rows: 1 out of 500 Number of script statements: 10 out of 200000 Maximum heap size: 0 out of 1000000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10 Number of fields describes: 0 out of 10 Number of record type describes: 0 out of 10 Number of child relationships describes: 0 out of 10 Number of picklist describes: 0 out of 10 Number of future calls: 0 out of 10 Number of find similar calls: 0 out of 10 Number of System.runAs() invocations: 0 out of 20 Total email recipients queued to be sent : 0 Stack frame variables and sizes: Frame0 *** Ending Test String_functions.public static testMethod void TestString_functions()

 

 

 

 

 

Message Edited by Slangan on 07-20-2009 07:33 AM

How can we write a testcase for this class.

public class test

public class createBasicSegmentResponse {

 

 

   public Long return_x;

 

 

   private String[] return_x_type_info = new String[]{'return','http://www.w3.org/2001/XMLSchema','long','1','1','false'};

 

 

   private String[] apex_schema_type_info = new String[]{'http://salesforce.com/','false','false'};

 

 

   private String[] field_order_type_info = new String[]{'return_x'};

 

 

   }

}

 

Please help me out as i am able to cover the code for normal classes but its getting diffulct to the classes generated from wsdl.

 

 

Thanks.

 

 

  • July 20, 2009
  • Like
  • 0

Hello

 

can anyone please throw some ideas..on how to solve the below issue ....many thanks in advance


Right now I have problems in writing test case when I want to deploy this class to the production. could you help me with writing the test case or example for the test case for the class below.

  

public class UpdateItemQuoteCurrency {

 

    // Constructor - this only really matters if the autoRun function doesn't work right

    private final Quotation__c q;

    public UpdateItemQuoteCurrency(ApexPages.StandardController stdController) {

        this.q = (Quotation__c)stdController.getRecord();

    }

   

    // Code we will invoke on page load.

    public PageReference autoRun() {

 

        String theId = ApexPages.currentPage().getParameters().get('id');

 

                Quotation__c Quote = [select CurrencyIsoCode from Quotation__c where Id= :theId];

 

        if (theId == null) {

            // Display the Visualforce page's content if no Id is passed over

            return null;

        }

 

        List<Item__c> itemsToUpdate = new List<Item__c>();

       

        List<Item__c> items = new List<Item__c>([SELECT Id FROM Item__c WHERE Quotation_No__c = :theId]);

        for (Item__c item :  items) {

             item.CurrencyIsoCode = Quote.CurrencyIsoCode;

             itemsToUpdate.add(item);            

        }

        update(itemsToUpdate);

        return null;

    } 

}

I have three customer objects created. Where the actual data entry is done and bill is processed.

 

Now i want to allow CUSTOMER to see those bill as part of the website, and also have the option of hyperlink, when they can drill down the data.

 

Kindly note, the data is to be pulled from all the 3 custom objects.

 

Now if i want to create such site using VisualForce. How to go about? And also i have one doubt, do i need to associate the visual page with customer object like STANDARD CONTROLLER = "Position__c").

 

Would be a great help if you can share some examples or steps in general.

 

Thanks in advance

Hello,

I am writting a trigger to rollup a field (Type) from the Opportunity object on Account. I get the error "Didn't understand relationship 'Opportunities' error". I am out of ideas. Any clue?

 

 

trigger UpdateMembershipType on Opportunity (after delete, after insert, after update) { set<ID> orgIDs = new Set<ID>(); if(Trigger.isInsert) { for(Opportunity o : System.Trigger.new){ orgIDs.add(o.AccountId); } Organization[] orgs = new List<Organization>(); orgs = [select Id, (select Type, RecordType.Name from Opportunities where IsWon = TRUE order by CloseDate Desc limit 1 ) from Organization where ID in :orgIDs ]; Opportunity[] os = new List<Opportunity>(); Map<Id, Opportunity[]> orgopp = new Map<Id, Opportunity[]>(); for (Organization eachOrg: orgs){ orgopp.put(eachOrg.Id, eachOrg.Opportunities); } Organization[] updatedOrganizations = new List<Organization>(); Opportunity[] opps = new List<Opportunity>(); for (Organization o : orgs ){ opps=orgopp.get(o.Id); for(Opportunity opty : opps) { o.Type__c=opty.Type; } updatedOrganizations.add(o); } if(updatedOrganizations.size()>0) {update updatedOrganizations;}}

 

 Thanks!

Pierre 

 

 

Hey,

 

I have an application that works very well in unpackaged, or unmanaged packaged code. However if I upload it to a managed package then the JavaScript remoting calls fail. I know this because nothing happens in my app and the following appears in the console:

 

 

Here I notice that it's not prepending my package namespace, a bug from managed packaging when it originally came out! Having a look at the sourcecode confirms this:

 

 

I've FBI'ed the code out but there's no namespace to the doubleunderscores in this code.

 

This leads me to believe I've uncovered a bug which makes me sad since my app is about 80% JavaScript. Any chance I'm doing something incorrectly and this isn't a bug?

 

Wes

Hello

 

I have a form that contains an inputtext and a commandlink that submits the form when clicked. I have noticed that if I press the enter key after entering text in the inputtext the page just refreshes. If I change the commandLink to a commandButton the form does submit, but I have certain reasons for using commandLink, so this is not feasible.

 

I have noticed this behaviour in another form on a seperate page too. Any ideas?

 

Wes 

Hey

 

I've recently changed my email address and went through the confirmation process. Within my profile it still says 

 

E-Mail Verification Status
Not Verified

 

Is this area broken at the moment?

 

Cheers,

Wes

Hello

 

I'm having an issue rerendering a pageblocktable after a record is inserted via a simple modal javascript/visualforce form. The strange thing is that I can see that the method that populates the table is called after the insert (I've checked the debug log) and that the number of rows returned is 1 more than before the insert. If I refresh the page it displays the record. The code follows:

 

VisualForce

 

<apex:page controller="RecipeController"> <!-- Javascript removed to ease readability --> <!-- datatable with list --> <apex:sectionHeader title="Recipes"/> <apex:form > <apex:actionStatus id="status" startText="Updating..."></apex:actionStatus> <apex:pageBlock title="Current Recipes" id="recipeList"> <apex:pageblocktable value="{!recipes}" var="recipe"> <apex:column > <apex:facet name="header">Name</apex:facet> <apex:outputfield value="{!recipe.name}"/> </apex:column> <apex:column > <apex:facet name="header">Short Description</apex:facet> <apex:outputfield value="{!recipe.ShortDescription__c}"/> </apex:column> <apex:column > <apex:facet name="header">Rating</apex:facet> <apex:outputfield value="{!recipe.Rating__c}"/> </apex:column> </apex:pageblocktable> <apex:pageblockbuttons location="top"> <apex:commandButton value="New" onComplete="YAHOO.recYippee.showMe();" rerender="recipeEdit"/ > <apex:commandbutton value="Refresh" status="status"/> </apex:pageblockbuttons> </apex:pageBlock> </apex:form> <!-- Modal window opened by javascript --> <div id="EditNew" style="display: none" > <div class="hd"> <apex:outputText value="Recipe Details" /> </div> <div class="bd"> <apex:actionregion > <apex:form id="RecipeEdit"> <apex:pageBlock title="List of stored recipes"> <apex:pageblocksection > <apex:inputField value="{!r.name}"/> <apex:inputField value="{!r.ShortDescription__c}" /> <apex:inputField value="{!r.Ingredients__c}" /> <apex:inputField value="{!r.CookingInstructions__c}" /> <apex:inputField value="{!r.CostPerPerson__c}" /> </apex:pageblocksection> <apex:pageblockButtons location="bottom"> <apex:commandButton value="Save" action="{!saveRecipe}"/> <apex:commandButton value="Cancel" immediate="true" oncomplete="YAHOO.recYippee.hideMe();" /> </apex:pageblockButtons> </apex:pageBlock> </apex:form> </apex:actionregion> </div> <div class="ft" style="font-size: 10px;"> <apex:outputPanel layout="block"> Please click the 'Save' button to store the recipe or cancel to return to the previous page. </apex:outputPanel> </div> </div> </apex:page>

 

 Apex Code

 

public class RecipeController{ private Recipe__c recipe = new Recipe__c(); private List<Recipe__c> recipes = new List<Recipe__c>(); public Recipe__c r{get{return recipe;}set{recipe=value;}} public RecipeController(){} public List<Recipe__c> getRecipes(){ recipes = [SELECT name, shortDescription__c, rating__c, costPerPerson__c, cookingInstructions__c, ingredients__c FROM recipe__c]; return recipes; } public void setRecipes(){} public PageReference SaveRecipe(){ upsert r; return null; } }

 

The javascript is not the issue, as I've used it in other places and it works fine. Any ideas?

 

 

 

Hello

 

I'm having a curious issue that I'm sure there's a more elegant solution for. As an example:

 

 

public class a { B bee = new B(); insert bee; a.b__c = bee.id; }

 

 I now cannot do something along the lines of
   
    a.b__r.name = 'test';

 
I have to either fetch the associated object fields via SOQL or associate the object directly  e.g.


    a.b__r = bee;


If I use this approach though and then 'insert a', the objects will no longer be related. Therefore I have to assign the id and then associate the relationship with the 'b' object if I wish to use the fields via their relationship with 'a'.

 

I know this is a strange situation, but I'm trying to maintain 'session' data and am doing this for persistence.

 

Any ideas about a more elegant solution?

 

Wes

 

 

Hello

 

I've looked around the forums and can't find something that answers my question exactly. Basically I'm trying to send an email to a 'contact' concerning a job application. I've created a master-detail field on the contact object linking to the necessary job application, but when the email is sent, the details for the job application (relatedTo fields) are blank.

 

The code follows:

 

(Here a create a temp contact record to get around only being able to send to contacts)

 

public class SendEmail { Job_Req__c jr; public String email {get;set;} public SendEmail(ApexPages.StandardController controller) { jr = (Job_Req__c)controller.getSubject(); } public void sendEmail(){ Contact c = new Contact(lastName='friend',email=this.email,jobRequisition__r=jr); insert c; Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTemplateId('00X80000001Bm2m'); mail.setTargetObjectId(c.id); Messaging.sendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail}); for ( Messaging.sendEmailResult result : results ) { if ( !result.isSuccess () ) { System.debug ( result ); } }

  delete c;

} }

 

 

<messaging:emailTemplate subject="I found this great job for you!" recipientType="Contact" relatedToType="Job_Req__c"> <messaging:plainTextEmailBody > Hello Your friend thought you may be interested in the following job: Reference: {!relatedTo.id} Title: {!relatedTo.Job_Title__c} Description: {!relatedTo.Job_Description__c} Kind Regards, The Team </messaging:plainTextEmailBody> </messaging:emailTemplate>

 

Wes

 

 

 

 

Hello

 

I'm getting a strange error with abbreviated getters and setters.. but when I write the full getters/setters the code works perfectly.

 

First, the code that works.

 

Extension

public class helper { SessionData__c s; public helper(ApexPages.StandardController controller) { s= new SessionData__c(); } public SessionData__c getS(){ return s; } public void setS(SessionData__c value){ s= value; } public void add(){ insert s; } }

 

Apex page

 

<apex:page standardController="SessionContainer__c" extensions="helper"> <!-- Begin Default Content REMOVE THIS --> <h1>Congratulations</h1> This is your new Page: session <!-- End Default Content REMOVE THIS --> <apex:pageblock> <apex:pageBlockSection> <apex:form > <apex:inputField value="{!S.name}"/> <apex:commandButton action="{!add}" value="Save"/> </apex:form> </apex:pageBlockSection> </apex:pageblock> </apex:page>

 

 

As I said, the above code works. Now should I change the controller extension so:

 

public class helper { SessionData__c s{get;set;} public helper(ApexPages.StandardController controller) { s= new SessionData__c(); } public void add(){ insert s; } }

 

 

I get the following error:

 

Could not resolve the entity from <apex:inputField> value binding '{!S.name}'. inputField can only be used with SObject fields.

 

Any ideas?

Hello

 

I have found many articles saying I have to speak to support to have this feature enabled, but no where does it tell me how to get ahold of support. Does anyone have the details?

 

Wes

Hello

 

Is it possible to package Force.com sites? I cannot see any simple way to do it besides packaging the pages etc. and then setting up sites post installation.

Hello

 

I'm having a strange issue, let me start with my code:

 

VisualForce:

 

<apex:commandButton action="{!sendEmail}" value="Send Email" id="emailButton"> <apex:param name="frmParam" assignTo="{!frm}" value="{!$User.Email}"></apex:param> <apex:param name="toParam" assignTo="{!to}" value="{!Application__c.Email__c}"></apex:param> <apex:param name="subjParam" assignTo="{!subject}" value="Your application for position no. {!Application__c.Job_Requisition__r.name}"></apex:param> </apex:commandButton>

 Controller:

 

public class emailApplicant { private Application__c app; private String jobRef = null; public string frm; public string to; public string subject; public string emailBody; public string getFrm(){ return frm; } public string getTo(){ return to; } public string getSubject(){ return subject; } public string getEmailBody(){ return emailBody; } public void setFrm(string value){ frm = value; } public void setTo(string value){ to = value; } public void setSubject(string value){ subject= value; } public void setEmailBody(string value){ emailBody=value; } public emailApplicant(ApexPages.StandardController controller){ app = (Application__c)controller.getSubject(); //Id id = System.currentPageReference().getParameters().get('id'); jobRef = [SELECT name FROM job_req__c WHERE id = :app.job_requisition__c].name; } public Application__c getAppInfo(){ return app; } public String getJobRef(){ return jobRef; } public PageReference sendEmail(){ PageReference p = new PageReference('https://na6.salesforce.com/'+app.job_requisition__c); p.setRedirect(true); Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String [] toAddresses = new String[]{to}; mail.setToAddresses(toAddresses); mail.setReplyTo(frm); mail.setSenderDisplayName(frm); mail.setSubject(subject+to+frm); mail.setPlainTextBody(emailBody); Messaging.sendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail}); for ( Messaging.sendEmailResult result : results ) { if ( !result.isSuccess () ) { System.debug ( result ); return p; } } return p; } }

 

The issue is that if I use a commandbutton in the VisualForce page I get the following error:

 

 

System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : null

 

This value is not null, and I can attest to this because if I simply change the commandButton into a commandLink, the result is positive. Could someone tell me if there is a bug, or if I am using the component incorrectly.

 

Thanks,

Wes

 

 

Hello

 

As far as iI can tell there's not straight forward Apex way to to alter the values in a picklist(bummer). Is there some alternative? Like destroying the picklist and then creating a new one with updated values(not ideal)..?

 

 

Wes

Hello

 

Is it possible to generate Apex code from the metadata API and including it in my Force.com IDE eclipse project so that I have Apex based access to the metadata?

 

Specifically I'm looking to dynamically update label - value pairs in picklists.

Hello

 

Is there a way to programmatically get the URL for a VisualForce page? Will it always be '/apex/MyPage'?

 

Wes

Hello

 

I am packaging an application with a custom Home Page Layout. I also set the necessary profile in the application to use the custom Home Page Layout and then include the profile settings in the package.

 

When installing the package I select the mapping to use, but when the client logs on they still only see the default Home Page.

 

Do I manually have to tell the relevant profiles to use the custom Home Page Layout after installation? It would really suck if I did.

Hey,

 

I have an application that works very well in unpackaged, or unmanaged packaged code. However if I upload it to a managed package then the JavaScript remoting calls fail. I know this because nothing happens in my app and the following appears in the console:

 

 

Here I notice that it's not prepending my package namespace, a bug from managed packaging when it originally came out! Having a look at the sourcecode confirms this:

 

 

I've FBI'ed the code out but there's no namespace to the doubleunderscores in this code.

 

This leads me to believe I've uncovered a bug which makes me sad since my app is about 80% JavaScript. Any chance I'm doing something incorrectly and this isn't a bug?

 

Wes

 

Hello...I consolidated 6 plain text email templates into 1 using conditional mark up (CASE) thus rendering the appropriate phrasing for the particular instance of the email. This worked like a charm and enabled me to have one CommandButton on a related VisualForce page instead of the 6 I had previously had.
Unfortunately the client made a follow up request: consolidate two of them further into one email but with much less content. On the surface it didn’t sound like too much work until I realized the only way to still use the same template was to obscure whole sections of text for this final scenario.
 
Below is a snippet of what I’ve been testing in the plain text template:

 
{!CASE(Session__c.Email_Notification__c, "FIRST APPOINTMENT", “START OF TEST”, “START OF TEST”)}
{!CASE(Session__c.Email_Notification__c, "FIRST APPOINTMENT", “”, “Please pay special attention to instructions below.”)}

{!CASE(Session__c.Email_Notification__c, "FIRST APPOINTMENT", “”, “Instructions:”)}
{!CASE(Session__c.Email_Notification__c, "FIRST APPOINTMENT", “”, “In lieu of a tire blow out, keep your ipad strapped in with a seat belt. Rear seating is always preferable for an ipad. But enough about Pat Metheny.”)}
{!CASE(Session__c.Email_Notification__c, "FIRST APPOINTMENT", “END OF TEST”, “END OF TEST”)}

 

The above code renders great for records that are not flagged “FIRST APPOINTMENT” e.g

START OF TEST
Please pay special attention to instructions below.

Instructions:
In lieu of a tire blow out, keep your ipad strapped in with a seat belt. Rear seating is always preferable for an ipad. But enough about Pat Metheny.
END OF TEST

But it literally puts white spaces for records that are flagged "FIRST APPOINTMENT", so they render as:
 
START OF TEST
 
 
 
 
END OF TEST

 
I am looking for a way to completely collapse white space as 75% of the template ends up rendering as white space for the FIRST APPOINTMENT scenario.
 
I also tested the following:
 
 
{!IF(ISPICKVAL(Session__c.Email_Notification__c , "FIRST APPOINTMENT"), "random1", NULL)}
{!IF(ISPICKVAL(Session__c.Email_Notification__c , "FIRST APPOINTMENT"), NULL, "random2")}
{!IF(ISPICKVAL(Session__c.Email_Notification__c , "FIRST APPOINTMENT"), "random3", NULL)}

The code above renders as:

 
random1
 
random 3

 
Suggestions greatly appreciated!

 

Hello

 

I want to authenticate Customer Portal users via the API from a Java platform, but I'd like to hand the user over to a Salesforce customer portal without having to re-authenticate. I've thought of some trickery that might work, but I wondered if there might be a direct way to pass the session id to some Force.com functionality (exposed as a web service perhaps) and have the user seamlessly continue their journey.

 

Wes

I want to write code that does stuff based on the choices in a picklist. I know all the choices in a picklist and of course I could hardcode it, but I want to be able to edit the picklist choices without breaking my code.

 

Example:

 

Let's say I have a custom object that has a picklist value named "Mood" with the options of "Happy", "Sad" and "Fine". Next I have a visualforce page with a table with totals for each mood.

 

I could easily write code in the VF controller that pulls all my records, and iterates through each with a if statement that checks the mood and totals them.

 

The problem there is if I ever add another mood to the picklist, I would then have to edit my vf page and the controller apex to reflect the additional moods.

 

It would be a lot nicer to be able, in apex, to get a list of the picklist options and then iterate through those and run the tallying code.

 

 

This is not my specific usecase, but it illustrates it nicely. Could someone out there help me out? 

Oh, and FYI, I through this code in there:

 

 

schema.describefieldresult f = schema.sobjecttype.my_custom_object__c.fields.my_custom_field__c;

 

but I get an error page saying, System.Exception: Too many fields describes: 11 

 

 

We have a Visual Force page which contains three tabs and each tab has 3-4 tabPanels. Here in each tabPanel we have invoked one component which has some custom functionality. We have used actionRegion, switchType, re-render (Ajax) attributes also and tried to debug our code, there I found that when I am doing some action on one component queries of other components are also getting fired. And getting a exception Too many SOQL queries.

 

Any pointer or suggestion for get rid of this problem.

  • August 14, 2009
  • Like
  • 0

I created a custom object AccountContactAssociation that servers as a many-to-many join. It has two custom Master-Detail fields. 

 

One is named Account and is a Master-Detail(Account).

One is named Contact and is a Master-Detail(Contact).

 

I'm trying to create a trigger as follows:

 

 

trigger AccountContactAssociationTrigger on AccountContactAssociation__c (after insert) {

AccountContactAssociation__c ac = Trigger.new[0];

 

  

  ac.Contact.FirstName = ac.Account.Name;

 

 

 

 

What I am basically trying to do is to access a field in the Account that is referenced by the junction object (in this case string Name) and assign it to a FirstName field in the referenced Contact object.

 

 

The above code does not compile, and I have a hard time figuring how to access the abovementioned fields.

 

 

I would greatly appreciate any suggestions.

 

Thanks! 

Hello,

 

Sometimes my System Log does not connect to my Org. Meaning, nothing prints. I try to load a page with a controller that simply writes a debug statement out to the log but nothing shows up at all.

 

It's as if the log is not even connected.

 

Does anyone have any idea why this is happening? Is there a setting somewhere I need to turn on?

 

Thanks!

 

Kevin

I'm getting this error:

System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Subject: data value too large: Review final judgement; Teleconference with opposing counsel to correct Final Judgement (max length=80): [Subject]

Why is this error occurring, how can I fix these errors? Do I have to manually put a Check for Field length in APEXclasses when saving records? If so, That would be very tedious :( .. is there amny better idea to fix this issue? :)
  • August 13, 2009
  • Like
  • 0

Hi,

I have created a before insert trigger on a custom object Object1__c which will create records for another custom object Object2__c. There is a before insert trigger in Object2__c that will create records for the 3rd custom object Object3__c. Earlier I used to get governor limit errors on SOQL queries as they were inside a loop. Now I keep getting error on List size being above 1000. Could I catch and exception and show it as an error in the visualforce page. How do I caluclate for the limit.

Thanks

Krishnadas

www.steadfastglobal.com 

I am trying to get a handle on how to get past an error when trying to build a package.  The error is:

 

Package upload error. There are problems that prevent this package from being uploaded.
Average test coverage across all Apex Classes and Triggers is 27%, at least 75% test coverage is required.

 

I am puzzled about the 27% because when I run my packaged Apex Classes (I don't have any Triggers) individually I get 85% coverage.  See below.

 

WSContoller2 - 81%
setInTestMethod - 100%
wwwMyWebService - Can't run a test here.  This is a WSDL generated web service call out.

 

Is the 27% all Classes on my development site?  even if they aren't included in my package?

 

Besides the 3 classes above that I wrote, I show the following two Apex Classes that where on my development account when it was first established.  I think they are used for the "Start Here" tab.  Do they count against my code coverage percentages?
    startHereController
    XMLDom

Message Edited by George1313 on 08-11-2009 07:22 PM

Hello everyone!!

 

I'm trying to do a select. I have the object person, where I have two text fields; howAmI__c and SuperWord__c

 

 by default: SuperWord__c='pro-active'

 

 

 I want to select people with the SuperWord inside of the field  howAmI__c

 

for instead, a person with howAmI__c='I am a really pro-active person'

 

I think It's something like:

 

select  howAmI__c, SuperWord__c from Person__c where howAmI__c=%SuperWord__c%

 

but it doesn't work!!

 

Any Idea?!?!?

 

 

Thanks in advance!!!

Hi,

 

I'm totally newbie on Sales force, and I'm trying something that should be easy.

From a Case, I want to manage a new type of object, named SMS

I created the object and now I want to customize the page, with APEX

 

So, I created a class

 

global class NetsizeClass { private SMS__c currentSms; public SMS__c getSms() { return currentSms; } public NetsizeClass(ApexPages.StandardController controller) { if (currentSms == null) currentSms = new SMS__c(); string sms_id = System.currentPageReference().getParameters().get('id'); if (sms_id == null || sms_id == '') { // New SMS currentSms.message__c = 'New SMS '; } else currentSms= [select message__c, status__c, case__c, contact__c from SMS__c where id = :sms_id]; } public void SendSMS() { if (currentSms.id == null || currentSms.id == '')
// New SMS
else
// Existing SMS

upsert currentSms;
... } }

 

and a Page, that overload the 'New' button in my SMS object

 

<apex:page standardController="SMS__c" extensions="NetsizeClass"> <apex:sectionHeader title="New SMS" subtitle=""/> <apex:form> <apex:pageBlock title="SMS information"> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}"/> <apex:commandButton value="Send SMS" action="{!SendSMS}"/> </apex:pageBlockButtons> <TABLE> <TR> <TD><B>Message</B></TD> <TD><apex:inputField value="{!sms.Message__c}" id="smsMsg"/></TD> </TR> <TR> <TD><B>Contact</B></TD> <TD><apex:inputField value="{!sms.Contact__c}" id="smsContact"/></TD> </TR> <TR> <TD><B>Case</B></TD> <TD><apex:inputField value="{!sms.Case__c}" id="smsCase"/></TD> </TR> <TR> <TD><B>Case 2</B></TD> <TD><apex:inputField value="{!SMS__c.Case__c}" id="smsCase2"/></TD> </TR> </TABLE> <br/> </apex:pageBlock> </apex:form> </apex:page>

 

It works fine, when I am on a Case, I see the button 'New SMS' (I customized the layout), that open my custom APEX page.

But I just don't know how to retreive the parent Case information (I'm using the 2 fields Case for my tests):

- the field smsCase is empty, and it's normal as it is linked to {!sms.Case__c} and sms is created in the constructor. But I read in some forums that it's the only way to retreive later the updated values (I want to customize the Edit and View page)

- the field smsCase2 is filled with the id of my Case, but I don't know how to retreive this data from my page.

 

I also would like to retreive automatically the contact linked in the parent Case, to link it to the SMS. But I think it should be easy to do when I'll have the ID of my Case.

 

I'm sure that I'm missing something but I searched in so much forums that I'm starting to mix-up everything.

Any help will be welcome :)

 

Thanks

Hervé

 

 

  • August 11, 2009
  • Like
  • 0

Hello,

 I am using the below code to redirect to the standard salesforce pages as:

 

    public PageReference Save()

    { 

String newPageUrl = 'https://ap1.salesforce.com/701/o';

   PageReference newPage = new PageReference(newPageUrl);

   newPage.setRedirect(true);

   return newPage; 

    } 

 This piece of code helps in navigating the page to campaign default page.Here the url-"https://ap1.salesforce.com/701/o" is the campaigns default page url for my account.

 

Instead of passing the complete url is there any way to redirect to sandard campaign page in pageReference method. 

 

Thanks,

shaan 

  • August 11, 2009
  • Like
  • 0

I have Product object in salesforce and there are some products like 'MQX', 'ARC 600' etc

 

I am trying to get records through LIKE query like:

 

results = Database.query('select Id,Name,Product_Group__c from Product2 where Name Like :filterby OR Name Like \'%'+filterby+'%\'  order by ' + sortFullExp);

 

When I set filterby variable to "MQX" its not returning records :smileysad:... When I tried tro get records for "ARC"also givinig me NULL but when I ask for "600" then its returning fine also when I requested " MQX"  mean with one space as prefix also getting result but not getting exact match but getting like "Prodcut of MQX" etc......please have a look on following code

 

private void BindData(Integer newPageIndex)
    {
        try
        {
                string sortFullExp = sortExpression  + ' ' + sortDirection;
                searchText=sortFullExp;
                if(filterby == null || filterby == '')
                {                    
                      //searchText='Coming';
                }
                else if(filterby != '')    
                {
                       
                        results = Database.query('select Id,Name,Product_Group__c from Product2 where Name Like :filterby OR Name Like \'%'+filterby+'%\'  order by ' + sortFullExp);
                      
                      
                    
                }                         
    
            pageResults = new List<Product2>();
            Transient Integer counter = 0;
            Transient Integer min = 0;
            Transient Integer max = 0;
            if (newPageIndex > pageNumber)
            {
                min = pageNumber * pageSize;
                max = newPageIndex * pageSize;
            }
            else
            {
                max = newPageIndex * pageSize;
                min = max - pageSize;
                //min = (min <>
            }
            for(Product2 a : results)
            {    
                counter++;
                if (counter > min && counter <= max)
                    pageResults.add(a);
            }
            pageNumber = newPageIndex;
            if (pageResults == null || pageResults.size() <= 0)
            {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Data not available for this view.'));
               results=null;
               pageResults=null;
            }
        }
        catch(Exception ex)
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,ex.getMessage()));
        }
    }

 

I have 7000 products in my object. Please help me in this. I want to get actual records for LIKE query.. Please reply ASAP Thanks in advance.